File: DDSCubeMap.cs

package info (click to toggle)
opentk 1.1.4c%2Bdfsg-2.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 68,640 kB
  • sloc: cs: 525,501; xml: 277,501; ansic: 3,597; makefile: 41
file content (273 lines) | stat: -rw-r--r-- 9,787 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// This code was written for the OpenTK library and has been released
// to the Public Domain.
// It is provided "as is" without express or implied warranty of any kind.

using System;
using System.Drawing;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using System.IO;
using System.Text;

using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;

using Examples.Shapes;
using Examples.TextureLoaders;

namespace Examples.Tutorial
{
    [Example("DDS Cube Map", ExampleCategory.OpenGL, "2.x", Documentation = "DDSCubeMap")]
    public class T13_GLSL_Earth: GameWindow
    {
        public T13_GLSL_Earth( )
            : base( 800, 800 )
        {
        }

        #region internal Fields

        // Shader
        int VertexShaderObject, FragmentShaderObject, ProgramObject;
        const string VertexShaderFilename = "Data/Shaders/CubeMap_VS.glsl";
        const string FragmentShaderFilename = "Data/Shaders/CubeMap_FS.glsl";

        // Textures
        const TextureUnit TMU0_Unit = TextureUnit.Texture0;
        const int TMU0_UnitInteger = 0;
        const string TMU0_Filename = "Data/Textures/earth-cubemap.dds";
        uint TMU0_Handle;
        TextureTarget TMU0_Target;

        // DL
        DrawableShape sphere;

        // Camera
        Vector3 EyePos = new Vector3( 0.0f, 0.0f, 6.0f );
        Vector3 Trackball = Vector3.Zero;

        #endregion internal Fields

        /// <summary>Setup OpenGL and load resources here.</summary>
        /// <param name="e">Not used.</param>
        protected override void OnLoad(EventArgs e)
        {
            this.VSync = VSyncMode.Off;

            // Check for necessary capabilities:
            string extensions = GL.GetString(StringName.Extensions);
            if (!GL.GetString(StringName.Extensions).Contains("GL_ARB_shading_language"))
            {
                throw new NotSupportedException(String.Format("This example requires OpenGL 2.0. Found {0}. Aborting.",
                    GL.GetString(StringName.Version).Substring(0, 3)));
            }

            if (!extensions.Contains("GL_ARB_texture_compression") ||
                 !extensions.Contains("GL_EXT_texture_compression_s3tc"))
            {
                throw new NotSupportedException("This example requires support for texture compression. Aborting.");
            }

            #region GL State

            GL.ClearColor( 0f, 0f, 0f, 0f );

            GL.Disable( EnableCap.Dither );

            GL.Enable( EnableCap.CullFace );
            GL.FrontFace( FrontFaceDirection.Ccw );
            GL.PolygonMode( MaterialFace.Front, PolygonMode.Fill );
            //  GL.PolygonMode( MaterialFace.Back, PolygonMode.Line );

            #endregion GL State

            #region Shaders

            string LogInfo;

            // Load&Compile Vertex Shader

            using ( StreamReader sr = new StreamReader( VertexShaderFilename ) )
            {
                VertexShaderObject = GL.CreateShader( ShaderType.VertexShader );
                GL.ShaderSource( VertexShaderObject, sr.ReadToEnd( ) );
                GL.CompileShader( VertexShaderObject );
            }

            GL.GetShaderInfoLog( VertexShaderObject, out LogInfo );
            if ( LogInfo.Length > 0 && !LogInfo.Contains( "hardware" ) )
                Trace.WriteLine( "Vertex Shader failed!\nLog:\n" + LogInfo );
            else
                Trace.WriteLine( "Vertex Shader compiled without complaint." );

            // Load&Compile Fragment Shader

            using ( StreamReader sr = new StreamReader( FragmentShaderFilename ) )
            {
                FragmentShaderObject = GL.CreateShader( ShaderType.FragmentShader );
                GL.ShaderSource( FragmentShaderObject, sr.ReadToEnd( ) );
                GL.CompileShader( FragmentShaderObject );
            }
            GL.GetShaderInfoLog( FragmentShaderObject, out LogInfo );

            if ( LogInfo.Length > 0 && !LogInfo.Contains( "hardware" ) )
                Trace.WriteLine( "Fragment Shader failed!\nLog:\n" + LogInfo );
            else
                Trace.WriteLine( "Fragment Shader compiled without complaint." );

            // Link the Shaders to a usable Program
            ProgramObject = GL.CreateProgram( );
            GL.AttachShader( ProgramObject, VertexShaderObject );
            GL.AttachShader( ProgramObject, FragmentShaderObject );

            // link it all together
            GL.LinkProgram( ProgramObject );

            // flag ShaderObjects for delete when not used anymore
            GL.DeleteShader( VertexShaderObject );
            GL.DeleteShader( FragmentShaderObject );

            int[] temp = new int[1];
            GL.GetProgram(ProgramObject, GetProgramParameterName.LinkStatus, out temp[0]);
            Trace.WriteLine( "Linking Program (" + ProgramObject + ") " + ( ( temp[0] == 1 ) ? "succeeded." : "FAILED!" ) );
            if ( temp[0] != 1 )
            {
                GL.GetProgramInfoLog( ProgramObject, out LogInfo );
                Trace.WriteLine( "Program Log:\n" + LogInfo );
            }

            GL.GetProgram(ProgramObject, GetProgramParameterName.ActiveAttributes, out temp[0]);
            Trace.WriteLine( "Program registered " + temp[0] + " Attributes. (Should be 4: Pos, UV, Normal, Tangent)" );

            Trace.WriteLine( "Tangent attribute bind location: " + GL.GetAttribLocation( ProgramObject, "AttributeTangent" ) );

            Trace.WriteLine( "End of Shader build. GL Error: " + GL.GetError( ) );

            #endregion Shaders

            #region Textures

            TextureLoaderParameters.FlipImages = false;
            TextureLoaderParameters.MagnificationFilter = TextureMagFilter.Linear;
            TextureLoaderParameters.MinificationFilter = TextureMinFilter.Linear;
            TextureLoaderParameters.WrapModeS = TextureWrapMode.ClampToEdge;
            TextureLoaderParameters.WrapModeT = TextureWrapMode.ClampToEdge;
            TextureLoaderParameters.EnvMode = TextureEnvMode.Modulate;

            ImageDDS.LoadFromDisk( TMU0_Filename, out TMU0_Handle, out TMU0_Target );
            Trace.WriteLine( "Loaded " + TMU0_Filename + " with handle " + TMU0_Handle + " as " + TMU0_Target );

            #endregion Textures

            Trace.WriteLine( "End of Texture Loading. GL Error: " + GL.GetError( ) );
            Trace.WriteLine( "");

            sphere = new SlicedSphere(1.5f, Vector3d.Zero, SlicedSphere.eSubdivisions.Four, new SlicedSphere.eDir[] { SlicedSphere.eDir.All }, true);

        }

