INTRODUCTION TO OPENGL - KAISTvclab.kaist.ac.kr/cs380/slide02-hello2d.pdf · OpenGL-Object...

Preview:

Citation preview

18/03/06

1

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

CS380:IntroductiontoComputerGraphicsIntroductiontoOpenGLSL

MinH.KimKAISTSchoolofComputing

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

INTRODUCTIONTOOPENGL

2

References:https://www.khronos.org/opengl/wiki/History_of_OpenGLhttps://www.cg.tuwien.ac.at/courses/CG23/slides/tutorials/CG2LU_OpenGL_3.x_Introduction_pt_1.pdf

18/03/06

2

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

WhatisOpenGL?•  OpenGL=OpenGraphicsLibrary•  Anopenindustry-standardAPIforhardwareacceleratedgraphicsdrawing

•  Implementedbygraphics-cardvendors•  MaintainedbytheKhronos-Group

3

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

WhatisOpenGL?•  Pros&Cons:

•  +Fullspecificationfreelyavailable•  +Everyonecanuseit•  +Canuseitanywhere(Windows,Linux,Mac,BSD,Mobilephones,Web-pages(soon),...)

•  +Long-termmaintenanceforolderapplications•  +NewfunctionalityusuallyearlieravailablethroughExtensions

•  -InclusionofExtensionstocoremaytakelonger•  ?Game-Industry

4

18/03/06

3

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

SetupOpenGLProject•  IncludeOpenGL-header:

#include<GL/gl.h>//basicOpenGL

•  LinkOpenGL-library“opengl32.lib”•  Ifneeded,alsolinkotherlibraries(esp.GLEW,seelater!).

5

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGLinmoredetail•  OpenGL-functionsprefixedwith“gl”:

glFunction{1234}{bsifd...}{v}(Targ1,Targ2,...);Example:glDrawArrays(GL_TRIANGLES,0,vertexCount);

•  OpenGL-constantsprefixedwith“GL_”:GL_SOME_CONSTANTExample:GL_TRIANGLES

•  OpenGL-typesprefixedwith“GL”:GLtypeExample:GLfloat

6

18/03/06

4

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGLinmoredetail•  OpenGLisastate-machine•  Rememberstate-machines:

– Onceastateisset,itremainsactiveuntilthestateischangedtosomethingelseviaatransition.

– AtransitioninOpenGLequalsafunction-call.

– AstateinOpenGLisdefinedbytheOpenGL-objectswhicharecurrent.

7

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGLinmoredetail•  SetOpenGL-states:

glEnable(...);glDisable(...);gl*(...);//severalcalldependingonpurpose

•  QueryOpenGL-stateswithGet-Methods:glGet*(...);//severalcallsavailable,dependingonwhattoquery

8

18/03/06

5

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGL2.1•  ReleasedinAugust2006•  Fullysupported“fixedfunction”(FF)•  GLSL-Shaderssupportedaswell•  MixofFFandshaderswaspossible,whichcouldgetconfusingorclumsyquicklyinbiggerapplications

•  Supportedbyallgraphics-drivers

9

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGL3.0•  ReleasedinAugust2008•  Introducedadeprecationmodel:

– MainlyFFwasmarkeddeprecated– UseofFFstillpossible,butnotrecommend

•  AlsointroducedContexts:– Forward-CompatibleContext(FWD-CC)vs.FullContext

•  WithFWD-CC,noaccesstoFFanymore,i.e.FF-function-callscreateerror“InvalidCall”

10

18/03/06

6

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGL3.0(cont.)•  Furthermore,GLSL1.3wasintroduced•  SupportedbyrecentNvidiaandATI-graphicsdrivers.

11

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGL3.1•  ReleasedinMarch2009•  IntroducedGLSL1.4•  Removeddeprecatedfeaturesof3.0,butFFcanstillbeaccessedbyusingthe“GL_ARB_compatibility”-extension.

•  SupportedbyrecentNvidiaandATI-graphicsdrivers.

12

18/03/06

7

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGL3.2•  ReleasedinAugust2009•  Profileswereintroduced:Core-Profilevs.Compatibility-Profile

