the opengl shading language - amd€¦ · mat3 m3[2]; v3[0] // is a vec3 v3[0][0] // is a float...

Post on 09-Jul-2020

3 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1

The OpenGL Shading Language

Bill Licea-KaneATI Research, Inc.

2

OpenGL Shading LanguageToday

• Brief History• How we replace Fixed Function• OpenGL Programmer View• OpenGL Shaderwriter View• Examples

3

OpenGL Shading LanguageToday

• Brief History• How we replace Fixed Function• OpenGL Programmer View• OpenGL Shaderwriter View• Examples

4

Brief History1968

“As far as generating pictures from data is concerned, we feel the display processor should be a specialized device, capable only of generating pictures from read-only representations in core.”

[Myer, Sutherland] On the Design of Display Processors.[Myer, Sutherland] On the Design of Display Processors.Communications of the ACM, Volume 11 Number 6, June, 1968Communications of the ACM, Volume 11 Number 6, June, 1968

5

Brief History1978THE

PROGRAMMINGLANGUAGE

[Kernighan, Ritchie] The C Programming Language[Kernighan, Ritchie] The C Programming Language19781978

6

Brief History1984

“Shading is an important part of computer imagery, but shaders have been based on fixed models to which all surfaces must conform. As computer imagery becomes more sophisticated, surfaces have more complex shading characteristics and thus require a less rigid shading model."

[Cook] Shade Trees[Cook] Shade TreesSIGGRAPH 1984SIGGRAPH 1984

7

Brief History1985

“We introduce the concept of a Pixel Stream Editor. This forms the basis for an interactive synthesizer for designing highly realistic Computer Generated Imagery. The designer works in an interactive Very High Level programming environment which provides a very fast concept/implement/view iteration cycle."

[[PerlinPerlin] An Image Synthesizer] An Image SynthesizerSIGGRAPH 1985SIGGRAPH 1985

8

Brief History1990

“A shading language provides a means to extend the shading and lighting formulae used by a rendering system."…"…because it is based on a simple subset of C, it is easy to parse and implement, but, because it has many high-level features that customize it for shading and lighting calulations, it is easy to use."

[[HanrahanHanrahan, Lawson] A Language for Shading and Lighting Calculations, Lawson] A Language for Shading and Lighting CalculationsSIGGRAPH 1990SIGGRAPH 1990

9

Brief HistoryJune 30, 1992

“This document describes the OpenGL graphics system: what it is, how it acts, and what is required to implement it.”

“OpenGL does not provide a programming language.…Programmability would conflict with keeping the API close to the hardware and thus with the goal of maximum performance.”

[Segal, [Segal, AkeleyAkeley] The OpenGL Graphics System: A Specification (V 1.0) June 30, 1] The OpenGL Graphics System: A Specification (V 1.0) June 30, 1992992

[Segal, [Segal, AkeleyAkeley] The Design of the OpenGL Graphics Interface, 1994] The Design of the OpenGL Graphics Interface, 1994

10

Brief HistoryAugust 23, 1993

Digital Equipment will begin shipping its first OpenGL product next Monday as part of the Open3D 2.0 layered product for Alpha AXP OSF/1....

--John Dennis – OpenGL Project Lead

[Dennis] [Dennis] comp.graphics.openglcomp.graphics.opengl19931993--0808--1919

11

Brief HistoryOctober 1993

billa@entropy.sps.mot.com (William C. Archibald) writes:

|> 1)Quite a few modern rendering techniques and renderers|> support shader function calls at arbitrary points|> across a surface being rendered. ... What I would|> _like_ to do is call the shader at visible|> (front-facing) points. Is there _any_ way to do|> this kind of thing in OpenGL?

Not with the current API. One could extend OpenGL in this manner...

[[AkeleyAkeley] ] comp.graphics.openglcomp.graphics.opengl19931993--1010--1313

12

Brief HistoryRecent

• August 2001, SIGGRAPH OpenGL BOF– 3DLabs calls for "programmable" OpenGL

• June 2002, OpenGL ARB– ATI chairs arb-gl2 workgroup

13

Brief HistoryRecent

• June 2003, OpenGL ARB– ARB approves OpenGL Shading Language

• March 2004, OpenGL ARB– Unanimous roadmap to core OpenGL 2.0

14

OpenGL Shading LanguageToday

• Brief History• How we replace Fixed Function• OpenGL Programmer View• OpenGL Shaderwriter View• Examples

15

[[KempfKempf, Frazier] OpenGL Reference Manual (2, Frazier] OpenGL Reference Manual (2ndnd Edition)Edition)www.opengl.orgwww.opengl.org

16

OpenGL Fixed FunctionVertex

TransformTransform[MVP],[MV],[MV][MVP],[MV],[MV]--TT

LightingLighting[0,1][0,1]

[0,1][0,1]

TexgenTexgen TextureTextureMatrixMatrixnn

ColorColorSecondaryColorSecondaryColor

TexCoordTexCoordnn

EdgeFlagEdgeFlag

NormalNormal

Vertex (object)Vertex (object)

TexCoordTexCoordnn

EdgeFlagEdgeFlag

Vertex (eye)Vertex (eye)

Vertex (clip)Vertex (clip)

FrontColorFrontColorBackColorBackColor

FrontSecondaryColorFrontSecondaryColorBackSecondaryColorBackSecondaryColor

17

OpenGL Vertex Shader

AttributeAttributenn

Attribute1Attribute1

Attribute0Attribute0

Attribute2Attribute2

EdgeFlagEdgeFlag

TemporariesTemporaries

VertexVertexShaderShader

UniformUniform

EdgeFlagEdgeFlag

TextureTexture

……

VaryingVaryingnn

Varying1Varying1

Varying0Varying0

Varying2Varying2……

ClipVertexClipVertex

PositionPosition

PointSizePointSize

18

Post Vertex Shader"After lighting" Clamp

EdgeFlagEdgeFlag

VaryingVaryingnn

ClipVertexClipVertex

PositionPosition

PointSizePointSize

FrontColorFrontColorBackColorBackColor

FrontSecondaryColorFrontSecondaryColorBackSecondaryColorBackSecondaryColor

EdgeFlagEdgeFlag

VaryingVaryingnn

ClipVertexClipVertex

PositionPosition

PointSizePointSize

FrontColorFrontColorBackColorBackColor

FrontSecondaryColorFrontSecondaryColorBackSecondaryColorBackSecondaryColor

[0,1][0,1]

[0,1][0,1]

19

OpenGL Fixed FunctionRasterization

ClipVertexClipVertex

PositionPosition PrimitivePrimitiveAssemblyAssembly

FlatshadeFlatshadeVaryingVaryingnn

Culling orCulling orClippingEdgeFlagEdgeFlag Clipping

PointPointLineLine

PolygonPolygonRasterization

FaceFaceProcessingProcessing

VaryingVaryingnn

CoordCoord

Rasterization

Pixel RectanglePixel RectangleBitmapBitmap

Rasterization

RasterPosRasterPos

VaryingVaryingnn Rasterization

20

OpenGL Fixed FunctionFragment

