/// <summary>Constructs a new GameWindow with the specified attributes.</summary>
 /// <param name="width">The width of the GameWindow in pixels.</param>
 /// <param name="height">The height of the GameWindow in pixels.</param>
 /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GameWindow.</param>
 /// <param name="title">The title of the GameWindow.</param>
 /// <param name="options">GameWindow options regarding window appearance and behavior.</param>
 /// <param name="device">The OpenTK.Graphics.DisplayDevice to construct the GameWindow in.</param>
 public GameWindow(int width, int height, GraphicsMode mode, string title, bool nullContext,
     GameWindowFlags options, DisplayDevice device)
     : base(width, height, title, options, mode, device)
 {
     try {
         glContext = nullContext ? new NullContext() :
             Factory.Default.CreateGLContext(mode, WindowInfo);
         glContext.MakeCurrent(WindowInfo);
         glContext.LoadAll();
         VSync = true;
     } catch (Exception e) {
         Debug.Print(e.ToString());
         base.Dispose();
         throw;
     }
 }
Exemple #2
0
 /// <summary>
 ///
 /// </summary>
 /// <see cref="http://www.opentk.com/doc/graphics/graphicscontext"/>
 public override void InitSynchronizedOnce()
 {
     if (!AlreadySynchronized)
     {
         AlreadySynchronized = true;
         AutoResetEvent CompletedEvent = new AutoResetEvent(false);
         var            CThread        = new Thread(() =>
         {
             Thread.CurrentThread.CurrentCulture = new CultureInfo(PspConfig.CultureName);
             NativeWindow         = new OpenTK.NativeWindow(512, 272, "PspGraphicEngine", GameWindowFlags.Default, GraphicsMode.Default, DisplayDevice.Default);
             NativeWindow.Visible = false;
             GraphicsContext      = new GraphicsContext(GraphicsMode.Default, NativeWindow.WindowInfo);
             GraphicsContext.MakeCurrent(NativeWindow.WindowInfo);
             {
                 (GraphicsContext as IGraphicsContextInternal).LoadAll();
                 Initialize();
             }
             GraphicsContext.MakeCurrent(null);
             CompletedEvent.Set();
             while (Running)
             {
                 NativeWindow.ProcessEvents();
                 Thread.Sleep(1);
             }
             StopEvent.Set();
         });
         CThread.IsBackground = true;
         CThread.Start();
         CompletedEvent.WaitOne();
     }
 }
Exemple #3
0
        public void Capture(bool force = false)
        {
            try
            {
                //Only proceed if this window is not already current
                if (force || CurrentContext != this)
                {
                    //Release the current context if it exists
                    CurrentContext?.Release();

                    //Make this context the current one
                    CurrentContext = this;
                    if (!_context.IsCurrent)
                    {
                        _context.MakeCurrent(WindowInfo);
                    }

                    ContextChanged?.Invoke(true);
                }
            }
            catch //(Exception x)
            {
                //MessageBox.Show(x.ToString());
                Reset();
            }
        }
Exemple #4
0
        /// <summary>
        /// Runs the given action on the UI thread and blocks the current thread while the action is running.
        /// If the current thread is the UI thread, the action will run immediately.
        /// </summary>
        /// <param name="action">The action to be run on the UI thread</param>
        internal static void BlockOnUIThread(Action action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            // If we are already on the UI thread, just call the action and be done with it
            if (IsOnUIThread())
            {
                action();
                return;
            }

            lock (BackgroundContext)
            {
                // Make the context current on this thread
                BackgroundContext.MakeCurrent(WindowInfo);
                // Execute the action
                action();
                // Must flush the GL calls so the texture is ready for the main context to use
                GL.Flush();
                REngine.CheckGLError();
                // Must make the context not current on this thread or the next thread will get error 170 from the MakeCurrent call
                BackgroundContext.MakeCurrent(null);
            }
        }
        public void Capture()
        {
            try
            {
                bool notThis = CurrentlyEnabled != this && CurrentlyEnabled != null && CurrentlyEnabled._context.IsCurrent;

                if (notThis)
                {
                    CurrentlyEnabled.Release();
                }

                CurrentlyEnabled = this;
                if (!_context.IsCurrent)
                {
                    _context.MakeCurrent(WindowInfo);
                }

                if (ContextChanged != null && notThis)
                {
                    ContextChanged(true);
                }
            }
            catch //(Exception x)
            {
                //MessageBox.Show(x.ToString());
                Reset();
            }
        }
Exemple #6
0
        public static IDisposable AcquireContext(IWindowInfo windowInfo = null)
        {
            Monitor.Enter(Lock);
            if (1 == ++ContextReferenceCount.Value)
            {
                GLGraphicsContext.MakeCurrent(windowInfo ?? GLWindow.WindowInfo);
            }

            return(new DisposableAction(FreeContext));
        }
 public virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         graphicsContext.MakeCurrent(windowInfo);
         OnShuttingDown();
         if (GraphicsContext.ShareContexts && (Interlocked.Decrement(ref graphicsContextCount) == 0))
         {
             OnGraphicsContextShuttingDown();
             sharedContextInitialized = false;
         }
         graphicsContext.Dispose();
     }
 }
Exemple #8
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         _GraphicsContext.MakeCurrent(_WindowInfo);
         OnShuttingDown();
         if (GraphicsContext.ShareContexts && (Interlocked.Decrement(ref _GraphicsContextCount) == 0))
         {
             OnGraphicsContextShuttingDown();
             _SharedContextInitialized = false;
         }
         _GraphicsContext.Dispose();
     }
 }
Exemple #9
0
 /// <summary>
 /// Makes the underlying this GLControl current in the calling thread.
 /// All OpenGL commands issued are hereafter interpreted by this GLControl.
 /// </summary>
 protected void MakeCurrent()
 {
     if (m_context != null)
     {
         m_context.MakeCurrent(m_implementation.WindowInfo);
     }
 }
Exemple #10
0
        public DecklinkWindow()
        {
            //Create the OpenGL window
            _win = new NativeWindow(PreviewWidth, PreviewHeight,
                                    "Decklink Test", GameWindowFlags.Default,
                                    GraphicsMode.Default, DisplayDevice.Default);

            //Now create a Graphics context
            //and set it active for this thread
            _context = new GraphicsContext(GraphicsMode.Default, _win.WindowInfo);
            _context.MakeCurrent(_win.WindowInfo);
            _context.LoadAll();

            //Create the frame buffer we will render to
            _fbo     = new FrameBuffer(1280, 720);
            _texLogo = new Texture("la1tv.png");
            _devices = new DecklinkDevices();

            InitDecklink(0);

            _deckLinkOutput.SetScheduledFrameCompletionCallback(this);
            _totalFrames = 0;

            ResetFrame();
            SetPreroll();
            InitOpenGL();
            Draw(); //thread blocking!
        }
Exemple #11
0
        public GL46SwapChain(SwapChainDescriptor swapChainDescriptor)
        {
            var options = new ToolkitOptions();

            options.Backend = PlatformBackend.Default;
            Toolkit.Init(options);

            _windowInfo = Utilities.CreateWindowsWindowInfo(swapChainDescriptor.WindowHandle);
            var graphicsContextFlags = GraphicsContextFlags.ForwardCompatible;

#if DEBUG
            graphicsContextFlags |= GraphicsContextFlags.Debug;
#endif
            _nativeContext = new GraphicsContext(GraphicsMode.Default, _windowInfo, null, 4, 6, graphicsContextFlags);
            _nativeContext.LoadAll();
            TurnOnDebugging();
            _nativeContext.MakeCurrent(_windowInfo);
            _nativeContext.SwapInterval = swapChainDescriptor.VSync ? 1 : 0;

            OpenTK.Graphics.OpenGL4.GL.Enable(EnableCap.CullFace);
            OpenTK.Graphics.OpenGL4.GL.CullFace(CullFaceMode.Back);
            OpenTK.Graphics.OpenGL4.GL.FrontFace(FrontFaceDirection.Ccw);

            OpenTK.Graphics.OpenGL4.GL.Enable(EnableCap.DepthTest);
            OpenTK.Graphics.OpenGL4.GL.DepthFunc(DepthFunction.Less);
        }