        protected override void OnUnload(EventArgs e)
        {
            sphere.Dispose();

            GL.DeleteProgram( ProgramObject );
            GL.DeleteTextures( 1, ref TMU0_Handle );

            base.OnUnload( e );
        }

        /// <summary>Respond to resize events here.</summary>
        /// <param name="e">Contains information on the new GameWindow size.</param>
        /// <remarks>There is no need to call the base implementation.</remarks>
        protected override void OnResize( EventArgs e )
        {
            GL.Viewport( 0, 0, Width, Height );

            GL.MatrixMode( MatrixMode.Projection );
            Matrix4 p = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Width / (float)Height, 0.1f, 10.0f);
            GL.LoadMatrix(ref p);

            GL.MatrixMode( MatrixMode.Modelview );
            GL.LoadIdentity( );

            base.OnResize( e );
        }

        /// <summary>Add your game logic here.</summary>
        /// <param name="e">Contains timing information.</param>
        /// <remarks>There is no need to call the base implementation.</remarks>
        protected override void OnUpdateFrame(FrameEventArgs e)
        {
            base.OnUpdateFrame(e);

            var keyboard = OpenTK.Input.Keyboard.GetState();
            var mouse = OpenTK.Input.Mouse.GetState();

            if (keyboard[OpenTK.Input.Key.Escape])
                this.Exit();
            if (keyboard[OpenTK.Input.Key.Space])
                Trace.WriteLine("GL: " + GL.GetError());

            Trackball.X = mouse.X;
            Trackball.Y = mouse.Y;
            Trackball.Z = mouse.Scroll.Y * 0.5f;
        }

        /// <summary>Add your game rendering code here.</summary>
        /// <param name="e">Contains timing information.</param>
        /// <remarks>There is no need to call the base implementation.</remarks>
       protected override void OnRenderFrame(FrameEventArgs e)
       {
           this.Title = "FPS: " + (1 / e.Time).ToString("0.");

           GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

           GL.UseProgram(ProgramObject);

           #region Textures

           GL.ActiveTexture(TMU0_Unit);
           GL.BindTexture(TMU0_Target, TMU0_Handle);

           #endregion Textures

           #region Uniforms

           GL.Uniform1(GL.GetUniformLocation(ProgramObject, "Earth"), TMU0_UnitInteger);

           #endregion Uniforms

           GL.PushMatrix();
           Matrix4 temp = Matrix4.LookAt(EyePos, Vector3.Zero, Vector3.UnitY);
           GL.MultMatrix(ref temp);

           GL.Rotate(Trackball.X, Vector3.UnitY);
           GL.Rotate(Trackball.Y, Vector3.UnitX);

           #region Draw

           GL.Color3(1f, 1f, 1f);

           sphere.Draw();

           #endregion Draw

           GL.PopMatrix();

           this.SwapBuffers();
       }

        /// <summary>Entry point</summary>
        [STAThread]
        public static void Main( )
        {
            using ( T13_GLSL_Earth example = new T13_GLSL_Earth( ) )
            {
                Utilities.SetWindowTitle(example);
                example.Run( 30.0, 0.0 );
            }
        }
    }
}