FrontFacing

TexTexnn

TETEnn

SumSum ColorColorFogFog

Depth

[0,1][0,1]

Coord Coord

FrontFacing

ColorColor

SecondaryColorSecondaryColor

TexCoord[TexCoord[nn]]

zz (|zzee|,f )

Depth

21

OpenGL Fragment Shader

FrontFacing

FragCoord

FrontFacing

FragColorFragColor

FragCoord

FragDepth FragDepth

TemporariesTemporaries

FragmentFragmentShaderShader

UniformUniform TextureTexture

VaryingVaryingnn

Varying1Varying1

Varying0Varying0

Varying2Varying2

……

FragData[FragData[nn]]

22

OpenGL Shading LanguageToday

• Brief History• How we replace Fixed Function• OpenGL Programmer View• OpenGL Shaderwriter View• Examples

23

Simple Programhelloshader

intint main ( main ( intint argcargc, , charchar ****argvargv )){{

GLhandleARBGLhandleARB VShaderVShader, , FShaderFShader, , PObjectPObject;;GLintGLint VStatusVStatus, , VStatusVStatus, , PStatusPStatus;;GLintGLint myColorLocationmyColorLocation;;GLfloatGLfloat myColor[4] = { 0.0, 0.5, 1.0, 1.0 };myColor[4] = { 0.0, 0.5, 1.0, 1.0 };

GLcharARBGLcharARB **VSourceVSource;;GLcharARBGLcharARB *FSource[2];*FSource[2];

VSourceVSource = "void main( void ){ = "void main( void ){ gl_Positiongl_Position = = ftransformftransform(); }"(); }"FSource[0] = "uniform vec4 FSource[0] = "uniform vec4 myColormyColor;";"FSource[1] = "void main( void ){ FSource[1] = "void main( void ){ gl_FragColorgl_FragColor = = myColormyColor; }"; }"

// Initialize OpenGL context, etc...// Initialize OpenGL context, etc...

24

Simple Programhelloshader

// Create objects// Create objects

VShaderVShader = = glCreateShaderObjectARBglCreateShaderObjectARB( GL_VERTEX_SHADER_ARB );( GL_VERTEX_SHADER_ARB );FShaderFShader = = glCreateShaderObjectARBglCreateShaderObjectARB( GL_FRAGMENT_SHADER_ARB );( GL_FRAGMENT_SHADER_ARB );PObjectPObject = = glCreateProgramOjbectARBglCreateProgramOjbectARB();();

// Attach // Attach shadershader objects to program (even empty objects)objects to program (even empty objects)

glAttachObjectARBglAttachObjectARB( ( PObjectPObject, , VShaderVShader ););glAttachObjectARBglAttachObjectARB( ( PObjectPObject, , FShaderFShader ););

25

Simple Programhelloshader

// Load source// Load source

glShaderSourceARBglShaderSourceARB( ( VShaderVShader, 1, , 1, VSourceVSource, NULL );, NULL );glShaderSourceARBglShaderSourceARB( ( FShaderFShader, 2, , 2, FSourceFSource, NULL );, NULL );

// And compile// And compile

glCompileShaderARBglCompileShaderARB( ( VShaderVShader ););glCompileShaderARBglCompileShaderARB( ( FShaderFShader ););

// Check compile status// Check compile status

glGetObjectParameterARBglGetObjectParameterARB( ( VShaderVShader, &, &VStatusVStatus ););glGetObjectParameterARBglGetObjectParameterARB( ( FShaderFShader, &, &FStatusFStatus ););

if ( !if ( !VStatusVStatus || !|| !FStatusFStatus ))returnreturn 0;0;

26

Simple Programhelloshader

glLinkProgramARBglLinkProgramARB( ( PObjectPObject ););glGetObjectParameterARBglGetObjectParameterARB( ( PObjectPObject, &, &PStatusPStatus ););

if ( !if ( !PStatusPStatus ))returnreturn 0;0;

myColorLocationmyColorLocation = = glGetUniformLocationglGetUniformLocation( ( PObjectPObject, ", "myColormyColor" );" );

glUseProgramObjectARBglUseProgramObjectARB( ( PObjectPObject ););

if ( if ( myColorLocationmyColorLocation != != --1 ) 1 ) // existing behavior INVALID_OPERATION// existing behavior INVALID_OPERATIONglUniform4fvARB( glUniform4fvARB( myColorLocationmyColorLocation, , myColormyColor ););

// Draw Stuff// Draw Stuff}}

27

OpenGL Shading LanguageToday

• Brief History• How we replace Fixed Function• OpenGL Programmer View• OpenGL Shaderwriter View• Examples

28

OpenGL Shading LanguagePreprocessor directives

#error#error##pragmapragma optimize(on|offoptimize(on|off))##pragmapragma debug(on|offdebug(on|off))

#line line file#line line file__LINE____LINE____FILE____FILE____VERSION____VERSION__// comment// comment/* comment */

###define#definedefined()defined()##undefundef#if#if##ifdefifdef##ifndefifndef#else#else##elifelif##endif /* comment */endif

29

OpenGL Shading LanguageTypes

• void

• float vec2 vec3 vec4• mat2 mat3 mat4• int ivec2 ivec3 ivec4

• bool bvec2 bvec3 bvec4

30

OpenGL Shading LanguageReserved Types

• double dvec2 dvec3 dvec4

• half hvec2 hvec3 hvec4

• fixed fvec2 fvec3 fvec4

31

OpenGL Shading LanguageSampler Types

• samplernD

• samplerCube

• samplernDShadow

32

OpenGL Shading LanguageReserved Sampler Types

• samplernDRect

• samplernDRect__EXT

• samplernDRectShadow

• samplernDRectShadow__EXT

33

OpenGL Shading Languagestruct Types

• some minor restrictions– no qualifiers

– no bit fields

– no forward references

– no in-place definitions

– no anonymous structures

34

OpenGL Shading Languagearray Types

• some minor restrictions– one dimensional

– size is integral constant expression

– can declare unsized array, but…

– specificy size and type of array ONCE

– any basic type and struct

– no initialization at declaration

35

OpenGL Shading LanguageScope of Types

• global– Outside function

– Shared globals must be same type

• local (nested)– within function definition

– within function

36

OpenGL Shading Languagetype qualifiers

• const

• attribute

• uniform

• varying

• in out

• default

37

OpenGL Shading Languageoperators

• grouping: ()

• array subscript: []

• function call and constructor: ()

• field selector and swizzle: .

• postfix: ++ --

• prefix: ++ -- + - !

38

OpenGL Shading Languageoperators

• binary: * / + -

• relational: < <= > >=

• equality: == !=

• logical: && ^^ ||

• selection: ?:

• assignment: = *= /= += -=

39

OpenGL Shading Languagereserved operators

• prefix: ~

• binary: %

• bitwise: << >> & ^ |

• assignment: %= <<= >>= &= ^= |=

40

OpenGL Shading Languageconstructors

• float( )

• int( )

• bool( )

• vec2( ) vec3( ) vec4( )

• mat2( ) mat3( ) mat4 ( )

41

OpenGL Shading Languagescalar constructors

floatfloat f; f; intint i; i; boolbool b;b;

floatfloat( b)( b) // b=true?1.0:0.0;// b=true?1.0:0.0;intint( b)( b) // b=true?1:0;// b=true?1:0;boolbool( b)( b) // identity// identityfloatfloat( i)( i) // // intint to floatto floatintint( i)( i) // identity// identityboolbool( i)( i) // i!=0?true:false;// i!=0?true:false;floatfloat( f)( f) // identity// identityintint( f)( f) // float to // float to intintboolbool( f)( f) // f!=0.0?true:false;// f!=0.0?true:false;

42

OpenGL Shading Languagevector constructors

vec2vec2 v2; v2; vec3 vec3 v3; v3; vec4vec4 v4;v4;

vec2vec2( 1.0 ,2.0)( 1.0 ,2.0)vec3vec3( 0.0 ,0.0 ,1.0)( 0.0 ,0.0 ,1.0)vec4vec4( 1.0 ,0.5 ,0.0 ,1.0)( 1.0 ,0.5 ,0.0 ,1.0)vec4vec4( 1.0)( 1.0) // all 1.0// all 1.0vec4vec4( v2 ,v2)( v2 ,v2) // different...// different...vec4vec4( v3 ,1)( v3 ,1) // ...types// ...typesvec2vec2( v4)( v4)floatfloat( v4)( v4)

43

OpenGL Shading Languagematrix constructors

vec4vec4 v4; v4; mat4mat4 m4;m4;

mat4mat4( 1.0, 2.0, 3.0, 4.0, ( 1.0, 2.0, 3.0, 4.0, // column major// column major5.0, 6.0, 7.0, 8.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10., 11., 12., 9.0, 10., 11., 12., 13., 14., 15., 16.)13., 14., 15., 16.)

mat4mat4( v4, v4, v4, v4)( v4, v4, v4, v4)mat4mat4( 1.0)( 1.0) // identity matrix// identity matrixmat3mat3( m4)( m4) // NOT! upper 3x3// NOT! upper 3x3vec4vec4( m4)( m4) // upper 4x1// upper 4x1floatfloat( m4) ( m4) // upper 1x1// upper 1x1

44

OpenGL Shading Languagestruct constructors

structstruct light {light {floatfloat intensity;intensity;vec3vec3 position;position;

};};light light headLightheadLight = light( 0.2= light( 0.2

,,vec3vec3( 0.0 ,0.0, 1.0));( 0.0 ,0.0, 1.0));// same as// same aslight light headLightheadLight;;headLight.intensityheadLight.intensity = 0.2;= 0.2;headLight.positionheadLight.position = = vec3vec3( 0.0 ,0.0, 1.0);( 0.0 ,0.0, 1.0);

45

OpenGL Shading Languagecomponents

• component accessor for vectors– xyzw rgba stpq [i]

• component accessor for matrices– [i] [i][j]

46

OpenGL Shading Languagevector components

vec2vec2 v2;v2;vec3vec3 v3;v3;vec4vec4 v4;v4;

v2.xv2.x // is a float// is a floatv2.zv2.z //// wrong: component undefined for typewrong: component undefined for typev4.rgbav4.rgba // is a vec4// is a vec4v4.stpv4.stp // is a vec3// is a vec3v4.bv4.b // is a float// is a floatv4.xyv4.xy // is a vec2// is a vec2v4.xgp v4.xgp //// wrong: mismatched component setswrong: mismatched component sets

47

OpenGL Shading Languagevector components (rvalue)

vec2vec2 v2;v2;vec3vec3 v3;v3;vec4vec4 v4;v4;

v4.wzyxv4.wzyx // swizzles, is a vec4// swizzles, is a vec4v4.bgrav4.bgra // swizzles, is a vec4// swizzles, is a vec4v4.xxxxv4.xxxx // smears x, is a vec4// smears x, is a vec4v4.xxxv4.xxx // smears x, is a vec3// smears x, is a vec3v4.yyxxv4.yyxx // duplicates x and y, is a vec4// duplicates x and y, is a vec4v2.yyyyv2.yyyy // // wrong: too many components for typewrong: too many components for type

48

OpenGL Shading Languagevector components (lvalue)

vec4vec4 v4 = v4 = vec4vec4 (1.0, 2.0, 3.0, 4.0);(1.0, 2.0, 3.0, 4.0);

v4.xw = v4.xw = vec2vec2( 5.0, 6.0);( 5.0, 6.0); // (5.0, 2.0, 3.0, 6.0)// (5.0, 2.0, 3.0, 6.0)v4.wx = v4.wx = vec2vec2( 7.0, 8.0);( 7.0, 8.0); // (8.0, 2.0, 3.0, 7.0)// (8.0, 2.0, 3.0, 7.0)v4.xx = v4.xx = vec2vec2( 9.0,10.0);( 9.0,10.0); //// wrong: x used twicewrong: x used twicev4.yz = 11.0;v4.yz = 11.0; //// wrong: type mismatchwrong: type mismatchv4.yz = v4.yz = vec2vec2( 12.0);( 12.0); // (8.0,12.0,12.0, 7.0)// (8.0,12.0,12.0, 7.0)

49

OpenGL Shading Languagevector components []

vec4vec4 v4 = v4 = vec4vec4( 1.0, 2.0, 3.0, 4.0);( 1.0, 2.0, 3.0, 4.0);floatfloat f;f;intint i;i;

f = v4[0];f = v4[0]; // 1.0// 1.0f = v4[3]; f = v4[3]; // 4.0// 4.0f = v4[4]; f = v4[4]; //// undefinedundefined// ...// ...f = v4[i+1]; f = v4[i+1]; // defined for // defined for --1<i<31<i<3

50

OpenGL Shading Languagematrix components []

mat4mat4 m4;m4;

m4[1] = m4[1] = vec4vec4( 2.0);( 2.0); // 2nd column = 2.0// 2nd column = 2.0m4[0][0] = 1.0; m4[0][0] = 1.0; // upper 1x1 = 1.0// upper 1x1 = 1.0m4[4][4] = 3.0; m4[4][4] = 3.0; //// undefinedundefined

51

OpenGL Shading Languagecomponents and arrays []

vec3vec3 v3[2];v3[2];mat3mat3 m3[2];m3[2];

v3[0]v3[0] // is a vec3// is a vec3v3[0][0]v3[0][0] // is a float// is a floatV3[0].xV3[0].x // is a float// is a float

m3[0]m3[0] // is a mat3// is a mat3m3[0][0]m3[0][0] // is a vec3, 1st column// is a vec3, 1st columnm3[0][0][0]m3[0][0][0] // is a float, upper 1x1// is a float, upper 1x1

// // ::--((

52

OpenGL Shading Languagevector matrix ops

mat4mat4 m4,n4;m4,n4;vec4 vec4 v4v4

m4 * v4m4 * v4 // is a vec4// is a vec4v4 * m4v4 * m4 // is a vec4// is a vec4m4 * n4m4 * n4 // is a mat4// is a mat4

53

OpenGL Shading Languageflow control (scalar)

• expression ? tExpression : fExpression

• if, if-else

• for, while, do-while

• return, break, continue

• discard (fragment only)

54

OpenGL Shading Languageuser-defined functions

• call by value-return

• in out inout keywords

• function overloading

• one return value (can be any type)

• scope rules same as C

55

OpenGL Shading Languagebuilt-in vertex

vec4vec4 gl_Positiongl_Position; ; // must be written// must be writtenvec4vec4 gl_ClipPositiongl_ClipPosition; ; // may be written// may be writtenfloatfloat gl_PointSizegl_PointSize; ; // may be written// may be written

56

OpenGL Shading Languagebuilt-in fragment

boolbool gl_FrontFacinggl_FrontFacing; ; // may be read// may be readvec4vec4 gl_FragCoordgl_FragCoord; ; // may be read// may be readvec4vec4 gl_FragColorgl_FragColor; ; // may be read/written// may be read/writtenvec4vec4 gl_FragDatagl_FragData[[nn]];; // may be read/written// may be read/writtenfloatfloat gl_FragDepthgl_FragDepth; ; // may be read/written// may be read/written

57

OpenGL Shading Languagebuilt-in attributes

// Vertex Attributes, p. 19// Vertex Attributes, p. 19attributeattribute vec4vec4 gl_Vertexgl_Vertex;;attributeattribute vec3vec3 gl_Normalgl_Normal;;attributeattribute vec4vec4 gl_Colorgl_Color;;attributeattribute vec4vec4 gl_SecondaryColorgl_SecondaryColor;;attributeattribute vec4vec4 gl_MultiTexCoordgl_MultiTexCoordnn;;attributeattribute floatfloat gl_FogCoordgl_FogCoord;;

58

OpenGL Shading Languageuser-defined attributes

// Vertex Attributes, p. 19// Vertex Attributes, p. 19attribute vec3attribute vec3 myTangentmyTangent;;attribute vec3attribute vec3 myBinormalmyBinormal;;attribute floatattribute float myTempturemyTempture;;attribute floatattribute float myPressuremyPressure;;attribute floatattribute float myRainfallmyRainfall;;attribute floatattribute float myTimemyTime;;// etc...// etc...

59

OpenGL Shading Languagebuilt-in varying

varying vec4varying vec4 gl_FrontColorgl_FrontColor;; // vertex// vertexvarying vec4varying vec4 gl_BackColorgl_BackColor;; // vertex// vertexvarying vec4varying vec4 gl_FrontSecondaryColorgl_FrontSecondaryColor; ; // vertex// vertexvarying vec4varying vec4 gl_BackSecondaryColorgl_BackSecondaryColor;; // vertex// vertex

varying vec4varying vec4 gl_Colorgl_Color;; // fragment// fragmentvarying vec4varying vec4 gl_SecondaryColorgl_SecondaryColor;; // fragment// fragment

varying vec4varying vec4 gl_TexCoordgl_TexCoord[];[]; // both// bothvarying floatvarying float gl_FogFragCoordgl_FogFragCoord;; // both// both

60

OpenGL Shading Languageuser-defined varying

varying vec3varying vec3 myNormalPrimemyNormalPrime;;varying vec3varying vec3 myTangentPrimemyTangentPrime;;varying vec3varying vec3 myBinormalPrimemyBinormalPrime;;varying floatvarying float myPressurePrimemyPressurePrime;;// etc...// etc...

61

OpenGL Shading Languagebuilt-in uniforms

// Matrix state, p. 31, 32, 37, 39, 40// Matrix state, p. 31, 32, 37, 39, 40uniform mat4uniform mat4 gl_ModelViewMatrixgl_ModelViewMatrix;;uniform mat4uniform mat4 gl_ProjectionMatrixgl_ProjectionMatrix;;uniform mat4uniform mat4 gl_ModelViewProjectionMatrixgl_ModelViewProjectionMatrix;;uniform mat3uniform mat3 gl_NormalMatrixgl_NormalMatrix;;uniform mat4uniform mat4 gl_TextureMatrixgl_TextureMatrix[[nn];];// Normal scaling, p. 33// Normal scaling, p. 33uniform floatuniform float gl_NormalScalegl_NormalScale;;

62

OpenGL Shading Languagebuilt-in uniforms

// Light State, p. 50, 53, 55// Light State, p. 50, 53, 55structstruct gl_LightSourceParametersgl_LightSourceParameters {{

vec4vec4 ambient; ambient; // // AcliAclivec4vec4 diffuse; diffuse; // // DcliDclivec4vec4 specularspecular; ; // // ScliSclivec4vec4 position; position; // // PpliPplivec4vec4 halfVectorhalfVector; ; // Derived: Hi// Derived: Hi

63

OpenGL Shading Languagebuilt-in uniforms

vec3vec3 spotDirectionspotDirection; // ; // SdliSdlifloatfloat spotExponentspotExponent; // ; // SrliSrlifloatfloat spotCutoffspotCutoff; // ; // CrliCrlifloatfloat spotCosCutoffspotCosCutoff; // Derived: ; // Derived: cos(Crlicos(Crli))floatfloat constantAttenuationconstantAttenuation // K0// K0floatfloat linearAttenuationlinearAttenuation // K1// K1floatfloat quadraticAttenuationquadraticAttenuation// K2// K2

};};uniformuniform gl_LightSourceParametersgl_LightSourceParameters

gl_LightSourcegl_LightSource[gl_MaxLights[gl_MaxLights];];

64

OpenGL Shading Languageuser-defined uniforms

uniform mat4uniform mat4 myGlobalMatrixmyGlobalMatrix;;uniform vec4uniform vec4 myAmbientmyAmbient;;uniform vec4uniform vec4 myDiffuseMatLightmyDiffuseMatLight;;uniform vec4uniform vec4 mySpecularMatLightmySpecularMatLight;;uniform floatuniform float myGlowmyGlow;;uniform vec4uniform vec4 myWarmmyWarm;;uniform vec4uniform vec4 myCoolmyCool;;uniform floatuniform float myCurrentTimemyCurrentTime;;// etc...// etc...

65

Built-in Functionsangles & trigonometry

genTypegenType radiansradians( ( genTypegenType degrees)degrees)genTypegenType degreesdegrees( ( genTypegenType radians)radians)genTypegenType sinsin( ( genTypegenType angle)angle) // radians// radiansgenTypegenType coscos( ( genTypegenType angle)angle)genTypegenType tantan( ( genTypegenType angle)angle)genTypegenType asinasin( ( genTypegenType angle)angle)genTypegenType acosacos( ( genTypegenType angle)angle)genTypegenType atanatan( ( genTypegenType y ,y ,genTypegenType x)x)genTypegenType atanatan( ( genTypegenType y_over_x)y_over_x)

66

Built-in Functionsexponential

genTypegenType powpow( ( genTypegenType x ,x ,genTypegenType y)y)genTypegenType exp2exp2( ( genTypegenType x)x)genTypegenType log2log2( ( genTypegenType x)x)genTypegenType sqrtsqrt( ( genTypegenType x)x)genTypegenType inversesqrtinversesqrt( ( genTypegenType x)x)

67

Built-in Functionscommon

genTypegenType absabs( ( genTypegenType x)x)genTypegenType signsign( ( genTypegenType x)x)genTypegenType floorfloor( ( genTypegenType x)x)genTypegenType ceilceil( ( genTypegenType x)x)genTypegenType fractfract( ( genTypegenType x)x)genTypegenType modmod( ( genTypegenType x ,x ,floatfloat y)y)genTypegenType modmod( ( genTypegenType x ,x ,genTypegenType y)y)genTypegenType minmin( ( genTypegenType x ,x ,genTypegenType y)y)genTypegenType maxmax( ( genTypegenType x ,x ,genTypegenType y)y)genTypegenType clampclamp( ( genTypegenType x ,x ,floatfloat v0, v0, floatfloat v1)v1)genTypegenType clampclamp( ( genTypegenType x ,x ,genTypegenType v0, v0, genTypegenType v1)v1)

68

Built-in Functionsinterpolations

// return x*(1.0// return x*(1.0--a) + y*aa) + y*agenTypegenType mixmix( ( genTypegenType x ,x ,genTypegenType y ,y ,floatfloat a)a)genTypegenType mixmix( ( genTypegenType x ,x ,genTypegenType y ,y ,genTypegenType a)a)// x <= edge ? 0.0 : 1.0// x <= edge ? 0.0 : 1.0genTypegenType stepstep( ( floatfloat edge ,edge ,genTypegenType x)x)genTypegenType stepstep( ( genTypegenType edge ,edge ,genTypegenType x)x)

69

Built-in Functionsinterpolations

// // genTypegenType t;t;// t = (x// t = (x--edge0)/(edge1edge0)/(edge1--edge0);edge0);// t = clamp( t, 0.0, 1.0 );// t = clamp( t, 0.0, 1.0 );// return t*t*(3.0// return t*t*(3.0--2.0*t);2.0*t);genTypegenType smoothstepsmoothstep( ( floatfloat edge0 ,edge0 ,floatfloat edge1edge1

,,genTypegenType x)x)genTypegenType smoothstepsmoothstep( ( genTypegenType edge0 ,edge0 ,genTypegenType edge1edge1

,,genTypegenType x)x)

70

Built-in Functionsgeometric

floatfloat lengthlength( ( genTypegenType x)x)floatfloat distancedistance( ( genTypegenType p0 ,p0 ,genTypegenType p1)p1)floatfloat dotdot( ( genTypegenType x ,x ,genTypegenType y)y)vec3vec3 crosscross( ( vec3vec3 x ,x ,vec3vec3 y)y)genTypegenType normalizenormalize( ( genTypegenType x)x)genTypegenType faceforwardfaceforward( ( genTypegenType NN

,,genTypegenType II,,genTypegenType NrefNref))

genTypegenType reflectreflect( ( genTypegenType II,,genTypegenType N)N)

71

Built-in Functionsvector relational

bGenTypebGenType lessThanlessThan( ( genTypegenType x ,x ,genTypegenType y)y)bGenTypebGenType lessThanEquallessThanEqual( ( genTypegenType xx

,,genTypegenType y)y)bGenTypebGenType greaterThangreaterThan( ( genTypegenType x ,x ,genTypegenType y)y)bGenTypebGenType greaterThanEqualgreaterThanEqual( ( genTypegenType xx

,,genTypegenType y)y)bGenTypebGenType equalequal( ( genTypegenType x ,x ,genTypegenType y)y)bGenTypebGenType notEqualnotEqual( ( genTypegenType x , x , genTypegenType y)y)

boolbool anyany( ( bGenTypebGenType x)x)boolbool allall( ( bGenTypebGenType x)x)

72

Built-in Functionstexture

vec4vec4 texture1Dtexture1D( ( sampler1Dsampler1D samplersampler,,floatfloat coordcoord ,,floatfloat biasbias))

vec4vec4 texture2Dtexture2D( ( sampler2Dsampler2D samplersampler,,vec2vec2 coordcoord ,,floatfloat biasbias))

vec4vec4 texture3Dtexture3D( ( sampler3Dsampler3D samplersampler,,vec3vec3 coordcoord ,,floatfloat biasbias))

vec4vec4 textureCubetextureCube( ( samplerCubesamplerCube samplersampler,,vec3vec3 coordcoord ,,floatfloat biasbias))

73

Built-in Functionstexture (projective)

vec4vec4 texture1DProjtexture1DProj( ( sampler1Dsampler1D samplersampler,,vec2vec2 coordcoord ,,floatfloat biasbias))

vec4vec4 texture2DProjtexture2DProj( ( sampler2Dsampler2D samplersampler,,vec3vec3 coordcoord ,,floatfloat biasbias))

vec4vec4 texture3DProjtexture3DProj( ( sampler3Dsampler3D samplersampler,,vec4vec4 coordcoord ,,floatfloat biasbias))

vec4vec4 textureCubeProjtextureCubeProj( ( samplerCubesamplerCube samplersampler,,vec4vec4 coordcoord ,,floatfloat biasbias))

74

Built-in Functionstexture (projective)

vec4vec4 texture1DProjtexture1DProj( ( sampler1Dsampler1D samplersampler,,vec4vec4 coordcoord ,,floatfloat biasbias))

vec4vec4 texture2DProjtexture2DProj( ( sampler2Dsampler2D samplersampler,,vec4vec4 coordcoord ,,floatfloat biasbias))

75

Built-in Functionstexture rectangle

#define #define GL__EXT_texture_rectangleGL__EXT_texture_rectanglevec4vec4 texture2DRectEXTtexture2DRectEXT((

sampler2DRect__EXTsampler2DRect__EXT samplersampler,,vec2vec2 coordcoord))