Exemple #12
0
        public void Initialize()
        {
            // <Rant>
            // OpenTK has a great fuckup in its design here. It's absolutly nohm it possible to create
            // a render context for offscreen rendering without creating an OpenTK window.
            // before.
            // Passing Utilities.CreateDummyWindowInfo() or anything else will cause an invalid cast exception
            // Using Utilities.CreateWindowsWindowInfo(IntPtr.Zero) binds the code to windows only
            // Really great, why do i need to have a window in order to render to memory? -_-
            //</Rant>

            _window = new NativeWindow { Visible = false };
            _context = new GraphicsContext(GraphicsMode.Default, _window.WindowInfo, 2, 0, GraphicsContextFlags.Default);
            _context.MakeCurrent(_window.WindowInfo);
            _context.LoadAll();

            // create offscreen rendertarget with high precision
            _rtt = new RenderToTexture(1, 1, false, 4, typeof(float));

            int precision;
            int range;
            GL.GetShaderPrecisionFormat(OpenTK.Graphics.OpenGL.ShaderType.FragmentShader, ShaderPrecisionType.HighFloat, out range, out precision);
            Debug.WriteLine("Precision: {0}, Range {1}", precision, range);

            // init SL#
            Bindings.OpenTK.SLSharp.Init();
        }
Exemple #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RenderCanvasWindowImp" /> class.
        /// </summary>
        /// <param name="windowHandle">The window handle.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        protected RenderCanvasWindowImp(IntPtr windowHandle, int width, int height)
        {
            _major = 1;
            _minor = 0;

            _flags = GraphicsContextFlags.Default;
            _wi    = Utilities.CreateWindowsWindowInfo(windowHandle);

            try
            {
                _mode    = new GraphicsMode(32, 24, 0, 8);
                _context = new GraphicsContext(_mode, _wi, _major, _minor, _flags);
            }
            catch
            {
                _mode    = new GraphicsMode(32, 24, 0, 0);
                _context = new GraphicsContext(_mode, _wi, _major, _minor, _flags);
            }

            _context.MakeCurrent(_wi);
            ((IGraphicsContextInternal)_context).LoadAll();

            GL.ClearColor(Color.MidnightBlue);

            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);

            // Use VSync!
            _context.SwapInterval = 1;
            _lastTimeTick         = Timer;

            BaseWidth  = width;
            BaseHeight = height;
        }
        public void Initialize()
        {
            // <Rant>
            // OpenTK has a great fuckup in its design here. It's absolutly nohm it possible to create
            // a render context for offscreen rendering without creating an OpenTK window.
            // before.
            // Passing Utilities.CreateDummyWindowInfo() or anything else will cause an invalid cast exception
            // Using Utilities.CreateWindowsWindowInfo(IntPtr.Zero) binds the code to windows only
            // Really great, why do i need to have a window in order to render to memory? -_-
            //</Rant>

            _window = new NativeWindow {
                Visible = false
            };
            _context = new GraphicsContext(GraphicsMode.Default, _window.WindowInfo, 2, 0, GraphicsContextFlags.Default);
            _context.MakeCurrent(_window.WindowInfo);
            _context.LoadAll();

            // create offscreen rendertarget with high precision
            _rtt = new RenderToTexture(1, 1, false, 4, typeof(float));

            int precision;
            int range;

            GL.GetShaderPrecisionFormat(OpenTK.Graphics.OpenGL.ShaderType.FragmentShader, ShaderPrecisionType.HighFloat, out range, out precision);
            Debug.WriteLine("Precision: {0}, Range {1}", precision, range);

            // init SL#
            Bindings.OpenTK.SLSharp.Init();
        }
Exemple #15
0
        /// <summary>Constructs a new GameWindow with the specified attributes.</summary>
        /// <param name="width">The width of the GameWindow in pixels.</param>
        /// <param name="height">The height of the GameWindow in pixels.</param>
        /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GameWindow.</param>
        /// <param name="title">The title of the GameWindow.</param>
        /// <param name="options">GameWindow options regarding window appearance and behavior.</param>
        /// <param name="device">The OpenTK.Graphics.DisplayDevice to construct the GameWindow in.</param>
        /// <param name="major">The major version for the OpenGL GraphicsContext.</param>
        /// <param name="minor">The minor version for the OpenGL GraphicsContext.</param>
        /// <param name="flags">The GraphicsContextFlags version for the OpenGL GraphicsContext.</param>
        /// <param name="sharedContext">An IGraphicsContext to share resources with.</param>
        /// <param name="isSingleThreaded">Should the update and render frames be fired on the same thread? If false, render and update events will be fired from separate threads.</param>
        public GameWindow(int width, int height, GraphicsMode mode, string title, GameWindowFlags options, DisplayDevice device,
                          int major, int minor, GraphicsContextFlags flags, IGraphicsContext sharedContext, bool isSingleThreaded)
            : base(width, height, title, options,
                   mode == null ? GraphicsMode.Default : mode,
                   device == null ? DisplayDevice.Default : device)
        {
            try
            {
                this.isSingleThreaded = isSingleThreaded;
                glContext             = new GraphicsContext(mode == null ? GraphicsMode.Default : mode, WindowInfo, major, minor, flags);
                glContext.MakeCurrent(WindowInfo);
#if !TIZEN
                (glContext as IGraphicsContextInternal).LoadAll();
#endif
                VSync = VSyncMode.On;

                //glWindow.WindowInfoChanged += delegate(object sender, EventArgs e) { OnWindowInfoChangedInternal(e); };
            }
            catch (Exception e)
            {
                Debug.Print(e.ToString());
                base.Dispose();
                throw;
            }
        }
        private void OnCompTargetRender(object sender, EventArgs e)
        {
            if (_context == null || _renderer == null)
            {
                return;
            }
            if (!ReferenceEquals(GraphicsContext.CurrentContext, _context))
            {
                _context?.MakeCurrent(_windowInfo);
            }
            if (_resizeStartStamp != 0)
            {
                if (_resizeStartStamp + ResizeUpdateInterval > _stopwatch.ElapsedMilliseconds)
                {
                    return;
                }
                _renderer?.DeleteBuffers();
                var width  = (int)RenderSize.Width;
                var height = (int)RenderSize.Height;
                _renderer         = new GLWpfControlRenderer(width, height, _image, _settings.UseHardwareRender, _settings.PixelBufferObjectCount);
                _resizeStartStamp = 0;
            }


            GL.BindFramebuffer(FramebufferTarget.Framebuffer, FrameBuffer);

            TimeSpan deltaTime = _stopwatch.Elapsed - _lastFrameStamp;

            Render?.Invoke(deltaTime);

            _renderer.UpdateImage();
            InvalidateVisual();
            _lastFrameStamp = _stopwatch.Elapsed;
        }
