protected virtual void OnWidgetShuttingDown(object sender, System.EventArgs e) { GL.Finish(); OpenTK.Graphics.GraphicsContext current = (OpenTK.Graphics.GraphicsContext)OpenTK.Graphics.GraphicsContext.CurrentContext; current.MakeCurrent(null); current.Dispose(); }
public OpenTKGLContext( OpenTK.Platform.IWindowInfo windowInfo ) { // setup created glcontrol / gtk control this.windowInfo = windowInfo; this.graphicsContext = new GraphicsContext( GraphicsMode.Default, this.windowInfo ); Initialized = true; }
public static IGraphicsContext CreateGraphicsContext(GraphicsMode mode, IWindowInfo window, int major, int minor, GraphicsContextFlags flags) { GraphicsContext graphicsContext = new GraphicsContext(mode, window, major, minor, flags); graphicsContext.MakeCurrent(window); graphicsContext.LoadAll(); return (IGraphicsContext) graphicsContext; }
private GLVersion GetMaximumSupportedProfile() { var window = ((AndroidWindow)this.WindowInfo); using (var context = new OpenTK.Graphics.GraphicsContext(GraphicsMode.Default, window, (int)GLVersion.ES2, 0, GraphicsContextFlags.Embedded)) { context.MakeCurrent(window); PlatformConfigurations.RendererName = GL.GetString(StringName.Renderer); int version; if (!OpenGLUtils.GetCurrentGLVersion(out version)) { version = 200; } context.MakeCurrent(null); window.DestroySurface(); if (version >= 300) { return(GLVersion.ES3); } return(GLVersion.ES2); } }
public OpenGLGraphics(Form form) { this.form = form; var windowInfo = Utilities.CreateWindowsWindowInfo(form.Handle); context = new GraphicsContext(GraphicsMode.Default, windowInfo); context.MakeCurrent(windowInfo); context.LoadAll(); GL.Enable(EnableCap.DepthTest); GL.ShadeModel(ShadingModel.Smooth); GL.Enable(EnableCap.Lighting); GL.Light(LightName.Light0, LightParameter.Ambient, new[] {.2f, .2f, .2f, 1.0f}); GL.Light(LightName.Light0, LightParameter.Diffuse, new[] {1, 1, 1, 1.0f}); GL.Light(LightName.Light0, LightParameter.Position, new[] {Common.LightX, Common.LightY, Common.LightZ}); GL.Enable(EnableCap.Light0); GL.MatrixMode(MatrixMode.Projection); Matrix4 prespective = Matrix4.CreatePerspectiveFieldOfView(Common.FieldOfView, (float)form.ClientSize.Width / (float)form.ClientSize.Height, Common.NearPlane, Common.FarPlane); GL.LoadMatrix(ref prespective); GL.MatrixMode(MatrixMode.Modelview); Matrix4 view = Matrix4.CreateTranslation(Common.CameraX, Common.CameraY, Common.CameraZ) * Matrix4.CreateRotationY(Common.CameraRotationY); GL.LoadMatrix(ref view); }
private void CreateContext(Form form) { var windowInfo = Utilities.CreateWindowsWindowInfo(form.Handle); context = new GraphicsContext(GraphicsMode.Default, windowInfo); context.MakeCurrent(windowInfo); context.LoadAll(); GL.Enable(EnableCap.DepthTest); }
public OpenGLGraphics(Form form, Common common) { this.form = form; this.common = common; var windowInfo = Utilities.CreateWindowsWindowInfo(form.Handle); context = new GraphicsContext(GraphicsMode.Default, windowInfo); context.MakeCurrent(windowInfo); context.LoadAll(); }
public DummyGLContext(ContextHandle handle, GraphicsContext.GetAddressDelegate loader) : this() { if (handle != ContextHandle.Zero) { Handle = handle; } Loader = loader; Mode = new GraphicsMode(new IntPtr(2), 32, 16, 0, 0, 0, 2, false); }
public Graphics(IApplicationWindow window) { _window = window; IntPtr handle = _window.GetHandle(); wi = GetWindowInfo(handle); //GraphicsMode graphicsMode = GraphicsMode.Default; GraphicsMode graphicsMode = new GraphicsMode(new ColorFormat(32), 16); _graphicsContext = new GraphicsContext( graphicsMode, wi); }
/// <summary> /// Creates an IGraphicsContext instance for the specified window. /// </summary> /// <param name="mode">The GraphicsMode for the GraphicsContext.</param> /// <param name="window">An IWindowInfo instance describing the parent window for this IGraphicsContext.</param> /// <param name="major">The major OpenGL version number for this IGraphicsContext.</param> /// <param name="minor">The minor OpenGL version number for this IGraphicsContext.</param> /// <param name="flags">A bitwise collection of GraphicsContextFlags with specific options for this IGraphicsContext.</param> /// <returns>A new IGraphicsContext instance.</returns> public static IGraphicsContext CreateGraphicsContext( GraphicsMode mode, IWindowInfo window, int major, int minor, GraphicsContextFlags flags) { GraphicsContext context = new GraphicsContext(mode, window, major, minor, flags); context.MakeCurrent(window); (context as IGraphicsContextInternal).LoadAll(); return context; }
public ErrorHelper(IGraphicsContext context) { if (context == null) throw new GraphicsContextMissingException(); this.Context = (GraphicsContext) context; lock (ErrorHelper.SyncRoot) { if (ErrorHelper.ContextErrors.ContainsKey(this.Context)) return; ErrorHelper.ContextErrors.Add(this.Context, new List<ErrorCode>()); } }
public ErrorHelper(IGraphicsContext context) { if (context == null) throw new GraphicsContextMissingException(); Context = (GraphicsContext)context; lock (SyncRoot) { if (!ContextErrors.ContainsKey(Context)) ContextErrors.Add(Context, new List<ErrorCode>()); } ResetErrors(); }
public static void Main() { using (Toolkit.Init(new ToolkitOptions { Backend = PlatformBackend.PreferNative })) { // Create a window and context using a third-party toolkit // (in this case SDL2) var window = SDL.CreateWindow("Test", 0, 0, 640, 480, WindowFlags.AllowHighDpi | WindowFlags.OpenGL); var context = SDL.GL.CreateContext(window); // The external context must be made current, // in order to correctly initialize OpenTK.Graphics SDL.GL.MakeCurrent(window, context); // Now we need to initialize OpenTK.Graphics using // the external context. This can be achieved in // two ways: // // var dummy = new GraphicsContext(ContextHandle.Zero, null); // -- or -- // var dummy = new GraphicsContext( // new ContextHandle(context), // (name) => SDL.GL.GetAddress(name), // () => new ContextHandle(SDL.GL.GetCurrentContext())); // // The first approach works only on Windows, Mac and Linux/X11. // // The second approach will work on all platforms supported // by the external toolkit. This means that you can use // OpenTK.Graphics everywhere, even on platforms not directly // supported by OpenTK. using (var dummy = new GraphicsContext( new ContextHandle(context), SDL.GL.GetAddress, () => new ContextHandle(SDL.GL.GetCurrentContext()))) { for (int i = 0; i < 100; i++) { SDL.PumpEvents(); GL.ClearColor(i / 100.0f, i / 100.0f, i / 100.0f, i / 100.0f); GL.Clear(ClearBufferMask.ColorBufferBit); SDL.GL.SwapWindow(window); } SDL.DestroyWindow(window); } } }
static void Main(string[] args) { ContextSettings contextSettings = new ContextSettings(24, 0, 0); var window = new RenderWindow(new SFML.Window.VideoMode(640, 480), "ImGui + SFML + .Net = <3", Styles.Default, contextSettings); OpenTK.Graphics.GraphicsMode graphicsMode = new OpenTK.Graphics.GraphicsMode(32, (int)contextSettings.DepthBits, (int)contextSettings.StencilBits, (int)contextSettings.AntialiasingLevel); OpenTK.Platform.IWindowInfo windowInfo = OpenTK.Platform.Utilities.CreateWindowsWindowInfo(window.SystemHandle); OpenTK.Graphics.GraphicsContext context = new OpenTK.Graphics.GraphicsContext(graphicsMode, windowInfo); context.MakeCurrent(windowInfo); context.LoadAll(); window.SetFramerateLimit(60); ImGuiSfml.Init(window); window.Closed += (s, e) => window.Close(); CircleShape shape = new CircleShape(100); shape.FillColor = Color.Green; Clock deltaClock = new Clock(); while (window.IsOpen) { window.DispatchEvents(); ImGuiSfml.Update(window, deltaClock.Restart()); ImGui.ShowDemoWindow(); //ImGui.ShowTestWindow(); /* * ImGui.Begin("Hello, world!"); * ImGui.Button("Look at this pretty button"); * ImGui.End(); */ window.Clear(); window.Draw(shape); ImGuiSfml.Render(window); window.Display(); } }
// TODO: make a not terrible constructor public Renderer(IntPtr handle, int width, int height) { renderWidth = width; renderHeight = height; GraphicsContext = new GraphicsContext(GraphicsMode.Default, Utilities.CreateWindowsWindowInfo(handle)); GraphicsContext.LoadAll(); GL.Enable(EnableCap.DepthTest); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); Camera = new Camera(new Vector3(0.0f, 0.0f, 0.0f), 0, 0, 0, 90, new Vector2(width, height)); DefaultRenderTextureShader defaultRenderTextureShader = new DefaultRenderTextureShader(); _renderTextureMesh = new RenderTextureMesh(defaultRenderTextureShader); RenderTexture = new RenderTexture(width, height, defaultRenderTextureShader); }
public unsafe SimpleGLWindow(string title, int desiredWidth, int desiredHeight) { _nativeWindow = new NativeWindow(desiredWidth, desiredHeight, title, GameWindowFlags.Default, GraphicsMode.Default, DisplayDevice.Default); _scaleFactor = NativeWindow.Width / desiredWidth; GraphicsContextFlags flags = GraphicsContextFlags.Default; _graphicsContext = new GraphicsContext(GraphicsMode.Default, NativeWindow.WindowInfo, 3, 0, flags); _graphicsContext.MakeCurrent(NativeWindow.WindowInfo); ((IGraphicsContextInternal)_graphicsContext).LoadAll(); // wtf is this? GL.ClearColor(Color.Black); NativeWindow.Closing += OnWindowClosing; NativeWindow.KeyDown += OnKeyDown; NativeWindow.KeyUp += OnKeyUp; NativeWindow.KeyPress += OnKeyPress; ImGui.LoadDefaultFont(); SetOpenTKKeyMappings(); CreateDeviceObjects(); }
public static void Main() { using (Toolkit.Init(new ToolkitOptions { Backend = PlatformBackend.PreferNative })) { var window = Sdl2.CreateWindow("Test", 0, 0, 640, 480, WindowFlags.AllowHighDpi | WindowFlags.OpenGL); var context = Sdl2.CreateContext(window); Sdl2.MakeCurrent(window, context); using (var dummy = new GraphicsContext(new ContextHandle(context), OpenTK.Platform.Utilities.CreateDummyWindowInfo())) { for (int i = 0; i < 100; i++) { Sdl2.PumpEvents(); GL.ClearColor(i / 100.0f, i / 100.0f, i / 100.0f, i / 100.0f); GL.Clear(ClearBufferMask.ColorBufferBit); Sdl2.SwapWindow(window); } Sdl2.DestroyWindow(window); } } }
IEnumerable<GraphicsMode> GetModesARB(INativeWindow native) { using (IGraphicsContext context = new GraphicsContext( new GraphicsMode(new IntPtr(2), new ColorFormat(), 0, 0, 0, new ColorFormat(), 2, false), (WinWindowInfo)native.WindowInfo, 1, 0, GraphicsContextFlags.Default)) { WinWindowInfo window = (WinWindowInfo)native.WindowInfo; // See http://www.opengl.org/registry/specs/ARB/wgl_pixel_format.txt // for more details Debug.Write("Retrieving ARB pixel formats.... "); if (Wgl.Delegates.wglChoosePixelFormatARB == null || Wgl.Delegates.wglGetPixelFormatAttribivARB == null) { Debug.WriteLine("failed."); yield break; } int[] attribs = new int[] { (int)WGL_ARB_pixel_format.AccelerationArb, (int)WGL_ARB_pixel_format.RedBitsArb, (int)WGL_ARB_pixel_format.GreenBitsArb, (int)WGL_ARB_pixel_format.BlueBitsArb, (int)WGL_ARB_pixel_format.AlphaBitsArb, (int)WGL_ARB_pixel_format.ColorBitsArb, (int)WGL_ARB_pixel_format.DepthBitsArb, (int)WGL_ARB_pixel_format.StencilBitsArb, (int)WGL_ARB_multisample.SampleBuffersArb, (int)WGL_ARB_multisample.SamplesArb, (int)WGL_ARB_pixel_format.AccumRedBitsArb, (int)WGL_ARB_pixel_format.AccumGreenBitsArb, (int)WGL_ARB_pixel_format.AccumBlueBitsArb, (int)WGL_ARB_pixel_format.AccumAlphaBitsArb, (int)WGL_ARB_pixel_format.AccumBitsArb, (int)WGL_ARB_pixel_format.DoubleBufferArb, (int)WGL_ARB_pixel_format.StereoArb, 0 }; int[] values = new int[attribs.Length]; int[] attribs_values = new int[] { (int)WGL_ARB_pixel_format.AccelerationArb, (int)WGL_ARB_pixel_format.FullAccelerationArb, (int)WGL_ARB_pixel_format.SupportOpenglArb, 1, (int)WGL_ARB_pixel_format.DrawToWindowArb, 1, 0, 0 }; int[] num_formats = new int[1]; // Get the number of available formats if (Wgl.Arb.ChoosePixelFormat(window.DeviceContext, attribs_values, null, 0, null, num_formats)) { // Create an array big enough to hold all available formats and get those formats int[] pixel = new int[num_formats[0]]; if (Wgl.Arb.ChoosePixelFormat(window.DeviceContext, attribs_values, null, pixel.Length, pixel, num_formats)) { foreach (int p in pixel) { // Find out what we really got as a format: if (!Wgl.Arb.GetPixelFormatAttrib(window.DeviceContext, p, 0, attribs.Length - 1, attribs, values)) { Debug.Print("[Warning] Failed to detect attributes for PixelFormat:{0}.", p); continue; } GraphicsMode mode = new GraphicsMode(new IntPtr(p), new ColorFormat(values[1], values[2], values[3], values[4]), values[6], values[7], values[8] != 0 ? values[9] : 0, new ColorFormat(values[10], values[11], values[12], values[13]), values[15] == 1 ? 2 : 1, values[16] == 1 ? true : false); yield return mode; } } } } }
private GLVersion GetMaximumSupportedProfile() { var window = ((AndroidWindow)this.WindowInfo); using (var context = new OpenTK.Graphics.GraphicsContext(GraphicsMode.Default, window, (int)GLVersion.ES2, 0, GraphicsContextFlags.Embedded)) { context.MakeCurrent(window); PlatformConfigurations.RendererName = GL.GetString(StringName.Renderer); int version; if (!OpenGLUtils.GetCurrentGLVersion(out version)) { version = 200; } context.MakeCurrent(null); window.DestroySurface(); if (version >= 300) { return GLVersion.ES3; } return GLVersion.ES2; } }
/// <summary> /// The main entry point for the application. /// </summary> static void Main() { // Request a 24-bits depth buffer when creating the window ContextSettings contextSettings = new ContextSettings(); contextSettings.DepthBits = 24; // Create the main window RenderWindow window = new RenderWindow(new VideoMode(800, 600), "SFML graphics with OpenGL", Styles.Default, contextSettings); window.SetVerticalSyncEnabled(true); // Initialize OpenTK Toolkit.Init(); GraphicsContext context = new GraphicsContext(new ContextHandle(IntPtr.Zero), null); // Setup event handlers window.Closed += new EventHandler(OnClosed); window.KeyPressed += new EventHandler<KeyEventArgs>(OnKeyPressed); window.Resized += new EventHandler<SizeEventArgs>(OnResized); // Create a sprite for the background Sprite background = new Sprite(new Texture("resources/background.jpg")); // Create a text to display on top of the OpenGL object Text text = new Text("SFML / OpenGL demo", new Font("resources/sansation.ttf")); text.Position = new Vector2f(250, 450); text.Color = new Color(255, 255, 255, 170); // Make the window the active target for OpenGL calls window.SetActive(); // Load an OpenGL texture. // We could directly use a SFML.Graphics.Texture as an OpenGL texture (with its Bind() member function), // but here we want more control on it (generate mipmaps, ...) so we create a new one int texture = 0; using (Image image = new Image("resources/texture.jpg")) { GL.GenTextures(1, out texture); GL.BindTexture(TextureTarget.Texture2D, texture); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, (int)image.Size.X, (int)image.Size.Y, 0, PixelFormat.Rgba, PixelType.UnsignedByte, image.Pixels); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); } // Enable Z-buffer read and write GL.Enable(EnableCap.DepthTest); GL.DepthMask(true); GL.ClearDepth(1); // Disable lighting GL.Disable(EnableCap.Lighting); // Configure the viewport (the same size as the window) GL.Viewport(0, 0, (int)window.Size.X, (int)window.Size.Y); // Setup a perspective projection GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); float ratio = (float)(window.Size.X) / window.Size.Y; GL.Frustum(-ratio, ratio, -1, 1, 1, 500); // Bind the texture GL.Enable(EnableCap.Texture2D); GL.BindTexture(TextureTarget.Texture2D, texture); // Define a 3D cube (6 faces made of 2 triangles composed by 3 vertices) float[] cube = new float[] { // positions // texture coordinates -20, -20, -20, 0, 0, -20, 20, -20, 1, 0, -20, -20, 20, 0, 1, -20, -20, 20, 0, 1, -20, 20, -20, 1, 0, -20, 20, 20, 1, 1, 20, -20, -20, 0, 0, 20, 20, -20, 1, 0, 20, -20, 20, 0, 1, 20, -20, 20, 0, 1, 20, 20, -20, 1, 0, 20, 20, 20, 1, 1, -20, -20, -20, 0, 0, 20, -20, -20, 1, 0, -20, -20, 20, 0, 1, -20, -20, 20, 0, 1, 20, -20, -20, 1, 0, 20, -20, 20, 1, 1, -20, 20, -20, 0, 0, 20, 20, -20, 1, 0, -20, 20, 20, 0, 1, -20, 20, 20, 0, 1, 20, 20, -20, 1, 0, 20, 20, 20, 1, 1, -20, -20, -20, 0, 0, 20, -20, -20, 1, 0, -20, 20, -20, 0, 1, -20, 20, -20, 0, 1, 20, -20, -20, 1, 0, 20, 20, -20, 1, 1, -20, -20, 20, 0, 0, 20, -20, 20, 1, 0, -20, 20, 20, 0, 1, -20, 20, 20, 0, 1, 20, -20, 20, 1, 0, 20, 20, 20, 1, 1 }; // Enable position and texture coordinates vertex components GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.TextureCoordArray); GL.VertexPointer(3, VertexPointerType.Float, 5 * sizeof(float), Marshal.UnsafeAddrOfPinnedArrayElement(cube, 0)); GL.TexCoordPointer(2, TexCoordPointerType.Float, 5 * sizeof(float), Marshal.UnsafeAddrOfPinnedArrayElement(cube, 3)); // Disable normal and color vertex components GL.DisableClientState(ArrayCap.NormalArray); GL.DisableClientState(ArrayCap.ColorArray); Clock clock = new Clock(); // Start game loop while (window.IsOpen) { // Process events window.DispatchEvents(); // Clear the window GL.Clear(ClearBufferMask.DepthBufferBit); // Draw background window.PushGLStates(); window.Draw(background); window.PopGLStates(); // Clear the depth buffer GL.Clear(ClearBufferMask.DepthBufferBit); // We get the position of the mouse cursor, so that we can move the box accordingly float x = Mouse.GetPosition(window).X * 200.0F / window.Size.X - 100.0F; float y = -Mouse.GetPosition(window).Y * 200.0F / window.Size.Y + 100.0F; // Apply some transformations GL.MatrixMode(MatrixMode.Modelview); GL.LoadIdentity(); GL.Translate(x, y, -100.0F); GL.Rotate(clock.ElapsedTime.AsSeconds() * 50, 1.0F, 0.0F, 0.0F); GL.Rotate(clock.ElapsedTime.AsSeconds() * 30, 0.0F, 1.0F, 0.0F); GL.Rotate(clock.ElapsedTime.AsSeconds() * 90, 0.0F, 0.0F, 1.0F); // Draw the cube GL.DrawArrays(OpenTK.Graphics.OpenGL.PrimitiveType.Triangles, 0, 36); // Draw some text on top of our OpenGL object window.PushGLStates(); window.Draw(text); window.PopGLStates(); // Finally, display the rendered frame on screen window.Display(); } // Don't forget to destroy our texture GL.DeleteTextures(1, ref texture); }
GraphicsMode SelectGraphicsModeARB(ColorDepth color, int depth, int stencil, int samples, ColorDepth accum, int buffers, bool stereo) { using (INativeWindow native_window = new NativeWindow()) using (IGraphicsContext context = new GraphicsContext(new GraphicsMode(new ColorFormat(), 0, 0, 0, new ColorFormat(), 2, false), native_window.WindowInfo, 1, 0, GraphicsContextFlags.Default)) { WinWindowInfo window = (WinWindowInfo)native_window.WindowInfo; Debug.Write("Selecting pixel format (ARB)... "); if (Wgl.Delegates.wglChoosePixelFormatARB == null || Wgl.Delegates.wglGetPixelFormatAttribivARB == null) { Debug.WriteLine("failed"); return null; } int[] attribs = new int[] { (int)WGL_ARB_pixel_format.AccelerationArb, (int)WGL_ARB_pixel_format.AlphaBitsArb, (int)WGL_ARB_pixel_format.RedBitsArb, (int)WGL_ARB_pixel_format.GreenBitsArb, (int)WGL_ARB_pixel_format.BlueBitsArb, (int)WGL_ARB_pixel_format.ColorBitsArb, (int)WGL_ARB_pixel_format.DepthBitsArb, (int)WGL_ARB_pixel_format.StencilBitsArb, (int)WGL_ARB_multisample.SampleBuffersArb, (int)WGL_ARB_multisample.SamplesArb, (int)WGL_ARB_pixel_format.AccumAlphaBitsArb, (int)WGL_ARB_pixel_format.AccumRedBitsArb, (int)WGL_ARB_pixel_format.AccumGreenBitsArb, (int)WGL_ARB_pixel_format.AccumBlueBitsArb, (int)WGL_ARB_pixel_format.AccumBitsArb, (int)WGL_ARB_pixel_format.DoubleBufferArb, (int)WGL_ARB_pixel_format.StereoArb, 0 }; int[] values = new int[attribs.Length]; int[] attribs_values = new int[] { (int)WGL_ARB_pixel_format.AccelerationArb, (int)WGL_ARB_pixel_format.FullAccelerationArb, (int)WGL_ARB_pixel_format.RedBitsArb, color.Red, (int)WGL_ARB_pixel_format.GreenBitsArb, color.Green, (int)WGL_ARB_pixel_format.BlueBitsArb, color.Blue, (int)WGL_ARB_pixel_format.AlphaBitsArb, color.Alpha, (int)WGL_ARB_pixel_format.ColorBitsArb, color.BitsPerPixel, (int)WGL_ARB_pixel_format.DepthBitsArb, depth, (int)WGL_ARB_pixel_format.StencilBitsArb, stencil, (int)WGL_ARB_multisample.SampleBuffersArb, samples > 0 ? 1 : 0, (int)WGL_ARB_multisample.SamplesArb, samples, (int)WGL_ARB_pixel_format.AccumRedBitsArb, accum.Red, (int)WGL_ARB_pixel_format.AccumGreenBitsArb, accum.Green, (int)WGL_ARB_pixel_format.AccumBlueBitsArb, accum.Blue, (int)WGL_ARB_pixel_format.AccumAlphaBitsArb, accum.Alpha, (int)WGL_ARB_pixel_format.AccumBitsArb, accum.BitsPerPixel, (int)WGL_ARB_pixel_format.DoubleBufferArb, 1, (int)WGL_ARB_pixel_format.StereoArb, stereo ? 1 : 0, 0, 0 }; int[] pixel = new int[1], num_formats = new int[1]; Wgl.Arb.ChoosePixelFormat(window.DeviceContext, attribs_values, null, 1, pixel, num_formats); if (num_formats[0] == 0 || pixel[0] == 0) { // Try again without an accumulator. Many modern cards cannot accelerate multisampled formats with accumulator buffers. attribs_values[10 * 2 + 1] = attribs_values[11 * 2 + 1] = attribs_values[12 * 2 + 1] = attribs_values[13 * 2 + 1] = attribs_values[14 * 2 + 1] = 0; Wgl.Arb.ChoosePixelFormat(window.DeviceContext, attribs_values, null, 1, pixel, num_formats); } if (num_formats[0] == 0 || pixel[0] == 0) { Debug.WriteLine("failed"); return null; } // Find out what we really got as a format: Wgl.Arb.GetPixelFormatAttrib(window.DeviceContext, pixel[0], 0, attribs.Length, attribs, values); GraphicsMode mode = new GraphicsMode(new IntPtr(pixel[0]), new ColorDepth(values[1], values[2], values[3], values[4]), values[6], values[7], values[8] != 0 ? values[9] : 0, new ColorDepth(values[10], values[11], values[12], values[13]), values[15] == 1 ? 2 : 1, values[16] == 1 ? true : false); Debug.WriteLine("success!"); return mode; } }
GraphicsMode SelectGraphicsModeARB(ColorDepth color, int depth, int stencil, int samples, ColorDepth accum, int buffers, bool stereo) { using (INativeWindow2 native_window = new NativeWindow()) using (IGraphicsContext context = new GraphicsContext(new GraphicsMode(new ColorFormat(), 0, 0, 0, new ColorFormat(), 2, false), native_window.WindowInfo, 1, 0, GraphicsContextFlags.Default)) { WinWindowInfo window = (WinWindowInfo)native_window.WindowInfo; // See http://www.opengl.org/registry/specs/ARB/wgl_pixel_format.txt // for more details Debug.Write("Selecting pixel format (ARB)... "); if (Wgl.Delegates.wglChoosePixelFormatARB == null || Wgl.Delegates.wglGetPixelFormatAttribivARB == null) { Debug.WriteLine("failed"); return null; } int[] attribs = new int[] { (int)WGL_ARB_pixel_format.AccelerationArb, (int)WGL_ARB_pixel_format.RedBitsArb, (int)WGL_ARB_pixel_format.GreenBitsArb, (int)WGL_ARB_pixel_format.BlueBitsArb, (int)WGL_ARB_pixel_format.AlphaBitsArb, (int)WGL_ARB_pixel_format.ColorBitsArb, (int)WGL_ARB_pixel_format.DepthBitsArb, (int)WGL_ARB_pixel_format.StencilBitsArb, (int)WGL_ARB_multisample.SampleBuffersArb, (int)WGL_ARB_multisample.SamplesArb, (int)WGL_ARB_pixel_format.AccumRedBitsArb, (int)WGL_ARB_pixel_format.AccumGreenBitsArb, (int)WGL_ARB_pixel_format.AccumBlueBitsArb, (int)WGL_ARB_pixel_format.AccumAlphaBitsArb, (int)WGL_ARB_pixel_format.AccumBitsArb, (int)WGL_ARB_pixel_format.DoubleBufferArb, (int)WGL_ARB_pixel_format.StereoArb, 0 }; int[] values = new int[attribs.Length]; int[] attribs_values = new int[] { (int)WGL_ARB_pixel_format.AccelerationArb, (int)WGL_ARB_pixel_format.FullAccelerationArb, (int)WGL_ARB_pixel_format.DrawToWindowArb, 1, (int)WGL_ARB_pixel_format.RedBitsArb, color.Red, (int)WGL_ARB_pixel_format.GreenBitsArb, color.Green, (int)WGL_ARB_pixel_format.BlueBitsArb, color.Blue, (int)WGL_ARB_pixel_format.AlphaBitsArb, color.Alpha, (int)WGL_ARB_pixel_format.ColorBitsArb, color.BitsPerPixel - color.Alpha, // Should not contain alpha bpp (see spec) (int)WGL_ARB_pixel_format.DepthBitsArb, depth, (int)WGL_ARB_pixel_format.StencilBitsArb, stencil, (int)WGL_ARB_multisample.SampleBuffersArb, samples > 0 ? 1 : 0, (int)WGL_ARB_multisample.SamplesArb, samples, (int)WGL_ARB_pixel_format.AccumRedBitsArb, accum.Red, (int)WGL_ARB_pixel_format.AccumGreenBitsArb, accum.Green, (int)WGL_ARB_pixel_format.AccumBlueBitsArb, accum.Blue, (int)WGL_ARB_pixel_format.AccumAlphaBitsArb, accum.Alpha, (int)WGL_ARB_pixel_format.AccumBitsArb, accum.BitsPerPixel, // Spec doesn't mention wether alpha bpp should be included... (int)WGL_ARB_pixel_format.DoubleBufferArb, buffers > 1 ? 1 : 0, (int)WGL_ARB_pixel_format.StereoArb, stereo ? 1 : 0, 0, 0 }; int[] pixel = new int[1], num_formats = new int[1]; bool success = Wgl.Arb.ChoosePixelFormat(window.DeviceContext, attribs_values, null, 1, pixel, num_formats); if (!success || num_formats[0] == 0 || pixel[0] == 0) { // Try again without an accumulator. Many modern cards cannot accelerate multisampled formats with accumulator buffers. int index_of_accum = Array.IndexOf(attribs_values, (int)WGL_ARB_pixel_format.AccumRedBitsArb); attribs_values[index_of_accum + 1] = attribs_values[index_of_accum + 3] = attribs_values[index_of_accum + 5] = attribs_values[index_of_accum + 7] = attribs_values[index_of_accum + 9] = 0; Wgl.Arb.ChoosePixelFormat(window.DeviceContext, attribs_values, null, 1, pixel, num_formats); } if (!success || num_formats[0] == 0 || pixel[0] == 0) { Debug.WriteLine("failed (no suitable pixel format)."); return null; } // Find out what we really got as a format: success = Wgl.Arb.GetPixelFormatAttrib(window.DeviceContext, pixel[0], 0, attribs.Length - 1, attribs, values); if (!success) { Debug.WriteLine("failed (pixel format attributes could not be determined)."); return null; } GraphicsMode mode = new GraphicsMode(new IntPtr(pixel[0]), new ColorDepth(values[1], values[2], values[3], values[4]), values[6], values[7], values[8] != 0 ? values[9] : 0, new ColorDepth(values[10], values[11], values[12], values[13]), values[15] == 1 ? 2 : 1, values[16] == 1 ? true : false); Debug.WriteLine("success!"); return mode; } }
void TextureThread() { try { OpenTK.INativeWindow newwindow = new OpenTK.NativeWindow(); OpenTK.INativeWindow window = newwindow; OpenTK.Graphics.IGraphicsContext newcontext = new OpenTK.Graphics.GraphicsContext(GLMode, window.WindowInfo); OpenTK.Graphics.IGraphicsContext context = newcontext; context.MakeCurrent(window.WindowInfo); TextureThreadContextReady.Set(); PendingTextures.Open(); Logger.DebugLog("Started Texture Thread"); while (window.Exists && TextureThreadRunning) { window.ProcessEvents(); TextureLoadItem item = null; if (!PendingTextures.Dequeue(Timeout.Infinite, ref item)) continue; if (LoadTexture(item.TeFace.TextureID, ref item.Data.Texture, false)) { OpenTK.Graphics.OpenGL.GL.GenTextures(1, out item.Data.TexturePointer); OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, item.Data.TexturePointer); Bitmap bitmap = new Bitmap(item.Data.Texture); bool hasAlpha; if (item.Data.Texture.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb) { hasAlpha = true; } else { hasAlpha = false; } item.Data.IsAlpha = hasAlpha; bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); Rectangle rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height); BitmapData bitmapData = bitmap.LockBits( rectangle, ImageLockMode.ReadOnly, hasAlpha ? System.Drawing.Imaging.PixelFormat.Format32bppArgb : System.Drawing.Imaging.PixelFormat.Format24bppRgb); OpenTK.Graphics.OpenGL.GL.TexImage2D( OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, hasAlpha ? OpenTK.Graphics.OpenGL.PixelInternalFormat.Rgba : OpenTK.Graphics.OpenGL.PixelInternalFormat.Rgb8, bitmap.Width, bitmap.Height, 0, hasAlpha ? OpenTK.Graphics.OpenGL.PixelFormat.Bgra : OpenTK.Graphics.OpenGL.PixelFormat.Bgr, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, bitmapData.Scan0); //// Auto detect if mipmaps are supported //int[] MipMapCount = new int[1]; //OpenTK.Graphics.OpenGL.GL.GetTexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.GetTextureParameter.TextureMaxLevel, out MipMapCount[0]); //OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMagFilter, (int)OpenTK.Graphics.OpenGL.TextureMagFilter.Linear); //if (MipMapCount[0] == 0) // if no MipMaps are present, use linear Filter //{ // OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear); //} //else //{ // OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, (int)OpenTK.Graphics.OpenGL.TextureMinFilter.LinearMipmapLinear); // OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapS, (int)OpenTK.Graphics.OpenGL.TextureWrapMode.Repeat); // OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapT, (int)OpenTK.Graphics.OpenGL.TextureWrapMode.Repeat); // OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.GenerateMipmap, 1); // OpenTK.Graphics.OpenGL.GL.GenerateMipmap(OpenTK.Graphics.OpenGL.GenerateMipmapTarget.Texture2D); //} //if (!enablemipmapd) if (instance.Config.CurrentConfig.DisableMipmaps) { OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear); } else { if (MipmapsSupported) { try { OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, (int)OpenTK.Graphics.OpenGL.TextureMinFilter.LinearMipmapLinear); OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapS, (int)OpenTK.Graphics.OpenGL.TextureWrapMode.Repeat); OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapT, (int)OpenTK.Graphics.OpenGL.TextureWrapMode.Repeat); OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.GenerateMipmap, 1); OpenTK.Graphics.OpenGL.GL.GenerateMipmap(OpenTK.Graphics.OpenGL.GenerateMipmapTarget.Texture2D); } catch { OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear); if (!msgdisplayed) { //Logger.Log("META3D TextureThread: Your video card does not support Mipmap. Try disabling Mipmaps from META3D tab under the Application/Preferences menu", Helpers.LogLevel.Warning); MessageBox.Show("Your video card does not support Mipmaps.\nDisable Mipmaps from the META3D tab under\nthe Application/Preferences menu"); msgdisplayed = true; } } } else { OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear); if (!msgdisplayed) { MessageBox.Show("Your video card does not support Mipmaps.\nDisable Mipmaps from the META3D tab under\nthe Application/Preferences menu"); msgdisplayed = true; } } } bitmap.UnlockBits(bitmapData); bitmap.Dispose(); OpenTK.Graphics.OpenGL.GL.Flush(); GLInvalidate(); } } newcontext.Dispose(); newwindow.Dispose(); //Logger.DebugLog("Texture thread exited"); } catch (Exception ex) { Logger.Log("META3D TextureThread: " + ex.Message, Helpers.LogLevel.Warning); } }
private void InitGL() { windowInfo = Utilities.CreateWindowsWindowInfo(window.Handle); context = new GraphicsContext(GraphicsMode.Default, windowInfo); context.MakeCurrent(windowInfo); context.LoadAll(); }
// --- functions --- /// <summary>Initializes the screen. A call to SDL_Init must have been made before calling this function. A call to Deinitialize must be made when terminating the program.</summary> /// <returns>Whether initializing the screen was successful.</returns> internal static bool Initialize() { if (SDL.SDL_InitSubSystem(SDL.SDL_INIT_VIDEO) != 0) { return false; } SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DOUBLEBUFFER, 1); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_RED_SIZE, 8); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_GREEN_SIZE, 8); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_BLUE_SIZE, 8); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_ALPHA_SIZE, 0); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DEPTH_SIZE, 24); SDL.SDL_GL_SetSwapInterval(Options.Current.VerticalSynchronization ? 1 : 0); if (Options.Current.AntiAliasingLevel != 0) { SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_MULTISAMPLESAMPLES, Options.Current.AntiAliasingLevel); } // --- video mode --- Width = Options.Current.FullscreenMode ? Options.Current.FullscreenWidth : Options.Current.WindowWidth; Height = Options.Current.FullscreenMode ? Options.Current.FullscreenHeight : Options.Current.WindowHeight; Fullscreen = Options.Current.FullscreenMode; SDL.SDL_WindowFlags flags = SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL/*| SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE*/ | SDL.SDL_WindowFlags.SDL_WINDOW_HIDDEN | SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE; if (Fullscreen) { flags |= SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN; } SDL.SDL_SetHint(SDL.SDL_HINT_RENDER_VSYNC, "true"); SDL.SDL_SetHint(SDL.SDL_HINT_VIDEO_ALLOW_SCREENSAVER, "false"); Window = SDL.SDL_CreateWindow(Application.ProductName, SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, Width, Height, flags); if (Window == IntPtr.Zero) { // --- not successful --- SDL.SDL_QuitSubSystem(SDL.SDL_INIT_VIDEO); return false; } GLContext = SDL.SDL_GL_CreateContext(Window); // --- set up OpenTK context tkContext = new GraphicsContext(new ContextHandle(GLContext), SDL.SDL_GL_GetProcAddress, () => new ContextHandle(SDL.SDL_GL_GetCurrentContext())); // --- set up icon --- string bitmapFile = OpenBveApi.Path.CombineFile(Program.FileSystem.DataFolder, "icon.png"); if (System.IO.File.Exists(bitmapFile)) { iconBmp = new System.Drawing.Bitmap(bitmapFile); // load file iconData = iconBmp.LockBits(new System.Drawing.Rectangle(0, 0, iconBmp.Width, iconBmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); // lock data iconSurface = SDL.SDL_CreateRGBSurfaceFrom(iconData.Scan0, iconBmp.Width, iconBmp.Height, 32, iconData.Stride, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); // upload to sdl SDL.SDL_SetWindowIcon(Window, iconSurface); // use icon // free in Deinitialize() } // --- set up anisotropic filtering --- Options.Current.AnisotropicFilteringMaximum = 0; string[] extensions = GL.GetString(StringName.Extensions).Split(new []{ ' ' }); for (int i = 0; i < extensions.Length; i++) { if (extensions[i] == "GL_EXT_texture_filter_anisotropic") { float n; GL.GetFloat((GetPName)ExtTextureFilterAnisotropic.MaxTextureMaxAnisotropyExt, out n); int m = (int)Math.Round(n); Options.Current.AnisotropicFilteringMaximum = Math.Max(0, m); break; } } if (Options.Current.AnisotropicFilteringLevel <= 0) { Options.Current.AnisotropicFilteringLevel = Options.Current.AnisotropicFilteringMaximum; } else if (Options.Current.AnisotropicFilteringLevel > Options.Current.AnisotropicFilteringMaximum) { Options.Current.AnisotropicFilteringLevel = Options.Current.AnisotropicFilteringMaximum; } // --- done --- Initialized = true; return true; }
void IXwtRender.CreateForWidgetContext(IRenderer renderer, IRenderOwner rendererimpl, Canvas widget) { var wBackend = Xwt.Toolkit.CurrentEngine.GetSafeBackend(widget) as Xwt.Backends.ICanvasBackend; var gtkwidget = wBackend.GetType().GetPropertyValue(wBackend, "Widget"); gtkwidget.GetType().SetPropertyValue(gtkwidget, "DoubleBuffered", false); // var widget = wBackend.GetType().GetPropertyValue(wBackend, "Widget"); // widget.GetType().SetPropertyValue(widget, "DoubleBuffered", false); // var gdkwin = widget.GetType().GetPropertyValue(widget, "GdkWindow"); var h = GetHandle(wBackend); // (IntPtr)gdkwin.GetType().GetPropertyValue(gdkwin, "Handle"); IntPtr windowHandle = gdk_x11_drawable_get_xid(h); // wBackend.Widget.Handle IntPtr display2 = gdk_drawable_get_display(h); IntPtr display = gdk_x11_drawable_get_xdisplay(h); IntPtr screen = gdk_display_get_default_screen(display2); int screenn = gdk_screen_get_number(screen); IntPtr rootWindow = gdk_screen_get_root_window(screen); IntPtr visualInfo = IntPtr.Zero; XVisualInfo info = new XVisualInfo(); info.VisualID = IntPtr.Zero; int dummy; visualInfo = XGetVisualInfo(display, XVisualInfoMask.ID, ref info, out dummy); // } /* else * { * visualInfo = GetVisualInfo(display); * }*/ var wBackendMain = Xwt.Toolkit.CurrentEngine.GetSafeBackend(widget.ParentWindow) as Xwt.Backends.IWindowFrameBackend; var winmain = wBackendMain.GetType().GetPropertyValue(wBackendMain, "Window"); var gdkwinmain = winmain.GetType().GetPropertyValue(winmain, "GdkWindow"); var hmain = (IntPtr)gdkwinmain.GetType().GetPropertyValue(gdkwinmain, "Handle"); Canvas view = null; EventHandler sizefunc = null; if (h == hmain) { view = new global::Xwt.Canvas() { ExpandHorizontal = true, ExpandVertical = true, HorizontalPlacement = WidgetPlacement.Fill, VerticalPlacement = WidgetPlacement.Fill, MinWidth = 1, MinHeight = 1, BackgroundColor = Xwt.Drawing.Colors.Black }; widget.AddChild(view); var viewbackend = Xwt.Toolkit.CurrentEngine.GetSafeBackend(view) as Xwt.Backends.ICanvasBackend; var gtkview = viewbackend.GetType().GetPropertyValue(viewbackend, "Widget"); gtkview.GetType().SetPropertyValue(gtkview, "DoubleBuffered", false); var hwnd = GetHandle(viewbackend); Debug.Assert(hwnd != hmain); sizefunc = new EventHandler((s, a) => widget.SetChildBounds(view, new Rectangle(Point.Zero, widget.Size))); widget.BoundsChanged += sizefunc; sizefunc(null, EventArgs.Empty); windowHandle = gdk_x11_drawable_get_xid(hwnd); } var WindowInfo = Utilities.CreateX11WindowInfo(display, screenn, windowHandle, rootWindow, visualInfo); XFree(visualInfo); var gfxcontext = new OpenTK.Graphics.GraphicsContext(new GraphicsMode(new ColorFormat(8, 8, 8, 8), 24, 8), WindowInfo, 3, 3, GraphicsContextFlags.Default); views[widget] = new viewinfo(WindowInfo, gfxcontext, (gfxcontext as IGraphicsContextInternal).Context) { view = view, sizefunc = sizefunc }; gfxcontext.MakeCurrent(WindowInfo); gfxcontext.LoadAll(); int major, minor; GL.GetInteger(GetPName.MajorVersion, out major); GL.GetInteger(GetPName.MinorVersion, out minor); Console.WriteLine("OpenGL {0}.{1}", major, minor); gfxcontext.MakeCurrent(null); }
static FinalizerThreadContextGL3x() { _window = new NativeWindow(); _context = new GraphicsContext(new GraphicsMode(32, 24, 8), _window.WindowInfo, 3, 2, GraphicsContextFlags.ForwardCompatible | GraphicsContextFlags.Debug); }
/// <summary> /// The main entry point for the application. /// </summary> static void Main() { // Request a 32-bits depth buffer when creating the window ContextSettings contextSettings = new ContextSettings(); contextSettings.DepthBits = 32; // Create the main window Window window = new Window(new VideoMode(640, 480), "SFML window with OpenGL", Styles.Default, contextSettings); // Make it the active window for OpenGL calls window.SetActive(); // Initialize OpenTK Toolkit.Init(); GraphicsContext context = new GraphicsContext(new ContextHandle(IntPtr.Zero), null); // Setup event handlers window.Closed += new EventHandler(OnClosed); window.KeyPressed += new EventHandler<KeyEventArgs>(OnKeyPressed); window.Resized += new EventHandler<SizeEventArgs>(OnResized); // Set the color and depth clear values GL.ClearDepth(1); GL.ClearColor(0, 0, 0, 1); // Enable Z-buffer read and write GL.Enable(EnableCap.DepthTest); GL.DepthMask(true); // Disable lighting and texturing GL.Disable(EnableCap.Lighting); GL.Disable(EnableCap.Texture2D); // Configure the viewport (the same size as the window) GL.Viewport(0, 0, (int)window.Size.X, (int)window.Size.Y); // Setup a perspective projection GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); float ratio = (float)(window.Size.X) / window.Size.Y; GL.Frustum(-ratio, ratio, -1, 1, 1, 500); // Define a 3D cube (6 faces made of 2 triangles composed by 3 vertices) float[] cube = new float[] { // positions // colors (r, g, b, a) -50, -50, -50, 0, 0, 1, 1, -50, 50, -50, 0, 0, 1, 1, -50, -50, 50, 0, 0, 1, 1, -50, -50, 50, 0, 0, 1, 1, -50, 50, -50, 0, 0, 1, 1, -50, 50, 50, 0, 0, 1, 1, 50, -50, -50, 0, 1, 0, 1, 50, 50, -50, 0, 1, 0, 1, 50, -50, 50, 0, 1, 0, 1, 50, -50, 50, 0, 1, 0, 1, 50, 50, -50, 0, 1, 0, 1, 50, 50, 50, 0, 1, 0, 1, -50, -50, -50, 1, 0, 0, 1, 50, -50, -50, 1, 0, 0, 1, -50, -50, 50, 1, 0, 0, 1, -50, -50, 50, 1, 0, 0, 1, 50, -50, -50, 1, 0, 0, 1, 50, -50, 50, 1, 0, 0, 1, -50, 50, -50, 0, 1, 1, 1, 50, 50, -50, 0, 1, 1, 1, -50, 50, 50, 0, 1, 1, 1, -50, 50, 50, 0, 1, 1, 1, 50, 50, -50, 0, 1, 1, 1, 50, 50, 50, 0, 1, 1, 1, -50, -50, -50, 1, 0, 1, 1, 50, -50, -50, 1, 0, 1, 1, -50, 50, -50, 1, 0, 1, 1, -50, 50, -50, 1, 0, 1, 1, 50, -50, -50, 1, 0, 1, 1, 50, 50, -50, 1, 0, 1, 1, -50, -50, 50, 1, 1, 0, 1, 50, -50, 50, 1, 1, 0, 1, -50, 50, 50, 1, 1, 0, 1, -50, 50, 50, 1, 1, 0, 1, 50, -50, 50, 1, 1, 0, 1, 50, 50, 50, 1, 1, 0, 1, }; // Enable position and color vertex components GL.EnableClientState(EnableCap.VertexArray); GL.EnableClientState(EnableCap.ColorArray); GL.VertexPointer(3, VertexPointerType.Float, 7 * sizeof(float), Marshal.UnsafeAddrOfPinnedArrayElement(cube, 0)); GL.ColorPointer(4, ColorPointerType.Float, 7 * sizeof(float), Marshal.UnsafeAddrOfPinnedArrayElement(cube, 3)); // Disable normal and texture coordinates vertex components GL.DisableClientState(EnableCap.NormalArray); GL.DisableClientState(EnableCap.TextureCoordArray); Clock clock = new Clock(); // Start the game loop while (window.IsOpen) { // Process events window.DispatchEvents(); // Clear color and depth buffer GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); // Apply some transformations GL.MatrixMode(MatrixMode.Modelview); GL.LoadIdentity(); GL.Translate(0.0F, 0.0F, -200.0F); GL.Rotate(clock.ElapsedTime.AsSeconds() * 50, 1.0F, 0.0F, 0.0F); GL.Rotate(clock.ElapsedTime.AsSeconds() * 30, 0.0F, 1.0F, 0.0F); GL.Rotate(clock.ElapsedTime.AsSeconds() * 90, 0.0F, 0.0F, 1.0F); // Draw the cube GL.DrawArrays(BeginMode.Triangles, 0, 36); // Finally, display the rendered frame on screen window.Display(); } }
public IGraphicsContext CreateContext(int major, int minor, GraphicsContextFlags flags) { GraphicsContext context = new GraphicsContext(mode, this.WindowInfo, major, minor, flags); mode = context.GraphicsMode; // get the XVisualInfo for this GraphicsMode XVisualInfo info = new XVisualInfo(); info.VisualID = mode.Index.Value; int dummy; IntPtr infoPtr = XGetVisualInfo(display, 1 /* VisualInfoMask.ID */, ref info, out dummy); info = (XVisualInfo)Marshal.PtrToStructure(infoPtr, typeof(XVisualInfo)); // set the X11 colormap. // Note: this only affects windows created in the future // (do we even need this here?) SetStaticFieldValue(xplatui, "CustomVisual", info.Visual); SetStaticFieldValue(xplatui, "CustomColormap", XCreateColormap(display, rootWindow, info.Visual, 0)); return context; }
private void StartJobThread() { Context.MakeCurrent(null); var contextReady = new AutoResetEvent(false); var thread = new Thread(() => { var window = new NativeWindow(); var context = new GraphicsContext(Context.GraphicsMode, window.WindowInfo); context.MakeCurrent(window.WindowInfo); contextReady.Set(); while (true) { var action = JobDispatcher.Instance.Dequeue(); action(); } }); thread.IsBackground = true; thread.Start(); contextReady.WaitOne(); MakeCurrent(); }
public void Dispose() { if (context != null) context.Dispose(); context = null; }