vec4vec4 texture2DRectProjEXTtexture2DRectProjEXT((sampler2DRect__EXTsampler2DRect__EXT samplersampler,,vec3vec3 coordcoord))

vec4vec4 texture2DRectProjEXTtexture2DRectProjEXT((sampler2DRect__EXTsampler2DRect__EXT samplersampler,,vec4vec4 coordcoord))

76

Built-in Functionsshadow

vec4vec4 shadow2Dshadow2D( ( sampler2DShadowsampler2DShadow samplersampler,,vec3vec3 coordcoord ,,floatfloat biasbias))

vec4vec4 shadow1DProjshadow1DProj( ( sampler1DShadowsampler1DShadow samplersampler,,vec4vec4 coordcoord ,,floatfloat biasbias))

vec4vec4 shadow2DProjshadow2DProj( ( sampler2DShadowsampler2DShadow samplersampler,,vec4vec4 coordcoord ,,floatfloat biasbias))

77

Built-in Functionsshadow rectangle

##ifndefifndef GL__EXT_texture_rectangleGL__EXT_texture_rectangle#define #define GL__EXT_texture_rectangleGL__EXT_texture_rectangle##endifendifvec4vec4 shadow2DRectEXTshadow2DRectEXT((

sampler2DRectShadow__EXTsampler2DRectShadow__EXT samplersampler,,vec3vec3 coordcoord))