Exemple #17
0
        public void StartRender(string inputFolder, string outputFolder, int width, int height)
        {
            ProcessTotal  = 0;
            ProcessAmount = 0;

            IsOperationActive = true;

            Framebuffer?.Dispoe();

            OutputFolder = outputFolder;
            Framebuffer  = new Framebuffer(FramebufferTarget.Framebuffer, width, height, PixelInternalFormat.Rgba);

            Control        = new GLContext();
            Control.Camera = new Camera();

            Control.Width         = width;
            Control.Height        = height;
            Control.Camera.Width  = width;
            Control.Camera.Height = height;

            Control.ScreenBuffer = Framebuffer;

            GraphicsMode mode   = new GraphicsMode(new ColorFormat(32), 24, 8, 4, new ColorFormat(32), 2, false);
            var          window = new GameWindow(width, height, mode);

            Context = new GraphicsContext(mode, window.WindowInfo);
            Context.MakeCurrent(window.WindowInfo);

            List <string> files = new List <string>();

            GetFiles(inputFolder, files);

            ProcessTotal = files.Count;
            for (int i = 0; i < files.Count; i++)
            {
                ProcessAmount = i;

                if (CancelOperation)
                {
                    break;
                }

                try
                {
                    ProcessName = $"Processing {files[i]}";
                    BatchRenderFile(files[i]);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

            ProcessAmount     = files.Count - 1;
            IsOperationActive = false;
            CancelOperation   = false;
        }
        public UseOpenGLCreationContext(GraphicsDevice graphicsDevice)
            : this()
        {
#if SILICONSTUDIO_PLATFORM_ANDROID
            // Unfortunately, android seems to not use GraphicsContext.CurrentContext to register its AndroidGraphicsContext,
            // so let's query EGL directly.
            if (GraphicsDevice.EglGetCurrentContext() == IntPtr.Zero)
#elif SILICONSTUDIO_PLATFORM_IOS
            if (OpenGLES.EAGLContext.CurrentContext == null)
#else
            if (OpenTK.Graphics.GraphicsContext.CurrentContext == null)
#endif
            {
                needUnbindContext        = true;
                useDeviceCreationContext = true;

#if SILICONSTUDIO_PLATFORM_ANDROID
                tegraWorkaround = graphicsDevice.Workaround_Context_Tegra2_Tegra3;

                // Notify main rendering thread there is some pending async work to do
                if (tegraWorkaround)
                {
                    useDeviceCreationContext = false; // We actually use real main context, so states will be kept
                    graphicsDevice.AsyncPendingTaskWaiting = true;
                }
#endif

                // Lock, since there is only one deviceCreationContext.
                // TODO: Support multiple deviceCreationContext (TLS creation of context was crashing, need to investigate why)
                asyncCreationLockObject = graphicsDevice.asyncCreationLockObject;
                Monitor.Enter(graphicsDevice.asyncCreationLockObject, ref asyncCreationLockTaken);

#if SILICONSTUDIO_PLATFORM_ANDROID
                if (tegraWorkaround)
                {
                    graphicsDevice.AsyncPendingTaskWaiting = false;
                }

                // On android, bind the actual android context
                // The deviceCreationContext is a dummy one, so that CurrentContext works.
                androidDeviceCreationContext = graphicsDevice.androidAsyncDeviceCreationContext;
                if (androidDeviceCreationContext != null)
                {
                    androidDeviceCreationContext.MakeCurrent(graphicsDevice.deviceCreationWindowInfo);
                }
#endif

                // Bind the context
                deviceCreationContext = graphicsDevice.deviceCreationContext;
                deviceCreationContext.MakeCurrent(graphicsDevice.deviceCreationWindowInfo);
            }
            else
            {
                // TODO Hardcoded to the fact it uses only one command list, this should be fixed
                CommandList = graphicsDevice.MainCommandList;
            }
        }
Exemple #19
0
 public bool MakeCurrent()
 {
     try {
         context.MakeCurrent(window);
         current = this;
         return(true);
     } catch (GraphicsContextException) {
         return(false);
     }
 }
Exemple #20
0
        private void DestroyFramebuffer()
        {
            AssertNotDisposed();
            AssertValidContext();

            __renderbuffergraphicsContext.MakeCurrent(null);

            _glapi.DeleteFramebuffers(1, ref _framebuffer);
            _framebuffer = 0;

            _glapi.DeleteRenderbuffers(1, ref _colorbuffer);
            _colorbuffer = 0;

            if (_depthbuffer != 0)
            {
                _glapi.DeleteRenderbuffers(1, ref _depthbuffer);
                _depthbuffer = 0;
            }
        }
		public static bool BindContext(IGraphicsContext context)
		{
			if (!context.IsDisposed)
			{
				context.MakeCurrent(Contexts[context].Window);
				return true;
			} else 	{
				return false;
			}
		}
Exemple #22
0
        internal static void BlockOnUIThread(Action action, bool needsUI = false, object additional = null)
        {
            /*if (action == null)
             *  throw new ArgumentNullException("action");*/

            // If we are already on the UI thread, just call the action and be done with it
            if (IsOnUIThread())
            {
                action();
                return;
            }

            lock (context)
            {
                if (needsUI)
                {
                    sync.Post(new System.Threading.SendOrPostCallback(delegate(object state)
                    {
                        action();
                    }), null);
                    return;
                }
                try
                {
                    context.MakeCurrent(windowInfo);
                }
                catch (Exception ex)
                {
                }

                action();

                GL.Flush();

                try
                {
                    context.MakeCurrent(null);
                }
                catch (Exception ex)
                {
                }
            }
        }
Exemple #23
0
        private void InitOpenGL()
        {
            var mode = new GraphicsMode(ColorFormat.Empty, 0, 0, 0, 0, 0, false);

            _context = new GraphicsContext(mode, _windowInfo, _settings.MajorVersion, _settings.MinorVersion, _settings.GraphicsContextFlags);
            _context.LoadAll();
            _context.MakeCurrent(_windowInfo);
            var width  = (int)RenderSize.Width;
            var height = (int)RenderSize.Height;

            _renderer = new GLWpfControlRenderer(width, height, _image, _settings.UseHardwareRender, _settings.PixelBufferObjectCount);
        }
 public override bool MakeCurrent()
 {
     try
     {
         m_graphicsContext.MakeCurrent(m_window);
         return(true);
     }
     catch (Exception e)
     {
         Console.WriteLine($"Failed to make current context active: {e}");
         return(false);
     }
 }
            void InitGL()
            {
                m_window  = new NativeWindow();
                m_context = new GraphicsContext(GraphicsMode.Default, m_window.WindowInfo);
                m_context.MakeCurrent(m_window.WindowInfo);
                m_context.LoadAll();

                // Setup rendering texture
                m_renderTextureHandle = (uint)GL.GenTexture();
                GL.BindTexture(TextureTarget.Texture2D, m_renderTextureHandle);
                GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);

                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
                GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, Owner.VisualWidth, Owner.VisualHeight, 0, OpenTK.Graphics.OpenGL.PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero);

                // Setup FBO
                m_fboHandle = (uint)GL.GenFramebuffer();
                GL.BindFramebuffer(FramebufferTarget.Framebuffer, m_fboHandle);
                GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, m_renderTextureHandle, 0);

                // Setup Cuda <-> OpenGL interop
                int length = Owner.VisualHeight * Owner.VisualWidth * sizeof(uint);

                //unbind - just in case this is causing us the invalid exception problems
                GL.BindBuffer(BufferTarget.PixelPackBuffer, 0);
                //create buffer
                GL.GenBuffers(1, out m_sharedBufferHandle);
                GL.BindBuffer(BufferTarget.PixelPackBuffer, m_sharedBufferHandle);
                GL.BufferData(BufferTarget.PixelPackBuffer, (IntPtr)(length), IntPtr.Zero, BufferUsageHint.StaticRead);  // use data instead of IntPtr.Zero if needed
                GL.BindBuffer(BufferTarget.PixelPackBuffer, 0);
                try
                {
                    m_renderResource = new CudaOpenGLBufferInteropResource(m_renderTextureHandle, CUGraphicsRegisterFlags.ReadOnly); // Read only by CUDA
                }
                catch (CudaException e)
                {
                    MyLog.INFO.WriteLine(
                        "{0}: CUDA-OpenGL interop error while itializing texture (using fallback): {1}",
                        GetType().Name, e.Message);
                }

                // Clean up
                GL.BindTexture(TextureTarget.Texture2D, 0);
                FramebufferErrorCode err = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer);

                GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
                GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            }