•  WithCore-Profile,onlyaccesstoOpenGL3.2core-functions

•  WithCompatibility-Profile,FFcanstillbeused•  AlsointroducedGLSL1.5•  SupportedbyrecentNvidiaandATI-graphicsdrivers.

13

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGL3.3•  Releasedon10thMarch2010•  IntroducesGLSL3.3•  IncludessomenewExtensions•  Maintainscompatibilitywitholderhardware

14

18/03/06

8

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGL4.0•  Releasedon10thMarch2010•  IntroducesGLSL4.0•  Introducesnewshader-stagesforhardware-tessellation(tessellationisaprocessthatreadsapatchprimitiveandgeneratesnewprimitivesusedbysubsequentpipelinestages.)

•  AdoptionofnewExtensionstoCore.

15

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGL4.6•  ReleasedonJuly30,2017•  SupportsGLSL4.6•  State-of-the-artOpenGLversion•  RefertotheKhronoswebsiteformoreinformation:https://www.khronos.org/opengl/wiki/History_of_OpenGL

16

18/03/06

9

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

GLEW•  OnWindowsonlyOpenGL1.1supportednatively.

•  TousenewerOpenGLversions,eachadditionalfunction,i.e.,allextensions(currently~1900),mustbeloadedmanually!

•  àLotsofwork!Therefore:•  UseGLEW=OpenGLExtensionWrangler

17

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

GLEW•  Includeitinyourprogramandinitializeit:

#include<GL/glew.h>//includebeforeotherGLheaders!//#include<GL/gl.h>includedwithGLEWalreadyvoidinitGLEW(){

GLenumerr=glewInit();//initializeGLEWif(err!=GLEW_OK)//checkforerror{ cout<<"GLEWError:"<<glewGetErrorString(err); exit(1);}

}

18

18/03/06

10

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

GLEW•  CheckforsupportedOpenGLversion:ttttttttt