vec4vec4 shadow2DRectProjEXTshadow2DRectProjEXT((sampler2DRectShadow__EXTsampler2DRectShadow__EXT samplersampler,,vec4vec4 coordcoord))

78

Built-in Functionsnoise

floatfloat noise1noise1( ( genTypegenType coordcoord))vec2vec2 noise2noise2( ( genTypegenType coordcoord))vec3vec3 noise3noise3( ( genTypegenType coordcoord))vec4vec4 noise4noise4( ( genTypegenType coordcoord))

79

Built-in Functionsvertex

vec4 vec4 ftransformftransform( void )( void )

// Example usage:// Example usage:gl_Positiongl_Position == ftransformftransform();();

// user// user--defined function, may be variantdefined function, may be variantvec4 vec4 ftransformftransform( void )( void ){{

vec4vec4 p;p;p = p = gl_ModelViewProjectionMatrixgl_ModelViewProjectionMatrix * * gl_Vertexgl_Vertex;;return p;return p;

}}

80

Built-in Functionsfragment

genTypegenType dFdxdFdx( ( genTypegenType p)p)genTypegenType dFdydFdy( ( genTypegenType p)p)genTypegenType fwidthfwidth( ( genTypegenType p)p)

81

OpenGL Shading LanguageToday

• Brief History• How we replace Fixed Function• OpenGL Programmer View• OpenGL Shaderwriter View• Examples