Exemple #26
0
        public override void CreateContext()
        {
            Debug.Assert(Window != null, "Missing window, cannot create context.");

            if (Context != null)
            {
                MakeContextNotCurrent();
                Context.Dispose();
            }

            Context = new GraphicsContext(GraphicsMode.Default, Window.WindowInfo);
            Context.LoadAll();
            Context.MakeCurrent(null);
        }
        private static IGraphicsContext GetOrCreateSharedOpenGLContext(GLWpfControlSettings settings)
        {
            if (_sharedContext != null)
            {
                var isSameContext = GLWpfControlSettings.WouldResultInSameContext(settings, _sharedContextSettings);
                if (!isSameContext)
                {
                    throw new ArgumentException($"The provided {nameof(GLWpfControlSettings)} would result" +
                                                $"in a different context creation to one previously created. To fix this," +
                                                $" either ensure all of your context settings are identical, or provide an " +
                                                $"external context via the '{nameof(GLWpfControlSettings.ContextToUse)}' field.");
                }
            }

            else
            {
                var nws = NativeWindowSettings.Default;
                nws.StartFocused    = false;
                nws.StartVisible    = false;
                nws.NumberOfSamples = 0;
                // if we ask GLFW for 1.0, we should get the highest level context available with full compat.
                nws.APIVersion = new Version(settings.MajorVersion, settings.MinorVersion);
                nws.Flags      = ContextFlags.Offscreen | settings.GraphicsContextFlags;
                // we have to ask for any compat in this case.
                nws.Profile      = settings.GraphicsProfile;
                nws.WindowBorder = WindowBorder.Hidden;
                nws.WindowState  = WindowState.Minimized;
                var glfwWindow = new NativeWindow(nws);
                var provider   = new GLFWBindingsContext();
                Wgl.LoadBindings(provider);
                // we're already in a window context, so we can just cheat by creating a new dependency object here rather than passing any around.
                var depObject = new DependencyObject();
                // retrieve window handle/info
                var window     = Window.GetWindow(depObject);
                var baseHandle = window is null ? IntPtr.Zero : new WindowInteropHelper(window).Handle;
                var hwndSource = new HwndSource(0, 0, 0, 0, 0, "GLWpfControl", baseHandle);

                _sharedContext          = glfwWindow.Context;
                _sharedContextSettings  = settings;
                _sharedContextResources = new IDisposable[] { hwndSource, glfwWindow };
                // GL init
                // var mode = new GraphicsMode(ColorFormat.Empty, 0, 0, 0, 0, 0, false);
                // _commonContext = new GraphicsContext(mode, _windowInfo, _settings.MajorVersion, _settings.MinorVersion,
                //     _settings.GraphicsContextFlags);
                // _commonContext.LoadAll();
                _sharedContext.MakeCurrent();
            }
            Interlocked.Increment(ref _sharedContextReferenceCount);
            return(_sharedContext);
        }
Exemple #28
0
        static GLService()
        {
            Lock = new object();
            ContextReferenceCount = new ThreadLocal <int>(() => 0, false);

            GLWindow          = new NativeWindow();
            GLGraphicsContext = new GraphicsContext(GraphicsMode.Default, GLWindow.WindowInfo);
            SubscribeContexts = new ConcurrentDictionary <WindowsFormsHost, SubscribeContext>();
            DrawingContexts   = new ConcurrentDictionary <Action, DrawingContext>();

            GLGraphicsContext.MakeCurrent(null);

            DisposableSerivce.Register(new DisposableAction(Dispose));
        }
Exemple #29
0
        /// <summary>
        /// Runs the given action on the UI thread and blocks the current thread while the action is running.
        /// If the current thread is the UI thread the action will run immediately.
        /// </summary>
        /// <param name="action">The action to run on the UI thread.</param>
        public static void BlockOnUIThread(Action action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            // if this is the main thread execute immediatly
            if (_mainThreadId == Thread.CurrentThread.ManagedThreadId)
            {
                action();
                return;
            }

            lock (BackgroundContext)
            {
                BackgroundContext.MakeCurrent(WindowInfo);
                action();
                GL.Flush();
                Graphics.Utilities.CheckGLError();
                BackgroundContext.MakeCurrent(null);
            }
        }
Exemple #30
0
        public GL2(IntPtr handle, int width, int height)
        {
            //Console.WriteLine(handle);

            IWindowInfo window_info;

            if (!IWindowInfoList.ContainsKey(handle))
            {
                window_info = Utilities.CreateWindowsWindowInfo(handle);
                IWindowInfoList.Add(handle, window_info);
            }

            window_info = IWindowInfoList[handle];

            if (!control2ContextList.ContainsKey(handle))
            {
                control2ContextList.Add(handle, new GraphicsContext(GraphicsMode.Default, window_info));

                string versionString = GL.GetString(StringName.Version);
                if (versionString == "")
                {
                    return;
                }
                string majorString = versionString.Split(' ')[0];
                var    v           = new Version(majorString);
                npotSupported = v.Major >= 2;


                GL.MatrixMode(MatrixMode.Projection);
                GL.LoadIdentity();
                GL.Ortho(0, width, height, 0, -1, 1);
                GL.MatrixMode(MatrixMode.Modelview);
                GL.LoadIdentity();

                GL.Viewport(0, 0, width, height);
            }

            control2Context = control2ContextList[handle];

            //var implementation = new GLControlFactory().CreateGLControl(format, this);

            //context = implementation.CreateContext(major, minor, flags);

            control2Context.MakeCurrent(window_info);

            GL.Viewport(0, 0, width, height);

            //GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
        }
            /// <summary>
            /// draws tetris game board into Owner's VisualOutput memory block
            /// data is ready for rendering thanks to updateTask (score, level, brickarea, ...)
            /// </summary>
            public override void Execute()
            {
                if (!m_texturesLoaded)
                {
                    MyMemoryManager.Instance.ClearGlobalVariable("HACK_NAME_" + GetHashCode(), Owner.GPU);
                    InitGL();
                    LoadTextures();
                    m_texturesLoaded = true;
                }

                m_context.MakeCurrent(m_window.WindowInfo);
                GL.Finish();

                SetupView();

                RenderBackground();
                RenderBricks();
                RenderHint();
                RenderText();

                CopyPixels();

                m_context.MakeCurrent(null);
            }
Exemple #32
0
 /// <summary>Constructs a new GameWindow with the specified attributes.</summary>
 /// <param name="width">The width of the GameWindow in pixels.</param>
 /// <param name="height">The height of the GameWindow in pixels.</param>
 /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GameWindow.</param>
 /// <param name="title">The title of the GameWindow.</param>
 /// <param name="options">GameWindow options regarding window appearance and behavior.</param>
 /// <param name="device">The OpenTK.Graphics.DisplayDevice to construct the GameWindow in.</param>
 public GameWindow(int width, int height, GraphicsMode mode, string title, bool nullContext,
                   GameWindowFlags options, DisplayDevice device) : base(width, height, title, mode, device)
 {
     try {
         glContext = nullContext ? new NullContext() :
                     Factory.Default.CreateGLContext(mode, WindowInfo);
         glContext.MakeCurrent(WindowInfo);
         glContext.LoadAll();
         VSync = true;
     } catch (Exception e) {
         Debug.Print(e.ToString());
         base.Dispose();
         throw;
     }
 }
Exemple #33
0
 public void MakeCurrent()
 {
     if (GraphicsContext.CurrentContext != canvas.Context)
     {
         try
         {
             control2Context.MakeCurrent(canvas.WindowInfo);
             GL.Flush();
         }
         catch
         {
             GL.Flush();
         }
     }
 }