if(glewIsSupported("GL_VERSION_3_2")){//OpenGL3.2supportedonthissystem}

•  Tocheckforaspecificextension:if(GLEW_ARB_geometry_shader4){//Geometry-Shadersupportedonthissystem}

19

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

GLEW•  Howtouse:

–  IncludeGLEW-header:#include<GL/glew.h>//GLEW

– LinkOpenGL-library“opengl32.lib”and“glew32.lib”– Copy“glew32.dll”tobinfolder– You’rereadytogo.

20

18/03/06

11

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGLProgramSkeleton•  TypicalOpenGL-Application:

21

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGLProgramSkeleton•  main():

– Program-Entry– Createwindow– Callinit()– Startmainwindow-loopCallcleanup()– Exitapplication

•  init():–  Initializelibraries,loadconfig-files,...– Allocateresources,preprocessing,...

22

18/03/06

12

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGLProgramSkeleton•  update():

– Handleuser-input,updategame-logic,...

•  render():– Doactualrenderingofgraphicshere!– Note:Callingrender()twicewithoutcallingupdate()inbetweenshouldresultinthesamerenderedimage!

•  cleanup():– Freeallresources

23

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGLProgramSkeleton•  Exampleinit()-function:

voidinit(){ //Createandinitializeawindowwithdepth-bufferand //double-buffering.Seeyourwindow-managersdocumentation. //enablethedepth-bufferinOpenGL glEnable(GL_DEPTH_TEST); //enableback-facecullinginOpenGL glEnable(GL_CULL_FACE); //defineaclearcolor glClearColor(0.0f,0.0f,0.0f,0.0f); //settheOpenGL-viewport glViewPort(0,0,windowWidth,windowHeight); //Dootherusefulthings}

24

18/03/06

13

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGLProgramSkeleton•  Thegeometryofa3D-objectisstoredinanarrayofverticescalledVertex-Array.

•  EachvertexcanhavesocalledAttributes,likeaNormalVectorandTexture-Coordinates.

•  OpenGLalsotreatsverticesasattributes!•  TorendergeometryinOpenGL,vertex-(attribute)-arraysarepassedtoOpenGLandthenrendered.

25

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGLProgramSkeleton•  Todoso:

– Querytheattribute-locationintheshader:GLintvertexLocation=glGetAttribLocation(myShaderProgram,"in_Position”);

– Enableanarrayforthevertex-attribute:glEnableVertexAttribArray(vertexLocation);

– ThentellOpenGLwhichdatatouse:glVertexAttribPointer(vertexLocation,3,GL_FLOAT,GL_FALSE,0,myVertexArray);

26

18/03/06

14

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGLProgramSkeleton•  Draw(“render”)thearrays:

tglDrawArrays(GL_TRIANGLES,0,3);//thisdoestheactualdraw

•  Finallydisabletheattribute-array:glDisableVertexAttribArray(vertexLocation);

27

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGLProgramSkeleton•  Examplerender()-function:

t//triangledatastaticGLfloatvertices[]={-0.5,-0.333333,0,//x1,y1,z1

+0.5,-0.333333,0,//x2,y2,z2 +0.0,+0.666666,0};//x3,y3,z3

...voidrender(){

//clearthecolor-bufferandthedepth-bufferglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

//activateashaderprogramglUseProgram(myShaderProgram);

//FindtheattributesGLintvertexLocation=glGetAttribLocation( myShaderProgram,"in_Position");

28

18/03/06

15

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGLProgramSkeleton//enablevertexattributearrayforthisattribute

glEnableVertexAttribArray(vertexLocation); //setattributepointer

glVertexAttribPointer(vertexLocation,3,GL_FLOAT, GL_FALSE,0,vertices);

//Draw("render")thetriangle

glDrawArrays(GL_TRIANGLES,0,3);

//Donewithrendering.DisablevertexattributearrayglDisableVertexAttribArray(vertexLocation);

//disableshaderprogram glUseProgram(0);

//Swapbuffers}

29

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGL-Objectlife-cycle•  InOpenGL,allobjects,likebuffersandtextures,aresomehowtreatedthesameway.

•  Onobjectcreationandinitialization:– First,createahandletotheobject(inOpenGLoftencalledaname).DothisONCEforeachobject.

– Then,bindtheobjecttomakeitcurrent.– PassdatatoOpenGL.Aslongasthedatadoesnotchange,youonlyhavetodothisONCE.

– Unbindtheobjectifnotused.

30

18/03/06

16

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGL-Objectlife-cycle•  Onrendering,orwhenevertheobjectisused:

– Bindittomakeitcurrent.– Useit.– Unbindit.

•  Finally,whenobjectisnotneededanymore:– Deleteobject.– Notethatinsomecasesyoumanuallyhavetodeleteattachedresources!

•  NOTE:OpenGL-objectsareNOTobjectsinanOOP-sense!

31

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Whatshadersare•  SmallC-likeprogramsexecutedonthegraphics-hardware

•  Replacefixedfunctionpipelinewithshaders•  Shader-Types

– VertexShader(VS):pervertexoperations– GeometryShader(GS):perprimitiveoperations– FragmentShader(FS):perfragment(pixel)operations,so-calledPixelShader

•  Usede.g.fortransformationsandlighting

32

18/03/06

17

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Shader-Executionmodel

33

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Rendering-Pipeline•  OpenGL3.xRendering-Pipeline:

34

18/03/06

18

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Rendering-Pipeline•  Remember:

– TheVertex-ShaderisexecutedONCEpereachvertex!

– TheFragment-ShaderisexecutedONCEperrasterizedfragment(~apixel)!

•  AShader-Programconsistsofboth,– OneVS– OneFS

35

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Settingupshadersandprograms•  Compileshaders:

ttttttttttttchar*shaderSource;//containsshadersourceintshaderHandle=glCreateShader(GL_SHADER_TYPE);//shader-types:vertex||geometry||fragmentglShaderSource(shaderHandle,1,shaderSource,NULL);glCompileShader(shaderHandle);

•  Createprogramandattachshaderstoit:tintprogramHandle=glCreateProgram();glAttachShader(programHandle,shaderHandle);//dothisforvertexANDfragment-shader(ANDgeometryifneeded)!

•  Finallylinkprogram:glLinkProgram(programHandle);

36

18/03/06

19

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Enablingshaders•  EnableaGLSLprogram:

tglUseProgram(programHandle);//shader-programnowactive– Theactiveshader-programwillbeuseduntilglUseProgram()iscalledagainwithanotherprogram-handle.

– CallofglUseProgram(0)setsnoprogramactive(undefinedstate!).

37

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Basicshaderlayout•  Shader-Programsmusthaveamain()-method•  Vertex-Shaderoutputstoatleastgl_Position•  Fragment-Shadertocustomdefinedoutput

//preprocessordirectiveslike:#version150//variabledeclarationsvoidmain(){

//dosomethingandwriteintooutputvariables}

38

18/03/06

20

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

ShaderParameter•  Shadervariableexamples:

tuniformmat4projMatrix;//uniforminputinvec4vertex;//attribut-inputoutvec3fragColor;//shaderoutput

•  Threetypes:– uniform:doesnotchangeperprimitive;read-onlyinshaders

–  in:VS:inputchangespervertex,read-only;FS:interpolatedinput;read-only

– out:shader-output;VStoFS;FSoutput.39

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

UniformParameter•  Setuniformparametersinanapplication:

t//firstgetlocationprojMtxLoc=glGetUniformLocation(programHandle,"projMatrix");//thensetcurrentvalueglUniformMatrix4fv(projMtxLoc,1,GL_FALSE,currentProjectionMatrix);

–  Firstgetthe„location“oftheuniform-variable–  Thensetthecurrentvalue–  Canpassvaluestovertex-andfragment-shader

40

18/03/06

21

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

AttributeParameter•  Avertexcanhaveattributeslikeanormal-vectorortexture-coordinates

•  OpenGLalsotreatsthevertexitselfasanattribute

•  Wewanttoaccessourcurrentvertexwithinourvertex-shader(asweusedtodowithgl_VertexinformerGLSL-versions):

•  Therefore,wedeclareinourvertex-shader:tinvec4vertex;//vertexattribut

41

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

AttributeParameter•  Now,therearetwowaystopassdatatothisshaderattribute-variable,dependingon:–  ifyoujusthaveanarrayofvertices(VertexArray),– oranVBO(VertexBufferObject).

•  Todoso:Queryshader-variablelocation– Enablevertex-attributearray– Setpointertoarray– Drawanddisablearray

42

18/03/06

22

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

AttributeParameter:Vertex-Array•  ForaVertex-Array,passdatalikethis:

//firstgettheattribute-locationvertexLocation=glGetAttribLocation(programHandle,"vertex");//enableanarrayfortheattributeglEnableVertexAttribArray(vertexLocation);//setattributepointerglVertexAttribPointer(vertexLocation,3,GL_FLOAT,GL_FALSE,0,myVertexArray);//Draw("render")thetriangleglDrawArrays(GL_TRIANGLES,0,3);//Donewithrendering.DisablevertexattributearrayglDisableVertexAttribArray(vertexLocation);

43

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

AttributeParameter:VBO•  SettingattributeparameterswithVBO:

//firstgetlocationvertexLocation=glGetAttribLocation(programHandle,"vertex");//activatedesiredVBOglBindBuffer(GL_ARRAY_BUFFER,vertexBuffer);//setattribute-pointerglVertexAttribPointer(vertexLocation,4,GL_FLOAT,GL_FALSE,0,0);//finallyenableattribute-arrayglEnableVertexAttribArray(vertexLocation);...

44

18/03/06

23

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

FragmentOutput•  SinceGLSL1.3,gl_FragColorisdeprecated.•  Therefore,needtodefineoutputonourown.•  DeclareoutputvariableinFS:

outvec4fragColor;//fragmentcoloroutput

•  Intheapplication,beforelinkingtheshader-programwithglLinkProgram(),bindtheFS-output:glBindFragDataLocation(programHandle,0,"fragColor");

•  FinallyassignavaluetofragColorintheFS.45

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Exampleusage•  Anapplicationusingshaderscouldbasicallylooklikethis:

//Loadshaderandinitializeparameter-handles//Dosomeusefulstufflikebindingtexture,activate//texture-units,calculateandupdatematrices,etc.//glUseProgram(programHandle);//Setshader-parameters//Drawgeometry//glUseProgram(anotherProgramHandle);...

46

18/03/06

24

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

HELLOWORLD2DAppendixA

47

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Code(hw2d.zip)•  weusec++–see‘C++primer’.

•  nowwelookatthecodefromthetextbook•  Corecodes:

– asst1.cpp– glsupport.h/.cpp– asst1-gl3.fshader– asst1-gl3.vshader

•  Auxiliarycodes:– ppm.h/.cpp

48

18/03/06

25

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Code(hw2d.zip)

49

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

asst1.cpp•  Setg_Gl2Compatible=truetouseGLSL1.0and

g_Gl2Compatible=falsetouseGLSL1.3.

•  onMacOSXcurrentlythereisnowayofusingOpenGL3.xwithGLSL1.3whenGLUTisused.

•  Ifg_Gl2Compatible=true,shaderswith-gl2suffixwillbeloaded.

•  Ifg_Gl2Compatible=false,shaderswith-gl3suffixwillbeloaded.

•  Tocompletetheassignmentyouonlyneedtoedittheshaderfilesthatgetloaded

50

18/03/06

26

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

asst1.cpp•  Howtochecktheversionyouhave

cout<<"GLver:"<<glGetString(GL_VERSION)<<"\n";cout<<"GLEWver:"<<glewGetString(GLEW_VERSION)<<"\n";cout<<"GLSLver:"<<glGetString(GL_SHADING_LANGUAGE_VERSION)<<"\n";

•  OutputsGLver:2.1NVIDIA-8.12.47310.40.00.05f01GLEWver:1.10.0GLSLver:1.20

51

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

asst1.cppintmain(intargc,char**argv){try{ initGlutState(argc,argv);

glewInit();//loadtheOpenGLextensions

initGLState();initShaders();initGeometry();initTextures();

glutMainLoop();return0;

}catch(construntime_error&e){

cout<<"Exceptioncaught:"<<e.what()<<endl;return-1;

}}

52

18/03/06

27

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

OpenGLAPI•  libraryofroutinestocontrolgraphics•  callstocompileandloadshaders•  callstoloadvertexdatatovertexbuffers•  callstoloadtextures•  drawcalls•  callstosetvariousoptionsinthepipeline

53

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Systemissues•  needsincludeandlibraryfiles,andinstalleddrivers.•  crossplatform•  thealternativewouldbeDirectXgraphics–dominantforPCgames–notcrossplatform

•  wewilluse3.0weusetheglewlibrarytoaccesstheAPI

•  OurcurrentcodesonMac:– OpenGL3.2(GLSL1.3)doesn’twork– OpenGL2.1(GLSL1.2)worksinstead

54

18/03/06

28

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

GLUT•  libraryoffunctionstotalkwiththewindowingsystem

•  openupwindows•  glutcaninformyouwhensome“event”occurs–mousemove,buttonpress,windowresize

•  youregistercallbackfunctionswithglut–  thecallbackfunctioniscalledwhentheeventoccurs– andpassedrelevantinfo(ex.themouselocation)

•  crossplatform(windows/X)

55

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

GLSL•  glshadinglanguage•  youwritesmallprogramstobeexecutedforeachvertex•  youwritesmallprogramstobeexecutedforeach

fragment•  youtellopenGLtocompile/link/loadthese“shaders”

–  theyoperateinparallelontheverticesandfragments(SIMD)•  competitors

–  microsoft’shlsl:•  dominantforpcgames•  onlyworkswithdirectX

–  nvidia’scg•  almostidenticaltohlsl•  alsoworkswithopenGL

–  needcgGLlibrary•  futuresupportunclear.

56

18/03/06

29

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

main()•  initializeslotsofstuff•  communicateswithopenGLAPIbyloadingglew.•  handsoffallcontroltoglut

– glutwillcallbackourownfunctionswhenneededtodoupdatinganddrawing

57

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

initGlutState()•  turnsonglut•  requestsawindowwithcolor,depth,and“doublebuffering”

•  registersthenamesofourcallbackfunctions– wewilllookatthemsoon

58

18/03/06

30

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

initGlutState()staticvoidinitGlutState(intargc,char**argv){

glutInit(&argc,argv);glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);glutInitWindowSize(g_width,g_height);//createawindowglutCreateWindow("CS492B:HelloWorld");//titlethewindowglutDisplayFunc(display);//displayrenderingcallbackglutReshapeFunc(reshape);//windowreshapecallbackglutMotionFunc(motion);//mousemovementcallbackglutMouseFunc(mouse);//mouseclickcallbackglutKeyboardFunc(keyboard);

}staticvoidreshape(intw,inth){g_width=w;g_height=h;glViewport(0,0,w,h);glutPostRedisplay();}

59

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Doublebuffering•  Themonitordisplaysoneimageatatime•  Soifwerenderthenextimagetoscreen,thenrenderedprimitivespopup

•  Andevenworse,weoftenclearthescreenbeforegeneratinganewimage

•  Abettersolutionis”doublebuffering”

18/03/06

31

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

•  Usetwobuffers:onefrontandoneback•  Thefrontbufferisdisplayed•  Thebackbufferisrenderedto•  Whennewimagehasbeencreatedinbackbuffer,swapfrontandback

Doublebuffering

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

initGLState()•  setssomeopenGLcontrolstates

– backgroundcolor– plumbingforr/wofframebuffer– moderncolorspace

staticvoidinitGLState(){ glClearColor(128./255,200./255,1,0); glEnable(GL_FRAMEBUFFER_SRGB);}

62

18/03/06

32

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

VertexBufferObject(VBO)staticGLfloatsqVerts[12]={-.5,-.5,.5,.5,.5,-.5,-.5,-.5,-.5,.5,.5,.5};staticGLfloatsqCol[18]={1,0,0,0,1,1,0,0,1,1,0,0,0,1,0,0,1,1};

63

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

initVBOs()•  TransmittingthevertexdatafromtheCPUtotheGPUisanexpensiveprocess!

•  VertexBufferObjectistotransfervertexdataovertoOpenGL.

•  inourcase,wehaveattributesforposition,color,(andlater,texturecoordinates)

•  whenthesquaregeometryiscreated,thedataispassedtotheVBOs

64

18/03/06

33

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

initVBOs()staticvoidinitVBOs(void){

glGenBuffers(1,&sqVertB0); //createavertexbutterglBindBuffer(GL_ARRAY_BUFFER,sqVertB0);//bindthebuffertotheGLbufferglBufferData(//passdatatotheGLbuffer GL_ARRAY_BUFFER, 12*sizeof(GLfloat), sqVerts, GL_STATIC_DRAW);

glGenBuffers(1,&sqColB0)glBindBuffer(GL_ARRAY_BUFFER,sqColB0);glBufferData( GL_ARRAY_BUFFER, 18*sizeof(GLfloat), sqCol, GL_STATIC_DRAW);

}

65

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

initVBOs()•  OpenGLOrder:(0,1,2),(2,1,3),(2,3,4),...•  Consistorientationofthetrianglesgenerated.

66

18/03/06

34

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Display•  calledbyglutwhenthescreenneedsupdating•  clearsscreen(youcanignoredepthfornow)•  setstheprogram(fromtheshaderState)•  setssomeuniformvariablesintheshaders(morelater)

•  drawsthegeometry

67

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Display()staticvoiddisplay(void){

glUseProgram(h_program)glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);drawObj(sqVertB0,sqColB0,6);glutSwapBuffers();

}voiddrawObj(constShaderState&curSS){

glBindBuffer(GL_ARRAY_BUFFER,vertbo);safe_glVertexAttribPointer2(h_aVertex);safe_glEnableVertexAttribArray(h_aVertex);

glBindBuffer(GL_ARRAY_BUFFER,colbo);safe_glVertexAttribPointer3(h_aColor);safe_glEnableVertexAttribArray(h_aColor);glDrawArrays(GL_TRIANGLES,0,numverts);

safe_glDisableVertexAttribArray(h_aVertex);safe_glDisableVertexAttribArray(h_aColor);

} 68

18/03/06

35

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

VertexShader•  Typicaluseofthev-shader:

–  todeterminethefinalpositionoftheverticesonthescreen•  Input:theattributevariables(position,color,text.coor.)•  Output:thereservedoutputvariable,gl_Position•  Thexandycoordinatesofthisvariableareinterpolated

aspositionswithinthedrawingwindow.

69

Normalizedviewport

coordinates

(-1,-1)

(1,1)(-1,1)

(1,-1)

GLUTwindow&generalimage

coordinates(0,1)

(1,0)(0,0)

(1,1)

Normalizedtexture

coordinates

(0,0)

(1,1)(0,1)

(1,0)

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

VertexShader#version130uniformfloatuVertexScale;invec2aPosition;invec3aColor;invec2aTexCoord0,aTexCoord1;outvec3vColor;outvec2vTexCoord0,vTexCoord1;voidmain(){gl_Position=vec4(aPosition.x*uVertexScale,aPosition.y,0,1);vColor=aColor;vTexCoord0=aTexCoord0;vTexCoord1=aTexCoord1;}

70

18/03/06

36

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

FragmentShader•  Afterrasterization(it’snotprogrammable)•  Input:interpolateddataofvaryingvariables•  Output:colorvaluesintheframebuffer(apartofGPUmemory)

•  Controlthematerialandgeometricpropertiesofthematerialatthatpixel

71

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

FragmentShader#version130uniformfloatuVertexScale;uniformsampler2DuTexUnit0,uTexUnit1;invec2vTexCoord0,vTexCoord1;invec3vColor;outvec4fragColor;voidmain(void){vec4color=vec4(vColor.x,vColor.y,vColor.z,1);vec4texColor0=texture(uTexUnit0,vTexCoord0);vec4texColor1=texture(uTexUnit1,vTexCoord1);floatlerper=clamp(.5*uVertexScale,0.,1.);floatlerper2=clamp(.5*uVertexScale+1.0,0.0,1.0);fragColor=((lerper)*texColor1+(1.0-lerper)*texColor0)*lerper2+color*(1.0-lerper2);}

72

Asvaryingvariables,thetexturecoordinatesareinterpolatedfromtheirvertexvaluestoappropriatevaluesateachpixel.

18/03/06

37

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Texture•  auxiliaryimagedata•  readfromafile,loadedtoopenGL,usedinfragmentshader

•  initTextures•  glTextureisawrapperaroundatexturehandle•  loadTexture•  –readsfromfile,turnsonany“textureunit”,turnsonatexture,passesthedata.

•  bindseachtexturetoaunit(wehave2here)•  wewillsendthe“textureunit”infoasauniform(seedisplay)

73

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Reshape•  calledbyglutwhenthewindowsizechanges.•  wetellopenGLofthenewsize•  westorethisinfoforourownuse•  thenwecallglutPostRedisplaysothatglutwillknowtotriggeradisplaycallback.

74

18/03/06

38

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Interaction•  wewillusemousemotiontochangetheglobalgobject

•  thiswillbesenttotheuniformuVertexScale•  thiswillbeusedinthevertexshadertochangethexcoordinateofthevertices

75

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Interaction:Mouse•  callback•  called(duetoourregistration)wheneverthemouse

•  isclickeddownorup•  westorethisinformation–weneedtofliptheycoordinatefromglut

76

18/03/06

39

MinH.Kim(KAIST) Foundationsof3DComputerGraphics,S.Gortler,MITPress,2012

Interaction:Motion•  callback•  calledwheneverthemouseismoved•  hereiswhereweupdategobjectScale•  thenwecallglutPostRedisplaysothatglutwillknowtotriggeradisplaycallback.

•  seedisplayforuseofscale•  seevertexshaderforuseofscale

77

Recommended