– Example 1

82

Trivial Shadervertex

varying vec3varying vec3 Normal;Normal; // output// outputvoidvoid main( main( voidvoid)){{

gl_Positiongl_Position = = ftransformftransform();();Normal = Normal = normalizenormalize( ( gl_NormalMatrixgl_NormalMatrix * * gl_Normalgl_Normal););gl_FrontColorgl_FrontColor = = gl_Colorgl_Color;;

}}

83

Trivial Shaderfragment

varyingvarying vec3vec3 Normal;Normal; // input// inputuniformuniform vec3vec3 LightColorLightColor;; // Light Color// Light Coloruniformuniform vec3vec3 LightPosLightPos;; // Light Position// Light Positionvoidvoid main( void)main( void){{

vec3vec3 color = color = LightColorLightColor;;color *= clamp( dot( color *= clamp( dot( normalizenormalize( ( Normal),LightPosNormal),LightPos))

,0.0, 1.0);,0.0, 1.0);gl_FragColorgl_FragColor = = vec4vec4( color, 1.0);( color, 1.0);

}}

84

OpenGL Shading LanguageToday

• Brief History• How we replace Fixed Function• OpenGL Programmer View• OpenGL Shaderwriter View• Examples

– Example 1– Hints and Kinks

85

Hints and Kinksno casts