Exemple #34
0
        public SDL2GLContext (GraphicsMode mode, IWindowInfo windowInfo, IGraphicsContext shared, bool direct,
            int major, int minor, GraphicsContextFlags flags)
		{
			SDL2WindowInfo currentWindow = (SDL2WindowInfo)windowInfo;
			window = currentWindow.WindowHandle;
            
			if (shared != null) {
				shared.MakeCurrent (windowInfo);
				lock (API.sdl_api_lock) {
					API.GL_SetAttribute (API.GLAttr.ShareWithCurrentContext, 1);
				}
			}

			lock (API.sdl_api_lock) {
				context = API.GL_CreateContext (currentWindow.WindowHandle);
			}

			MakeCurrent (windowInfo);

			if (shared != null) {
				shared.MakeCurrent (windowInfo);
			}
			Handle = new ContextHandle(context);
        }
        public UseOpenGLCreationContext(GraphicsDevice graphicsDevice)
            : this()
        {
#if SILICONSTUDIO_PLATFORM_ANDROID
            // Unfortunately, android seems to not use GraphicsContext.CurrentContext to register its AndroidGraphicsContext,
            // so let's query EGL directly.
            if (GraphicsDevice.EglGetCurrentContext() == IntPtr.Zero)
#elif SILICONSTUDIO_PLATFORM_IOS
            if (OpenGLES.EAGLContext.CurrentContext == null)
#else
            if (GraphicsContext.CurrentContext == null)
#endif
            {
                needUnbindContext = true;
                useDeviceCreationContext = true;

#if SILICONSTUDIO_PLATFORM_ANDROID
                tegraWorkaround = graphicsDevice.Workaround_Context_Tegra2_Tegra3;

                // Notify main rendering thread there is some pending async work to do
                if (tegraWorkaround)
                {
                    useDeviceCreationContext = false; // We actually use real main context, so states will be kept
                    graphicsDevice.AsyncPendingTaskWaiting = true;
                }
#endif

                // Lock, since there is only one deviceCreationContext.
                // TODO: Support multiple deviceCreationContext (TLS creation of context was crashing, need to investigate why)
                asyncCreationLockObject = graphicsDevice.asyncCreationLockObject;
                Monitor.Enter(graphicsDevice.asyncCreationLockObject, ref asyncCreationLockTaken);

#if SILICONSTUDIO_PLATFORM_ANDROID
                if (tegraWorkaround)
                    graphicsDevice.AsyncPendingTaskWaiting = false;

                // On android, bind the actual android context
                // The deviceCreationContext is a dummy one, so that CurrentContext works.
                androidDeviceCreationContext = graphicsDevice.androidAsyncDeviceCreationContext;
                if (androidDeviceCreationContext != null)
                    androidDeviceCreationContext.MakeCurrent(graphicsDevice.deviceCreationWindowInfo);
#endif

                // Bind the context
                deviceCreationContext = graphicsDevice.deviceCreationContext;
                deviceCreationContext.MakeCurrent(graphicsDevice.deviceCreationWindowInfo);
            }
        }
Exemple #36
0
        static GLService()
        {
            Lock = new object();
            ContextReferenceCount = new ThreadLocal<int>(() => 0, false);

            GLControl = new GLControl(GraphicsMode.Default);
            GLControl.CreateControl();
            //GLWindow = new NativeWindow();
            GLGraphicsContext = GLControl.Context;
            //GLGraphicsContext = new GraphicsContext(GraphicsMode.Default, GLControl.WindowInfo);
            SubscribeContexts = new ConcurrentDictionary<WindowsFormsHost, SubscribeContext>();
            DrawingContexts = new ConcurrentDictionary<Action, DrawingContext>();

            GLGraphicsContext.MakeCurrent(null);

            DisposableSerivce.Register(new DisposableAction(Dispose));
        }
Exemple #37
0
 public Program(int width, int height, GraphicsMode mode, string title, GameWindowFlags options, DisplayDevice device,
                   int major, int minor, GraphicsContextFlags flags, IGraphicsContext sharedContext)
     : base(width, height, title, options,
            mode == null ? GraphicsMode.Default : mode,
            device == null ? DisplayDevice.Default : device)
 {
     try
     {
         glContext = new GraphicsContext(mode == null ? GraphicsMode.Default : mode, WindowInfo, major, minor, flags);
         glContext.MakeCurrent(WindowInfo);
         (glContext as IGraphicsContextInternal).LoadAll();
     }
     catch (Exception e)
     {
         Debug.Print(e.ToString());
         base.Dispose();
         throw;
     }
 }
        public UseOpenGLCreationContext(GraphicsDevice graphicsDevice)
            : this()
        {
            if (OpenTK.Graphics.GraphicsContext.CurrentContextHandle.Handle == IntPtr.Zero)
            {
                needUnbindContext = true;
                useDeviceCreationContext = true;

#if SILICONSTUDIO_PLATFORM_ANDROID
                tegraWorkaround = graphicsDevice.Workaround_Context_Tegra2_Tegra3;

                // Notify main rendering thread there is some pending async work to do
                if (tegraWorkaround)
                {
                    useDeviceCreationContext = false; // We actually use real main context, so states will be kept
                    graphicsDevice.AsyncPendingTaskWaiting = true;
                }
#endif

                // Lock, since there is only one deviceCreationContext.
                // TODO: Support multiple deviceCreationContext (TLS creation of context was crashing, need to investigate why)
                asyncCreationLockObject = graphicsDevice.asyncCreationLockObject;
                Monitor.Enter(graphicsDevice.asyncCreationLockObject, ref asyncCreationLockTaken);

#if SILICONSTUDIO_PLATFORM_ANDROID
                if (tegraWorkaround)
                    graphicsDevice.AsyncPendingTaskWaiting = false;
#endif

                // Bind the context
                deviceCreationContext = graphicsDevice.deviceCreationContext;
                deviceCreationContext.MakeCurrent(graphicsDevice.deviceCreationWindowInfo);
            }
            else
            {
                // TODO Hardcoded to the fact it uses only one command list, this should be fixed
                CommandList = graphicsDevice.MainCommandList;
            }
        }
Exemple #39
0
        /// <summary>Constructs a new GameWindow with the specified attributes.</summary>
        /// <param name="width">The width of the GameWindow in pixels.</param>
        /// <param name="height">The height of the GameWindow in pixels.</param>
        /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GameWindow.</param>
        /// <param name="title">The title of the GameWindow.</param>
        /// <param name="options">GameWindow options regarding window appearance and behavior.</param>
        /// <param name="device">The OpenTK.Graphics.DisplayDevice to construct the GameWindow in.</param>
        /// <param name="major">The major version for the OpenGL GraphicsContext.</param>
        /// <param name="minor">The minor version for the OpenGL GraphicsContext.</param>
        /// <param name="flags">The GraphicsContextFlags version for the OpenGL GraphicsContext.</param>
        /// <param name="sharedContext">An IGraphicsContext to share resources with.</param>
        public GameWindow(int width, int height, GraphicsMode mode, string title, GameWindowFlags options, DisplayDevice device,
                          int major, int minor, GraphicsContextFlags flags, IGraphicsContext sharedContext)
            : base(width, height, title, options,
                   mode == null ? GraphicsMode.Default : mode,
                   device == null ? DisplayDevice.Default : device)
        {
            try
            {
                glContext = new GraphicsContext(mode == null ? GraphicsMode.Default : mode, WindowInfo, major, minor, flags);
                glContext.MakeCurrent(WindowInfo);
                (glContext as IGraphicsContextInternal).LoadAll();

                VSync = VSyncMode.On;

                //glWindow.WindowInfoChanged += delegate(object sender, EventArgs e) { OnWindowInfoChangedInternal(e); };
            }
            catch (Exception e)
            {
                Debug.Print(e.ToString());
                base.Dispose();
                throw;
            }
        }
		// This gets called when the drawing surface is ready
		protected override void OnLoad (EventArgs e)
		{
			base.OnLoad (e);

			try {
				// Clear the current Context
				GraphicsContext.MakeCurrent (null);
				// Create a secondary context using the same information the primary 
				// context was created with
				backgroundContext = new AndroidGraphicsContext(GraphicsMode, WindowInfo, GraphicsContext, ContextRenderingApi, GraphicsContextFlags.Embedded);
			}catch {
				// secondary context not supported
				backgroundContext = null;
			}

			MakeCurrent();

			var vertexShader = LoadShader(ShaderType.VertexShader, vertexShaderCode);
			var fragmentShader = LoadShader(ShaderType.FragmentShader, fragmentShaderCode);

			program = GL.CreateProgram ();             // create empty OpenGL Program
			GL.AttachShader (program, vertexShader);   // add the vertex shader to program
			GL.AttachShader (program, fragmentShader); // add the fragment shader to program

			GL.BindAttribLocation (program, ATTRIB_VERTEX, "position");
			GL.BindAttribLocation (program, ATTRIB_TEXCOORD, "texcoord");

			GL.LinkProgram (program);                  // create OpenGL program executables

			uniformTextureLocation = GL.GetUniformLocation (program, "texture");

			if (vertexShader != 0) {
				GL.DetachShader (program, vertexShader);
				GL.DeleteShader (vertexShader);
			}

			if (fragmentShader != 0) {
				GL.DetachShader (program, fragmentShader);
				GL.DeleteShader (fragmentShader);
			}

			GL.Viewport (0, 0, Width, Height);

			// Run the render loop
			Run ();

			Task.Factory.StartNew (() => {
				//Thread.Sleep(500);
				// load the bitmap 
				bitmap = BitmapFactory.DecodeResource (Context.Resources, Resource.Drawable.f_spot);

				// the device may or may not support a background Context. But rather than 
				// duplicating this code we just create an Action which we can invoke on this
				// background thread later or queue to be executed on the rendering thread.
				Action acton = new Action (() => {
					GL.Enable (EnableCap.Texture2D);
					GL.GenTextures(1, out textureid);
					GL.ActiveTexture (TextureUnit.Texture0);
					GL.BindTexture (TextureTarget.Texture2D, textureid);
					// setup texture parameters
					GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
					GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
					GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
					GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
					Android.Opengl.GLUtils.TexImage2D ((int)TextureTarget.Texture2D, 0, bitmap, 0); 
					// make sure the texture is pushed to the GPU.
					GL.Flush();

					// make sure we free resources
					bitmap.Recycle();
					bitmap.Dispose();
					bitmap = null;
				});


				// take a lock so the main rendering thread does not try to draw anything
				// there are other ways to do this, but its is probably the simplest
				lock (lockobject) {
					if (backgroundContext != null) {
						// Clear the current context bound to the Display 
						backgroundContext.MakeCurrent (null);
						// make this context active
						backgroundContext.MakeCurrent (WindowInfo);
						// do our processing
						acton.Invoke ();
						// clear the current context again so we don't error on the main thread
						backgroundContext.MakeCurrent (null);
					} else {
						// Secondary Context's are not supported on this device
						// queue the action for execution later.
						actions.Enqueue (acton);
					}
				}

			});
		}
 private void CreateContext()
 {
     window = new GameWindow();
     context = new GraphicsContext(GraphicsMode.Default, window.WindowInfo);
     context.MakeCurrent(window.WindowInfo);
 }
Exemple #42
0
 public void SetCurrentContext(IGraphicsContext context)
 {
     context.MakeCurrent(null);
 }
Exemple #43
0
        private void Initialize(Bitmap data, IGraphicsContext context, IWindowInfo info)
        {
            OpenTK.Graphics.OpenGL.PixelFormat pf_external = PixelFormatToGl(data.PixelFormat);
            PixelInternalFormat pf_internal = PixelFormatToInternal(data.PixelFormat);

            IGraphicsContext old_context = GraphicsContext.CurrentContext;
            context.MakeCurrent(info);
            m_graphics_context = context;
            m_window_info = info;

            BitmapData bd = data.LockBits(new Rectangle(new Point(0, 0), data.Size), ImageLockMode.ReadOnly, data.PixelFormat);
            try
            {
                int old_texture;
                GL.GetInteger(GetPName.TextureBinding2D, out old_texture);

                m_texture_id = GL.GenTexture();
                GL.BindTexture(TEXTURE_TARGET, TextureId);
                GL.TexImage2D(TEXTURE_TARGET, 0, pf_internal, data.Width, data.Height, 0, pf_external, PixelType.UnsignedByte, bd.Scan0);

                // todo: optionally generate mipmaps if desirable
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

                GL.BindTexture(TEXTURE_TARGET, old_texture);
            }
            finally { data.UnlockBits(bd); }
            old_context.MakeCurrent(info);
        }
        /// <summary>
        /// Create Graphcis Context
        /// </summary>
        /// <returns></returns>
        public bool CreateGraphicsContext()
        {
            // If this looks uninitialized...  initialize.
            if (ColorBPP == 0)
            {
                ColorBPP = 32;

                if (DepthBPP == 0) DepthBPP = 16;
            }

            ColorFormat colorBufferColorFormat = new ColorFormat(ColorBPP);

            ColorFormat accumulationColorFormat = new ColorFormat(AccumulatorBPP);

            int buffers = 2;
            if (SingleBuffer) buffers--;

            GraphicsMode graphicsMode = new GraphicsMode(colorBufferColorFormat, DepthBPP, StencilBPP, Samples, accumulationColorFormat, buffers, Stereo);

            #if MAC
            IntPtr windowHandle = gdk_quartz_window_get_nswindow(GdkWindow.Handle);

            // Problem: gdk_window_ensure_native() crashes when used more than once.
            // For now, just create a NSView in place and use that instead.
            // Needs some care updating when resizing, hiding, etc, but seems to work.
            // (I'd guess this is pretty much what gdk_window_ensure_native() does internally.)

            var customView = NativeClass.AllocateClass("CustomNSView" + uniqueId++, "NSView");
            NativeClass.RegisterClass(customView);

            nsView = SendIntPtr(SendIntPtr(customView, sel_registerName("alloc")), sel_registerName("initWithFrame:"), new RectangleF(0, 0, 400, 400));

            bool native = gdk_window_ensure_native(GdkWindow.Handle);
            if (!native)
            {
                throw new PlatformNotSupportedException("Could not create native view.");
            }

            nsView = gdk_quartz_window_get_nsview(GdkWindow.Handle);

            windowInfo = OpenTK.Platform.Utilities.CreateMacOSWindowInfo(windowHandle, nsView);
            UpdateNSView();
            #elif LINUX
                IntPtr display = gdk_x11_display_get_xdisplay(Display.Handle);
                int screen = Screen.Number;
                IntPtr windowHandle = gdk_x11_drawable_get_xid(GdkWindow.Handle);
                IntPtr rootWindow = gdk_x11_drawable_get_xid(RootWindow.Handle);

                IntPtr visualInfo;
                if (graphicsMode.Index.HasValue)
                {
                    XVisualInfo info = new XVisualInfo();
                    info.VisualID = graphicsMode.Index.Value;
                    int dummy;
                    visualInfo = XGetVisualInfo(display, XVisualInfoMask.ID, ref info, out dummy);
                }
                else
                {
                    visualInfo = GetVisualInfo(display);
                }

                windowInfo = OpenTK.Platform.Utilities.CreateX11WindowInfo(display, screen, windowHandle, rootWindow, visualInfo);
                XFree(visualInfo);
            #endif

            // GraphicsContext
            graphicsContext = new GraphicsContext(graphicsMode, windowInfo, GlVersionMajor, GlVersionMinor, graphicsContextFlags);
            graphicsContext.MakeCurrent(windowInfo);

            if (GraphicsContext.ShareContexts)
            {
                Interlocked.Increment(ref graphicsContextCount);

                if (!sharedContextInitialized)
                {
                    sharedContextInitialized = true;
                    ((IGraphicsContextInternal)graphicsContext).LoadAll();
                    OnGraphicsContextInitialized();
                }
            }
            else
            {
                ((IGraphicsContextInternal)graphicsContext).LoadAll();
                OnGraphicsContextInitialized();
            }

            this.OnInitialized(this, null);

            this.timerId = GLib.Timeout.Add(16, new GLib.TimeoutHandler(this.Render));

            return false;
        }
		/// <summary>
		/// 
		/// </summary>
		/// <see cref="http://www.opentk.com/doc/graphics/graphicscontext"/>
		public override void InitSynchronizedOnce()
		{
			if (!AlreadyInitialized)
			{
				AlreadyInitialized = true;
				AutoResetEvent CompletedEvent = new AutoResetEvent(false);
				var CThread = new Thread(() =>
				{
					Thread.CurrentThread.CurrentCulture = new CultureInfo(PspConfig.ThreadCultureName);

					var UsedGraphicsMode = new GraphicsMode(
						color: new OpenTK.Graphics.ColorFormat(8, 8, 8, 8),
						depth: 16,
						stencil: 8,
						samples: 0,
						accum: new OpenTK.Graphics.ColorFormat(16, 16, 16, 16),
						//accum: new OpenTK.Graphics.ColorFormat(0, 0, 0, 0),
						buffers: 2,
						stereo: false
					);

					var UsedGameWindowFlags = GameWindowFlags.Default;

					//Console.Error.WriteLine(UsedGraphicsMode);
					//Console.ReadKey();
#if USE_GL_CONTROL
					GLControl = new GLControl(UsedGraphicsMode, 3, 0, GraphicsContextFlags.Default);
#else
					NativeWindow = new NativeWindow(512, 272, "PspGraphicEngine", UsedGameWindowFlags, UsedGraphicsMode, DisplayDevice.GetDisplay(DisplayIndex.Default));
#endif
					
#if SHOW_WINDOW
					NativeWindow.Visible = true;
#endif
					//Utilities.CreateWindowsWindowInfo(handle);

					GraphicsContext = new GraphicsContext(UsedGraphicsMode, WindowInfo);
					GraphicsContext.MakeCurrent(WindowInfo);
					{
						GraphicsContext.LoadAll();
						Initialize();
					}
					GraphicsContext.SwapInterval = 0;

#if true
					//Console.WriteLine("## {0}", UsedGraphicsMode);
					Console.WriteLine("## UsedGraphicsMode: {0}", UsedGraphicsMode);
					Console.WriteLine("## GraphicsContext.GraphicsMode: {0}", GraphicsContext.GraphicsMode);

					Console.WriteLine("## OpenGL Context Version: {0}.{1}", GlGetInteger(GetPName.MajorVersion), GlGetInteger(GetPName.MinorVersion));

					Console.WriteLine("## Depth Bits: {0}", GlGetInteger(GetPName.DepthBits));
					Console.WriteLine("## Stencil Bits: {0}", GlGetInteger(GetPName.StencilBits));
					Console.WriteLine("## Accum Bits: {0},{1},{2},{3}", GlGetInteger(GetPName.AccumRedBits), GlGetInteger(GetPName.AccumGreenBits), GlGetInteger(GetPName.AccumBlueBits), GlGetInteger(GetPName.AccumAlphaBits));

					if (GlGetInteger(GetPName.StencilBits) <= 0)
					{
						ConsoleUtils.SaveRestoreConsoleState(() =>
						{
							Console.ForegroundColor = ConsoleColor.Red;
							Console.Error.WriteLine("No stencil bits available!");
						});
					}

					/*
					GL.Enable(EnableCap.StencilTest);
					GL.StencilMask(0xFF);
					GL.ClearColor(new Color4(Color.FromArgb(0x11, 0x22, 0x33, 0x44)));
					GL.ClearStencil(0x7F);
					GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.StencilBufferBit);

					var TestData = new uint[16 * 16];
					TestData[0] = 0x12345678;
					GL.ReadPixels(0, 0, 16, 16, PixelFormat.Rgba, PixelType.UnsignedInt8888Reversed, TestData);
					Console.WriteLine(GL.GetError());
					for (int n = 0; n < TestData.Length; n++) Console.Write("{0:X}", TestData[n]);
					*/
#endif

					GraphicsContext.MakeCurrent(null);
					CompletedEvent.Set();
					while (Running)
					{
#if !USE_GL_CONTROL
						NativeWindow.ProcessEvents();
#endif
						Thread.Sleep(1);
					}
					StopEvent.Set();
				});
				CThread.Name = "GpuImplEventHandling";
				CThread.IsBackground = true;
				CThread.Start();
				CompletedEvent.WaitOne();
			}
		}