floatfloat Function( Function( vec4vec4 p ) p ) // C assumptions// C assumptions{{

floatfloat f;f;f = (f = (floatfloat)p)p; ; // WRONG// WRONG

// no casts// no castsreturnreturn f;f;

}}

86

Hints and Kinksno casts

floatfloat Function( Function( vec4vec4 p ) p ) // C assumptions// C assumptions{{

floatfloat f;f;f = f = floatfloat( p ); ( p ); // OK// OK

// constructor// constructorreturnreturn f;f;

}}

87

Hints and Kinksno casts

floatfloat Function( Function( vec4vec4 p ) p ) // C assumptions// C assumptions{{

float float f;f;f = p.x; f = p.x; // OK// OK

// swizzle// swizzlereturnreturn f;f;

}}

88

Hints and Kinksno vec4-centricism

vec4vec4 Function( Function( vec4vec4 p ) p ) // ARB_*_program// ARB_*_program// assumptions// assumptions

{{vec4vec4 f;f;f = f = p.xxxxp.xxxx; ; // OK// OK

// valid swizzle// valid swizzlereturnreturn f;f;

}}

89

Hints and Kinksno vec4-centricism

vec4vec4 Function( Function( floatfloat p ) p ) // ARB_*_program// ARB_*_program// assumptions// assumptions

{{vec4vec4 f;f;f = f = p.xxxxp.xxxx; ; // WRONG// WRONG

// invalid swizzle// invalid swizzlereturnreturn f;f;

}}

90

Hints and Kinksno vec4-centricism

vec4vec4 Function( Function( floatfloat p ) p ) // ARB_*_program// ARB_*_program// assumptions// assumptions

{{vec4vec4 f;f;f = vec4( p.x ); f = vec4( p.x ); // OK// OK

// explicit constructor// explicit constructorreturnreturn f;f;

}}

91

Hints and Kinksno implicit casts

vec4vec4 Function( Function( vec4 vec4 p ) p ) // C or // C or RenderManRenderMan// assumptions// assumptions

{{vec4vec4 f;f;f = 2 * p; f = 2 * p; // WRONG// WRONG

// no implicit casts// no implicit castsreturnreturn f;f;

}}

92

Hints and Kinksno implicit casts

vec4 vec4 Function( Function( vec4vec4 p ) p ) // C or // C or RenderManRenderMan// assumptions// assumptions

{{vec4vec4 f;f;f = 2.0 * p; f = 2.0 * p; // OK// OK

// float * vec4// float * vec4returnreturn f;f;

}}

93

Hints and Kinksno implicit casts

vec4 vec4 Function( Function( vec4vec4 p ) p ) // C or // C or RenderManRenderMan// assumptions// assumptions

{{vec4vec4 f;f;f = f = floatfloat( 2 ) * p; ( 2 ) * p; // OK// OK

// float * vec2// float * vec2returnreturn f;f;

}}

94

Hints and Kinksdeclare before use

vec4vec4 Function( Function( vec3vec3 p ) p ) // Shading Language// Shading Language// assumptions// assumptions

{{vec4vec4 f.a = 1.0; f.a = 1.0; // Wrong// Wrong

// declared after use// declared after usef.rgbf.rgb = p;= p;returnreturn f;f;

}}

95

Hints and Kinksdeclare before use

vec4vec4 Function( Function( vec3vec3 p ) p ) // Shading Language// Shading Language// assumptions// assumptions

{{vec4vec4 f[3] = 1.0; f[3] = 1.0; // Wrong// Wrong

// declared after use// declared after usef.rgbf.rgb = p;= p;returnreturn f;f;

}}

96

Hints and Kinksdeclare before use

vec4vec4 Function( Function( vec3vec3 p ) p ) // Shading Language// Shading Language// assumptions// assumptions

{{vec4vec4 f; f; // OK// OK

// declared before use// declared before usef.rgbf.rgb = p; = p; f.a = 1.0;f.a = 1.0;returnreturn f;f;

}}

97

Hints and Kinksdeclare before use

vec4vec4 Function( Function( vec3vec3 p ) p ) // Shading Language// Shading Language// assumptions// assumptions

{{vec4vec4 f = f = vec4vec4( p, 1 );( p, 1 );// OK// OK

// declared before use// declared before usereturn f;return f;

}}