Exemple #46
0
		internal void MakeContextCurrent(IGraphicsContext context, global::OpenTK.Platform.IWindowInfo windowInfo)
		{
			context.MakeCurrent(windowInfo);
			PurgeStateCache();
		}
Exemple #47
0
 /// <summary>Constructs a new GameWindow with the specified attributes.</summary>
 /// <param name="width">The width of the GameWindow in pixels.</param>
 /// <param name="height">The height of the GameWindow in pixels.</param>
 /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GameWindow.</param>
 /// <param name="title">The title of the GameWindow.</param>
 /// <param name="options">GameWindow options regarding window appearance and behavior.</param>
 /// <param name="device">The OpenTK.Graphics.DisplayDevice to construct the GameWindow in.</param>
 public GameWindow(int width, int height, GraphicsMode mode, string title, GameWindowFlags options, DisplayDevice device)
     : base(width, height, title, options, mode == null ? GraphicsMode.Default : mode, device == null ? DisplayDevice.Default : device)
 {
     try {
         glContext = Factory.Default.CreateGLContext(mode == null ? GraphicsMode.Default : mode, WindowInfo);
         glContext.MakeCurrent(WindowInfo);
         glContext.LoadAll();
         VSync = true;
         //glWindow.WindowInfoChanged += delegate(object sender, EventArgs e) { OnWindowInfoChangedInternal(e); };
     } catch (Exception e) {
         Debug.Print(e.ToString());
         base.Dispose();
         throw;
     }
 }
Exemple #48
0
        // Called when the widget needs to be (fully or partially) redrawn.
        protected override bool OnExposeEvent(Gdk.EventExpose eventExpose)
        {
            if (!initialized) {
                initialized = true;

                // If this looks uninitialized...  initialize.
                if (ColorBPP == 0) {
                    ColorBPP = 32;

                    if (DepthBPP == 0)
                        DepthBPP = 16;
                }

                ColorFormat colorBufferColorFormat = new ColorFormat (ColorBPP);

                ColorFormat accumulationColorFormat = new ColorFormat (AccumulatorBPP);

                int buffers = 2;
                if (SingleBuffer)
                    buffers--;

                GraphicsMode graphicsMode = new GraphicsMode (colorBufferColorFormat, DepthBPP, StencilBPP, Samples, accumulationColorFormat, buffers, Stereo);

                // IWindowInfo
                if (Configuration.RunningOnWindows) {
                    IntPtr windowHandle = gdk_win32_drawable_get_handle (GdkWindow.Handle);
                    windowInfo = Utilities.CreateWindowsWindowInfo (windowHandle);
                } else if (Configuration.RunningOnMacOS) {
                    IntPtr windowHandle = gdk_x11_drawable_get_xid (GdkWindow.Handle);
                    const bool ownHandle = true;
                    const bool isControl = true;
                    windowInfo = Utilities.CreateMacOSCarbonWindowInfo (windowHandle, ownHandle, isControl);
                } else if (Configuration.RunningOnX11) {
                    IntPtr display = gdk_x11_display_get_xdisplay (Display.Handle);
                    int screen = Screen.Number;
                    IntPtr windowHandle = gdk_x11_drawable_get_xid (GdkWindow.Handle);
                    IntPtr rootWindow = gdk_x11_drawable_get_xid (RootWindow.Handle);

                    IntPtr visualInfo;
                    if (graphicsMode.Index.HasValue) {
                        XVisualInfo info = new XVisualInfo ();
                        info.VisualID = graphicsMode.Index.Value;
                        int dummy;
                        visualInfo = XGetVisualInfo (display, XVisualInfoMask.ID, ref info, out dummy);
                    } else {
                        visualInfo = GetVisualInfo (display);
                    }

                    windowInfo = Utilities.CreateX11WindowInfo (display, screen, windowHandle, rootWindow, visualInfo);
                    XFree (visualInfo);
                } else
                    throw new PlatformNotSupportedException ();

                // GraphicsContext
                graphicsContext = new GraphicsContext (graphicsMode, windowInfo, GlVersionMajor, GlVersionMinor, GraphicsContextFlags);
                graphicsContext.MakeCurrent (windowInfo);

                if (GraphicsContext.ShareContexts) {
                    Interlocked.Increment (ref graphicsContextCount);

                    if (!sharedContextInitialized) {
                        sharedContextInitialized = true;
                        ((IGraphicsContextInternal)graphicsContext).LoadAll ();
                        OnGraphicsContextInitialized ();
                    }
                } else {
                    ((IGraphicsContextInternal)graphicsContext).LoadAll ();
                    OnGraphicsContextInitialized ();
                }

                OnInitialized ();
            } else {
                graphicsContext.MakeCurrent (windowInfo);
            }

            bool result = base.OnExposeEvent (eventExpose);
            OnRenderFrame ();
            eventExpose.Window.Display.Sync (); // Add Sync call to fix resize rendering problem (Jay L. T. Cornwall) - How does this affect VSync?
            graphicsContext.SwapBuffers ();
            return result;
        }
Exemple #49
0
 /// <summary>
 /// 
 /// </summary>
 /// <see cref="http://www.opentk.com/doc/graphics/graphicscontext"/>
 public override void InitSynchronizedOnce()
 {
     if (!AlreadySynchronized)
     {
         AlreadySynchronized = true;
         AutoResetEvent CompletedEvent = new AutoResetEvent(false);
         var CThread = new Thread(() =>
         {
             Thread.CurrentThread.CurrentCulture = new CultureInfo(PspConfig.CultureName);
             NativeWindow = new OpenTK.NativeWindow(512, 272, "PspGraphicEngine", GameWindowFlags.Default, GraphicsMode.Default, DisplayDevice.Default);
             NativeWindow.Visible = false;
             GraphicsContext = new GraphicsContext(GraphicsMode.Default, NativeWindow.WindowInfo);
             GraphicsContext.MakeCurrent(NativeWindow.WindowInfo);
             {
                 (GraphicsContext as IGraphicsContextInternal).LoadAll();
                 Initialize();
             }
             GraphicsContext.MakeCurrent(null);
             CompletedEvent.Set();
             while (Running)
             {
                 NativeWindow.ProcessEvents();
                 Thread.Sleep(1);
             }
             StopEvent.Set();
         });
         CThread.IsBackground = true;
         CThread.Start();
         CompletedEvent.WaitOne();
     }
 }
Exemple #50
0
		private void Initialize()
		{
			_Initialized = true;

			// If this looks uninitialized...  initialize.
			if (ColorBPP == 0)
			{
				ColorBPP = 32;

				if (DepthBPP == 0)
					DepthBPP = 16;
			}

			ColorFormat colorBufferColorFormat = new ColorFormat(ColorBPP);

			ColorFormat accumulationColorFormat = new ColorFormat(AccumulatorBPP);

			int buffers = 2;
			if (SingleBuffer)
				buffers--;

			GraphicsMode graphicsMode = new GraphicsMode(colorBufferColorFormat, DepthBPP, StencilBPP, Samples, accumulationColorFormat, buffers, Stereo);

			if (Configuration.RunningOnWindows)
				Console.WriteLine("OpenTK running on windows");
			else if (Configuration.RunningOnMacOS)
				Console.WriteLine("OpenTK running on OSX");
			else
				Console.WriteLine("OpenTK running on X11");

			// IWindowInfo
			if (Configuration.RunningOnWindows)
				_WindowInfo = InitializeWindows();
			else if (Configuration.RunningOnMacOS)
				_WindowInfo = InitializeOSX();
			else
				_WindowInfo = InitializeX(graphicsMode);

			// GraphicsContext
			_GraphicsContext = new GraphicsContext(graphicsMode, _WindowInfo, GLVersionMajor, GLVersionMinor, GraphicsContextFlags);
			_GraphicsContext.MakeCurrent(_WindowInfo);

			if (GraphicsContext.ShareContexts)
			{
				Interlocked.Increment(ref _GraphicsContextCount);

				if (!_SharedContextInitialized)
				{
					_SharedContextInitialized = true;
					((IGraphicsContextInternal)_GraphicsContext).LoadAll();
					OnGraphicsContextInitialized();
				}
			}
			else
			{
				((IGraphicsContextInternal)_GraphicsContext).LoadAll();
				OnGraphicsContextInitialized();
			}

			OnInitialized();
		}
        // Called when the widget needs to be (fully or partially) redrawn.
        protected override bool OnExposeEvent(Gdk.EventExpose eventExpose)
        {
            if (!initialized)
            {
                Console.WriteLine("GLWIDGET IS INITIALIZING!");

                initialized = true;

                // If this looks uninitialized...  initialize.
                if (ColorBPP == 0)
                {
                    ColorBPP = 32;

                    if (DepthBPP == 0) DepthBPP = 16;
                }

                ColorFormat colorBufferColorFormat = new ColorFormat(ColorBPP);

                ColorFormat accumulationColorFormat = new ColorFormat(AccumulatorBPP);

                int buffers = 2;
                if (SingleBuffer) buffers--;

                graphicsMode = new GraphicsMode(colorBufferColorFormat, DepthBPP, StencilBPP, Samples, accumulationColorFormat, buffers, Stereo);

                this.SetupWindowInfo();
                poisonedWindowHandle = false;

                // GraphicsContext
                graphicsContext = new GraphicsContext(graphicsMode, windowInfo, GlVersionMajor, GlVersionMinor, graphicsContextFlags);
                graphicsContext.MakeCurrent(windowInfo);

                if (false)
                {
                    Interlocked.Increment(ref graphicsContextCount);

                    if (!sharedContextInitialized)
                    {
                        sharedContextInitialized = true;
                        ((IGraphicsContextInternal)graphicsContext).LoadAll();
                        OnGraphicsContextInitialized();
                    }
                }
                else
                {
                    ((IGraphicsContextInternal)graphicsContext).LoadAll();
                    OnGraphicsContextInitialized();
                }

                OnInitialized();
            }
            else
            {
                if (poisonedWindowHandle)
                {
                    this.SetupWindowInfo();
                    poisonedWindowHandle = false;
                }

                graphicsContext.MakeCurrent(windowInfo);
            }

            bool result = base.OnExposeEvent(eventExpose);
            OnRenderFrame();
            eventExpose.Window.Display.Sync(); // Add Sync call to fix resize rendering problem (Jay L. T. Cornwall) - How does this affect VSync?
            graphicsContext.SwapBuffers();
            return result;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RenderCanvasWindowImp" /> class.
        /// </summary>
        /// <param name="windowHandle">The window handle.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        public RenderCanvasWindowImp(IntPtr windowHandle, int width, int height)
        {
            // _mode = GraphicsMode.Default;
            bool antiAliasing = true;
            _mode = new GraphicsMode(32, 24, 0, (antiAliasing) ? 8 : 0);
            _major = 1;
            _minor = 0;
            _flags = GraphicsContextFlags.Default;
            _wi = Utilities.CreateWindowsWindowInfo(windowHandle);

            try
            {
                _context = new GraphicsContext(_mode, _wi, _major, _minor, _flags);
            }
            catch
            {
                antiAliasing = false;
                _mode = new GraphicsMode(32, 24, 0, (antiAliasing) ? 8 : 0);
                _context = new GraphicsContext(_mode, _wi, _major, _minor, _flags);
            }

            _context.MakeCurrent(_wi);
            ((IGraphicsContextInternal)_context).LoadAll();

            GL.ClearColor(Color.MidnightBlue);

            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);

            // Use VSync!
            _context.SwapInterval = 1;
            _lastTimeTick = Timer;

            _width = width;
            _height = height;
        }