98

Hints and Kinksno vector scalar assignment

vec4 vec4 Function( Function( vec4 vec4 p ) p ) // HLSL assumptions// HLSL assumptions{{

vec4vec4 f = 0.0; f = 0.0; // WRONG// WRONG// // lvaluelvalue rvaluervalue mismatchmismatch

f += p.x;f += p.x;return f;return f;

}}

99

Hints and Kinksno vector scalar assignment

vec4vec4 Function( Function( vec4vec4 p ) p ) // HLSL assumptions// HLSL assumptions{{

vec4vec4 f = f = vec4vec4( 0.0 ); ( 0.0 ); // OK// OK// constructor// constructor

f += p.x; f += p.x; // OK// OK// f = f + p.x;// f = f + p.x;

returnreturn f;f;}}

100

Hints and Kinkstranspose built-in?

vec4vec4 Function( Function( vec4vec4 p ) p ) // ARB_*_program// ARB_*_program// assumptions// assumptions

{{vec4vec4 f;f;f = transpose( f = transpose( gl_ModelViewMatrixgl_ModelViewMatrix ) * p;) * p;returnreturn f;f;

}}

101

Hints and Kinkstranspose built-in?

vec4vec4 Function( Function( vec4vec4 p ) p ) // ARB_*_program// ARB_*_program// assumptions// assumptions

{{vec4vec4 f;f;f = p * f = p * gl_ModelViewMatrixgl_ModelViewMatrix;;returnreturn f;f;

}}

102

Hints and Kinksextensions

##ifndefifndef GL__EXT_cool_extensionGL__EXT_cool_extension#error "#error "GL__EXT_cool_extensionGL__EXT_cool_extension required"required"##endifendifvec4vec4 Function( Function( vec4vec4 p )p ){{

vec4vec4 color;color;color = color = coolFunctionEXTcoolFunctionEXT( p );( p );color.rgbcolor.rgb *= *= color.acolor.a;;returnreturn color;color;

}}

103

Hints and Kinksextensions

##ifndefifndef GL__EXT_cool_extensionGL__EXT_cool_extensionvec4vec4 coolFunctionEXTcoolFunctionEXT( ( vec4vec4 p ); // emulate p ); // emulate ##endifendifvec4vec4 Function( Function( vec4vec4 p )p ){{

vec4vec4 color;color;color = color = coolFunctionEXTcoolFunctionEXT( p );( p );color.rgbcolor.rgb *= *= color.acolor.a;;returnreturn color;color;

}}

104

OpenGL Shading LanguageToday

• Brief History• How we replace Fixed Function• OpenGL Programmer View• OpenGL Shaderwriter View• Examples

– Example 1– Hints and Kinks– Example 2

105

Porting Shadersexample (with optimizations)

[Segal, [Segal, AkeleyAkeley, Leech] The OpenGL Graphics System: A Specification (V 1.5), Leech] The OpenGL Graphics System: A Specification (V 1.5)p. 47p. 47

106

Porting Shadersteaching example

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 p, p, in vec3in vec3 N )N ){{

vec3vec3 R, U;R, U;floatfloat M;M;U = U = normalizenormalize( p );( p );R = R = reflectreflect( U, N );( U, N );M = 2.0 * M = 2.0 * sqrtsqrt( R.x*R.x + R.y*R.y + (R.z+1.0)*(R.z+1.0) );( R.x*R.x + R.y*R.y + (R.z+1.0)*(R.z+1.0) );returnreturn vec2( R.x/M + 0.5, R.y/M + 0.5 );vec2( R.x/M + 0.5, R.y/M + 0.5 );

}}

[Rost] OpenGL Shading Language ("Orange Book" )[Rost] OpenGL Shading Language ("Orange Book" )p. 229p. 229

107

Porting Shadersargument normalization

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 pp, , in vec3in vec3 N )N ){{

vec3 vec3 R, U;R, U;floatfloat M;M;U =U = normalizenormalize( p );( p );R = R = reflectreflect( U, N );( U, N );M = 2.0 * M = 2.0 * sqrtsqrt( R.x*R.x + R.y*R.y + (R.z+1.0)*(R.z+1.0) );( R.x*R.x + R.y*R.y + (R.z+1.0)*(R.z+1.0) );return vec2return vec2( R.x/M + 0.5, R.y/M + 0.5 );( R.x/M + 0.5, R.y/M + 0.5 );

}}

108

Porting Shaderslet caller normalize

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;floatfloat M;M;R = R = reflectreflect( U, N );( U, N );M = 2.0 * M = 2.0 * sqrtsqrt( R.x*R.x + R.y*R.y + (R.z+1.0)*(R.z+1.0) );( R.x*R.x + R.y*R.y + (R.z+1.0)*(R.z+1.0) );return vec2return vec2( R.x/M + 0.5, R.y/M + 0.5 );( R.x/M + 0.5, R.y/M + 0.5 );

}}

109

Porting Shaders(z+1)

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;floatfloat M;M;R = R = reflectreflect( U, N );( U, N );M = 2.0 * M = 2.0 * sqrtsqrt( R.x*R.x + R.y*R.y +( R.x*R.x + R.y*R.y + (R.z+1.0)*(R.z+1.0) );(R.z+1.0)*(R.z+1.0) );return vec2return vec2( R.x/M + 0.5, R.y/M + 0.5 );( R.x/M + 0.5, R.y/M + 0.5 );

}}

110

Porting Shaderscse (exception proves rule)

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N ) N ) {{

vec3vec3 R;R;floatfloat M;M;R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;M = 2.0 * M = 2.0 * sqrtsqrt( R.x*R.x + R.y*R.y + R.z*R.z );( R.x*R.x + R.y*R.y + R.z*R.z );return vec2return vec2( R.x/M + 0.5, R.y/M + 0.5 );( R.x/M + 0.5, R.y/M + 0.5 );

}}

111

Porting Shadersx2+y2+z2

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;floatfloat M;M;R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;M = 2.0 * M = 2.0 * sqrtsqrt( R.x*R.x + R.y*R.y + R.z*R.z );( R.x*R.x + R.y*R.y + R.z*R.z );return vec2return vec2( R.x/M + 0.5, R.y/M + 0.5 );( R.x/M + 0.5, R.y/M + 0.5 );

}}

112

Porting Shadersvectorize scalar expression

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N ) N ) {{

vec3vec3 R;R;floatfloat M;M;R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;M = 2.0 * M = 2.0 * sqrtsqrt( dot( R, R ) );( dot( R, R ) );return vec2return vec2( R.x/M + 0.5, R.y/M + 0.5 );( R.x/M + 0.5, R.y/M + 0.5 );

}}

113

Porting Shadersbuilt-in function?

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;floatfloat M;M;R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;M = 2.0 * M = 2.0 * sqrtsqrt( ( dotdot( R, R ) );( R, R ) );return vec2return vec2( R.x/M + 0.5, R.y/M + 0.5 );( R.x/M + 0.5, R.y/M + 0.5 );

}}

114

Porting Shaderslength

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;floatfloat M;M;R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;M = 2.0 * M = 2.0 * lengthlength( R );( R );return vec2return vec2( R.x/M + 0.5, R.y/M + 0.5 );( R.x/M + 0.5, R.y/M + 0.5 );

}}

115

Porting ShadersM is denominator only

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;floatfloat M;M;R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;M = 2.0 * M = 2.0 * lengthlength( R );( R );return vec2return vec2( R.x/M + 0.5, R.y/M + 0.5 );( R.x/M + 0.5, R.y/M + 0.5 );

}}

116

Porting Shaderspre-invert M

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;floatfloat inverseMinverseM;;R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;inverseMinverseM = 1.0/( 2.0 * = 1.0/( 2.0 * lengthlength( R ) );( R ) );return vec2return vec2( R.x*( R.x*inverseMinverseM + 0.5, R.y*+ 0.5, R.y*inverseMinverseM + 0.5 );+ 0.5 );

}}

117

Porting Shaders1.0/2.0

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;float float inverseMinverseM;;R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;inverseMinverseM = 1.0/( 2.0 * = 1.0/( 2.0 * lengthlength( R ) );( R ) );return vec2return vec2( R.x*( R.x*inverseMinverseM + 0.5, R.y*+ 0.5, R.y*inverseMinverseM + 0.5 );+ 0.5 );

}}

118

Porting Shadersconstant folding (epr)

vec2 vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;floatfloat inverseMinverseM;;R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;inverseMinverseM = 0.5 / = 0.5 / lengthlength( R );( R );return vec2return vec2( R.x*( R.x*inverseMinverseM + 0.5, R.y*+ 0.5, R.y*inverseMinverseM + 0.5 );+ 0.5 );

}}

119

Porting Shadersscale and bias

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;floatfloat inverseMinverseM;;R =R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;inverseMinverseM = 0.5 / = 0.5 / lengthlength( R );( R );return vec2return vec2( R.x*( R.x*inverseMinverseM + 0.5, R.y*+ 0.5, R.y*inverseMinverseM + 0.5 );+ 0.5 );

}}

120

Porting Shadersvectorize scale and bias

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;floatfloat inverseMinverseM;;R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;inverseMinverseM = 0.5 / = 0.5 / lengthlength( R );( R );returnreturn R.xyR.xy**inverseMinverseM + 0.5;+ 0.5;

}}

121

Porting Shadersbuilt-in function?

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;floatfloat inverseMinverseM;;R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;inverseMinverseM = 0.5 / = 0.5 / lengthlength( R );( R );returnreturn R.xyR.xy**inverseMinverseM + 0.5;+ 0.5;

}}

122

Porting Shadersuser-defined function

floatfloat inverselengthinverselength( ( const in vec3 const in vec3 p );p );

vec2 vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;floatfloat inverseMinverseM;;R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;inverseMinverseM = 0.5 * = 0.5 * inverselengthinverselength( R );( R );returnreturn R.xyR.xy**inverseMinverseM + 0.5;+ 0.5;

}}

floatfloat inverselengthinverselength( ( vec3vec3 p )p ){{

returnreturn inversesqrtinversesqrt( ( dotdot( p, p ) );( p, p ) );}}

123

Porting Shadersscalar temporary

float float inverselengthinverselength( ( const in vec3const in vec3 p );p );

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;floatfloat inverseMinverseM;;R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;inverseMinverseM = 0.5 * = 0.5 * inverselengthinverselength( R );( R );returnreturn R.xyR.xy**inverseMinverseM + 0.5; + 0.5;

}}

floatfloat inverselengthinverselength( ( const in vec3const in vec3 p )p ){{

returnreturn inversesqrtinversesqrt( ( dotdot( p, p ) );( p, p ) );}}

124

Porting Shadersreorder to vectorize

floatfloat inverselengthinverselength( ( const in vec3const in vec3 p )p )

vec2 vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;

R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;R.xyR.xy *= *= inverselengthinverselength( R );( R );returnreturn R.xyR.xy*0.5 + 0.5;*0.5 + 0.5;

}}

floatfloat inverselengthinverselength( ( const in vec3const in vec3 p )p ){{

returnreturn inversesqrtinversesqrt( ( dotdot( p, p ) );( p, p ) );}}

125

Porting Shadersbuilt-in?

floatfloat inverselengthinverselength( ( const inconst in vec3vec3 p )p )

vec2 vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3 R;vec3 R;

R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;R.xyR.xy *= *= inverselengthinverselength( R );( R );return return R.xyR.xy*0.5 + 0.5;*0.5 + 0.5;

}}

floatfloat inverselengthinverselength( ( const in vec3const in vec3 p )p ){{

returnreturn inversesqrtinversesqrt( ( dotdot( p, p ) );( p, p ) );}}

126

Porting Shadersnormalize (readable but slow?)

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3vec3 R;R;

R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;R = R = normalizenormalize( R );( R );returnreturn R.xyR.xy*0.5 + 0.5;*0.5 + 0.5;

}}

127

Porting Shadersfunction parameters

vec2vec2 SphereMapSphereMap( ( in vec3in vec3 U, U, in vec3in vec3 N )N ){{

vec3 R;vec3 R;

R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;R = R = normalizenormalize( R );( R );returnreturn R.xyR.xy*0.5 + 0.5;*0.5 + 0.5;

}}

128

Porting Shadersconst

vec2 vec2 SphereMapSphereMap( ( const in vec3const in vec3 U, U, const in vec3const in vec3 N )N ){{

vec3 R;vec3 R;

R = R = reflectreflect( U, N );( U, N );R.z += 1.0;R.z += 1.0;R = R = normalizenormalize( R );( R );return return R.xyR.xy*0.5 + 0.5;*0.5 + 0.5;

}}

129

Porting Shadersadd terse comments

// // prenormalizeprenormalize parametersparametersvec2 vec2 SphereMapSphereMap( const in vec3 U, const in vec3 N )( const in vec3 U, const in vec3 N ){{

vec3 R;vec3 R;

R = R = reflectreflect( U, N );( U, N );R.z += 1.0; R.z += 1.0; // half// half--angleangleR = R = normalizenormalize( R );( R );return return R.xyR.xy*0.5 + 0.5; *0.5 + 0.5; // [// [--1.0,1.0]1.0,1.0]-->[0.0,1.0]>[0.0,1.0]

}}

130

Porting Shadersfin

vec2vec2 SphereMapSphereMap( ( const in vec3const in vec3 U, U, const in vec3const in vec3 N )N ){{

vec3vec3 R;R;

R = R = reflectreflect( U, N );( U, N );R.z += 1.0; R.z += 1.0; // half// half--angleangleR = R = normalizenormalize( R );( R );returnreturn R.xyR.xy*0.5 + 0.5; *0.5 + 0.5; // [// [--1.0,1.0]1.0,1.0]-->[0.0,1.0]>[0.0,1.0]

}}

// example usage// example usagevec2vec2 tctc = = SphereMapSphereMap( ( normalizenormalize( p ), ( p ), normalizenormalize( n ) );( n ) );

top related