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 #2
0
        internal LegacyInputDriver(INativeWindow window)
        {
            if (window == null)
                throw new ArgumentNullException();

            var mouse = new MouseDevice();
            mouse.Description = "Standard Mouse";
            mouse.NumberOfButtons = 3;
            mouse.NumberOfWheels = 1;
            dummy_mice_list.Add(mouse);

            var keyboard = new KeyboardDevice();
            keyboard.Description = "Standard Keyboard";
            keyboard.NumberOfKeys = 101;
            keyboard.NumberOfLeds = 3;
            keyboard.NumberOfFunctionKeys = 12;
            dummy_keyboard_list.Add(keyboard);

            // Hook mouse events
            window.MouseDown += mouse.HandleMouseDown;
            window.MouseUp += mouse.HandleMouseUp;
            window.MouseMove += mouse.HandleMouseMove;
            window.MouseWheel += mouse.HandleMouseWheel;

            // Hook keyboard events
            window.KeyDown += keyboard.HandleKeyDown;
            window.KeyUp += keyboard.HandleKeyUp;
        }
        internal LegacyInputDriver(INativeWindow window)
        {
            if (window == null)
            {
                throw new ArgumentNullException();
            }

            var mouse = new MouseDevice();

            mouse.Description     = "Standard Mouse";
            mouse.NumberOfButtons = 3;
            mouse.NumberOfWheels  = 1;
            dummy_mice_list.Add(mouse);

            var keyboard = new KeyboardDevice();

            keyboard.Description          = "Standard Keyboard";
            keyboard.NumberOfKeys         = 101;
            keyboard.NumberOfLeds         = 3;
            keyboard.NumberOfFunctionKeys = 12;
            dummy_keyboard_list.Add(keyboard);

            // Hook mouse events
            window.MouseDown  += mouse.HandleMouseDown;
            window.MouseUp    += mouse.HandleMouseUp;
            window.MouseMove  += mouse.HandleMouseMove;
            window.MouseWheel += mouse.HandleMouseWheel;

            // Hook keyboard events
            window.KeyDown += keyboard.HandleKeyDown;
            window.KeyUp   += keyboard.HandleKeyUp;
        }
        public OpenGLApi(INativeWindow window)
        {
            glContext = Factory.Default.CreateGLContext(GraphicsMode.Default, window);
            GL.LoadEntryPoints(glContext);

            MinZNear = 0.1f;
            InitFields();

            int size;

            GL.GetIntegerv(GetPName.MaxTextureSize, &size);
            MaxTexWidth = size; MaxTexHeight = size;

                        #if !GL11
            CustomMipmapsLevels = true;
            CheckVboSupport();
                        #else
            CustomMipmapsLevels = false;
                        #endif
            base.InitCommon();

            setupBatchFuncCol4b            = SetupVbPos3fCol4b;
            setupBatchFuncTex2fCol4b       = SetupVbPos3fTex2fCol4b;
            setupBatchFuncCol4b_Range      = SetupVbPos3fCol4b_Range;
            setupBatchFuncTex2fCol4b_Range = SetupVbPos3fTex2fCol4b_Range;

            GL.EnableClientState(ArrayCap.VertexArray);
            GL.EnableClientState(ArrayCap.ColorArray);
        }
Exemple #5
0
 public static void BringToFront(INativeWindow window)
 {
     if (window == null || window.WindowInfo.Handle == IntPtr.Zero)
     {
         return;
     }
 }
Exemple #6
0
 public static void HideFromTaskbar(INativeWindow window)
 {
     if (window == null || window.WindowInfo.Handle == IntPtr.Zero)
     {
         return;
     }
 }
Exemple #7
0
        public Direct3D9Api(INativeWindow window)
        {
            MinZNear = 0.05f;
            IntPtr winHandle = window.WinHandle;

            d3d = Direct3D.Direct3DCreate9(Direct3D.SdkVersion);
            const int adapter = 0;             // default adapter

            InitFields();
            FindCompatibleFormat(adapter);

            PresentParameters args = GetPresentArgs(640, 480);

            try {
                device = Direct3D.CreateDevice(d3d, adapter, DeviceType.Hardware, winHandle, createFlags, &args);
            } catch (SharpDXException) {
                createFlags = CreateFlags.Mixed;
                try {
                    device = Direct3D.CreateDevice(d3d, adapter, DeviceType.Hardware, winHandle, createFlags, &args);
                } catch (SharpDXException) {
                    createFlags = CreateFlags.Software;
                    device      = Direct3D.CreateDevice(d3d, adapter, DeviceType.Hardware, winHandle, createFlags, &args);
                }
            }

            Capabilities caps;

            Device.GetCapabilities(device, &caps);
            MaxTexWidth  = caps.MaxTextureWidth;
            MaxTexHeight = caps.MaxTextureHeight;

            CustomMipmapsLevels = true;
            SetDefaultRenderStates();
            InitCommon();
        }
Exemple #8
0
        public void AfterTest(ITest details)
        {
            Console.WriteLine("----- Beginning Duality environment teardown -----");

            // Remove NUnit Console logs
            Logs.RemoveGlobalOutput(this.consoleLogOutput);
            this.consoleLogOutput = null;

            if (this.dummyWindow != null)
            {
                ContentProvider.ClearContent();
                this.dummyWindow.Dispose();
                this.dummyWindow = null;
            }

            // Save local testing memory. As this uses Duality serializers,
            // it needs to be done before terminating Duality.
            if (TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed && !System.Diagnostics.Debugger.IsAttached)
            {
                Serializer.WriteObject(TestHelper.LocalTestMemory, TestHelper.LocalTestMemoryFilePath, typeof(XmlSerializer));
            }

            DualityApp.Terminate();
            Environment.CurrentDirectory = this.oldEnvDir;

            Console.WriteLine("----- Duality environment teardown complete -----");
        }
Exemple #9
0
        public static void AddOpenGl(this IServiceCollection services)
        {
            services.AddSingleton <EglDisplay>(svc =>
            {
                //svc.GetRequiredService<BcmHost>();

                svc.GetRequiredService <ILogger <Program> >().LogDebug("Initializing EglDisplay");
                return(new EglDisplay());
            });
            services.AddSingleton <EglContext>(svc =>
            {
                EglDisplay display = svc.GetRequiredService <EglDisplay>();

                svc.GetRequiredService <ILogger <Program> >().LogDebug("Initializing EglContext");
                return(new EglContext(display));
            });
            services.AddSingleton <EglSurface>(svc =>
            {
                EglDisplay display         = svc.GetRequiredService <EglDisplay>();
                INativeWindow nativeWindow = svc.GetRequiredService <INativeWindow>();

                svc.GetRequiredService <ILogger <Program> >().LogDebug("Initializing EglSurface");
                return(new EglSurface(display, nativeWindow));
            });
            services.AddSingleton <Data>(svc =>
            {
                svc.GetRequiredService <ILogger <Program> >().LogDebug("Initializing Data");
                return(new Data());
            });
        }
Exemple #10
0
        private IEnumerable <GraphicsMode> GetModesPFD(INativeWindow native)
        {
            WinWindowInfo         window        = native.WindowInfo as WinWindowInfo;
            IntPtr                deviceContext = window.DeviceContext;
            PixelFormatDescriptor pfd           = new PixelFormatDescriptor();

            pfd.Size    = API.PixelFormatDescriptorSize;
            pfd.Version = API.PixelFormatDescriptorVersion;
            pfd.Flags   = PixelFormatDescriptorFlags.DRAW_TO_WINDOW | PixelFormatDescriptorFlags.SUPPORT_OPENGL;
            if (Environment.OSVersion.Version.Major >= 6)
            {
                pfd.Flags |= PixelFormatDescriptorFlags.SUPPORT_COMPOSITION;
            }
            // ISSUE: reference to a compiler-generated field
            this.\u003C\u003E7__wrapc = new bool[2]
            {
                false,
                true
            };
            bool[] flagArray;
            for (int index = 0; index < flagArray.Length; ++index)
            {
                bool generic_allowed = flagArray[index];
                int  pixel           = 0;
                while (WinGraphicsMode.DescribePixelFormat(deviceContext, ++pixel, (int)API.PixelFormatDescriptorSize, ref pfd) != 0)
                {
                    if (generic_allowed || (pfd.Flags & PixelFormatDescriptorFlags.GENERIC_FORMAT) == (PixelFormatDescriptorFlags)0)
                    {
                        GraphicsMode fmt = new GraphicsMode(new IntPtr?((IntPtr)pixel), new ColorFormat((int)pfd.RedBits, (int)pfd.GreenBits, (int)pfd.BlueBits, (int)pfd.AlphaBits), (int)pfd.DepthBits, (int)pfd.StencilBits, 0, new ColorFormat((int)pfd.AccumBits), (pfd.Flags & PixelFormatDescriptorFlags.DOUBLEBUFFER) != (PixelFormatDescriptorFlags)0 ? 2 : 1, (pfd.Flags & PixelFormatDescriptorFlags.STEREO) != (PixelFormatDescriptorFlags)0);
                        yield return(fmt);
                    }
                }
            }
        }
Exemple #11
0
        public static unsafe int CreateDxgiSwapchain
        (
            this INativeWindow window,
            IDXGIFactory2 *factory,
            IUnknown *pDevice,
            SwapChainDesc1 *pDesc,
            SwapChainFullscreenDesc *pFullscreenDesc,
            IDXGIOutput *pRestrictToOutput,
            IDXGISwapChain1 **ppSwapChain
        )
        {
            if (window.Win32.HasValue)
            {
                return(factory->CreateSwapChainForHwnd
                           (pDevice, window.Win32.Value.Hwnd, pDesc, pFullscreenDesc, pRestrictToOutput, ppSwapChain));
            }

            if (window.WinRT.HasValue)
            {
                return(factory->CreateSwapChainForCoreWindow
                           (pDevice, (IUnknown *)window.WinRT.Value, pDesc, pRestrictToOutput, ppSwapChain));
            }

            Throw();
            return(-1);
Exemple #12
0
        public void Dispose()
        {
            Console.WriteLine("----- Beginning Duality environment teardown -----");

            // Remove NUnit Console logs
            Logs.RemoveGlobalOutput(_consoleLogOutput);
            _consoleLogOutput = null;

            if (_dummyWindow != null)
            {
                ContentProvider.ClearContent();
                _dummyWindow.Dispose();
                _dummyWindow = null;
            }

            /*// Save local testing memory. As this uses Duality serializers,
             * // it needs to be done before terminating Duality.
             * if (TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Passed && !System.Diagnostics.Debugger.IsAttached)
             * {
             *      Serializer.WriteObject(TestHelper.LocalTestMemory, TestHelper.LocalTestMemoryFilePath, typeof(XmlSerializer));
             * }*/

            try
            {
                DualityApp.Terminate();
            }
            catch (BackendException)
            {
            }

            Environment.CurrentDirectory = _oldEnvDir;

            Console.WriteLine("----- Duality environment teardown complete -----");
        }
Exemple #13
0
        private static void Main(string[] args)
        {
            // Override working directory
            Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

            DualityApp.Init(DualityApp.ExecutionContext.Game, new DefaultAssemblyLoader(), args);

            ScreenMode newScreenMode;

            switch (Preferences.Get <int>("Screen", 0))
            {
            default:
            case 0: newScreenMode = ScreenMode.Window; break;

            case 1: newScreenMode = ScreenMode.FullWindow; break;
            }

            using (INativeWindow window = DualityApp.OpenWindow(new WindowOptions {
                Title = AssemblyTitle,
                RefreshMode = (args.Contains("/nv") ? RefreshMode.NoSync : (args.Contains("/mv") ? RefreshMode.ManualSync : RefreshMode.VSync)),
                Size = LevelRenderSetup.TargetSize,
                ScreenMode = newScreenMode
            })) {
                current = new App(window);
                current.ShowMainMenu();
                window.Run();
            }

            DualityApp.Terminate();

            // ToDo: Linux-specific workaround
            Environment.Exit(0);
        }
Exemple #14
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();
        }
        public void AfterTest(TestDetails details)
        {
            Console.WriteLine("----- Beginning Duality environment teardown -----");

            // Remove NUnit Console logs
            Log.RemoveGlobalOutput(this.consoleLogOutput);
            this.consoleLogOutput = null;

            if (this.dummyWindow != null)
            {
                ContentProvider.ClearContent();
                ContentProvider.DisposeDefaultContent();
                this.dummyWindow.Dispose();
                this.dummyWindow = null;
            }
            DualityApp.Terminate();
            Environment.CurrentDirectory = this.oldEnvDir;

            // Save local testing memory
            if (TestContext.CurrentContext.Result.Status == TestStatus.Passed && !System.Diagnostics.Debugger.IsAttached)
            {
                Serializer.WriteObject(TestHelper.LocalTestMemory, TestHelper.LocalTestMemoryFilePath, SerializeMethod.Xml);
            }

            Console.WriteLine("----- Duality environment teardown complete -----");
        }
Exemple #16
0
        private void OnMouseInput(INativeWindow window, IInputDevice device, ref HIDMouseInput input)
        {
            var mouseDevice  = (MouseDevice)InputDevice.GetOrAddDevice(device);
            var coreWindow   = window == null ? null : CoreWindow.FindWindow(window);
            var rootVisual   = coreWindow?.RootVisual;
            var hitUIElement = rootVisual?.InputHitTest(new Point(input.CursorX, input.CursorY));

            if (hitUIElement != null)
            {
                if (input.ChangedButton == 0)
                {
                    UIElement.RaiseEvent(new PointerRoutedEventArgs(UIElement.PointerMoveEvent, hitUIElement, mouseDevice));
                }
                else if (input.ChangedButton == 6)
                {
                    ;
                }
                else
                {
                    if (input.ChangedButtonState == PointerButtonState.Pressed)
                    {
                        UIElement.RaiseEvent(new PointerButtonRoutedEventArgs(UIElement.PointerPressedEvent, hitUIElement, mouseDevice,
                                                                              input.ChangedButton, input.ChangedButtonState));
                    }
                    else if (input.ChangedButtonState == PointerButtonState.Released)
                    {
                        UIElement.RaiseEvent(new PointerButtonRoutedEventArgs(UIElement.PointerReleasedEvent, hitUIElement, mouseDevice,
                                                                              input.ChangedButton, input.ChangedButtonState));
                    }
                }
            }
        }
        public void AfterTest(TestDetails details)
        {
            Console.WriteLine("----- Beginning Duality environment teardown -----");

            // Remove NUnit Console logs
            Log.RemoveGlobalOutput(this.consoleLogOutput);
            this.consoleLogOutput = null;

            if (this.dummyWindow != null)
            {
                ContentProvider.ClearContent();
                ContentProvider.DisposeDefaultContent();
                this.dummyWindow.Dispose();
                this.dummyWindow = null;
            }
            DualityApp.Terminate();
            Environment.CurrentDirectory = this.oldEnvDir;

            // Save local testing memory
            if (TestContext.CurrentContext.Result.Status == TestStatus.Passed && !System.Diagnostics.Debugger.IsAttached)
            {
                Serializer.WriteObject(TestHelper.LocalTestMemory, TestHelper.LocalTestMemoryFilePath, SerializeMethod.Xml);
            }

            Console.WriteLine("----- Duality environment teardown complete -----");
        }
        public static Matrix4 CreatePerspectiveFieldOfView(INativeWindow window)
        {
            float aspect = (float)window.Width / (float)window.Height;

            //return Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspect, 1.0f, 500.0f);
            return(Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspect, 0.00001f, 500.0f));
        }
Exemple #19
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 #20
0
        public KeyboardState(INativeWindow window)
        {
            _actions = new List <Actions>();

            window.KeyDown += Window_KeyDown;
            window.KeyUp   += Window_KeyUp;
        }
Exemple #21
0
            public TemporaryContext(INativeWindow native)
            {
                Debug.WriteLine("[WGL] Creating temporary context to load extensions");

                if (native == null)
                {
                    throw new ArgumentNullException();
                }

                // Create temporary context and load WGL entry points
                // First, set a compatible pixel format to the device context
                // of the temp window
                WinWindowInfo   window   = native.WindowInfo as WinWindowInfo;
                WinGraphicsMode selector = new WinGraphicsMode(window.DeviceContext);

                WinGLContext.SetGraphicsModePFD(selector, GraphicsMode.Default, window);

                bool success = false;

                // Then, construct a temporary context and load all wgl extensions
                Context = new ContextHandle(Wgl.CreateContext(window.DeviceContext));
                if (Context != ContextHandle.Zero)
                {
                    success = TryMakeCurrent(window, Context.Handle);
                }
                else
                {
                    Debug.Print("[WGL] CreateContext failed with error: {0}", Marshal.GetLastWin32Error());
                }

                if (!success)
                {
                    Debug.WriteLine("[WGL] Failed to create temporary context");
                }
            }
Exemple #22
0
        internal Window(
            string title,
            INativeWindow nativeWindow,
            SurfaceKhr surface,
            HostDevice hostDevice,
            HostDeviceRequirements deviceRequirements,
            Logger logger = null)
        {
            if (nativeWindow == null)
            {
                throw new ArgumentNullException(nameof(nativeWindow));
            }
            if (surface == null)
            {
                throw new ArgumentNullException(nameof(surface));
            }
            if (hostDevice == null)
            {
                throw new ArgumentNullException(nameof(hostDevice));
            }
            this.title        = title;
            this.nativeWindow = nativeWindow;
            this.surface      = surface;
            this.hostDevice   = hostDevice;
            this.logger       = logger;

            //Subscribe to callbacks for the native window
            nativeWindow.CloseRequested += OnNativeWindowCloseRequested;
            nativeWindow.Resized        += OnNativeWindowResized;

            //Create a logical device (and queues on the device)
            IList <string> enabledExtensions;

            (logicalDevice, graphicsQueue, presentQueue, enabledExtensions) = hostDevice.CreateLogicalDevice(
                surface: surface,
                deviceRequirements: deviceRequirements);
            hasDebugMarkerExtension = enabledExtensions.Contains("VK_EXT_debug_marker");
            if (hasDebugMarkerExtension)
            {
                logger?.Log(nameof(Window), "Enabled debug-markers");
            }

            //Get a presentmode to use
            presentMode = hostDevice.GetPresentMode(surface);
            //Get the surfaceformat to use
            (surfaceFormat, surfaceColorspace) = hostDevice.GetSurfaceFormat(surface);
            //Gets how many swapchain images we should use
            swapchainCount = hostDevice.GetSwapchainCount(surface);

            //Create a command-pool attached to this device
            commandPool = logicalDevice.CreateCommandPool(new CommandPoolCreateInfo(
                                                              queueFamilyIndex: graphicsQueue.FamilyIndex,
                                                              flags: CommandPoolCreateFlags.None
                                                              ));

            //Create the swapchain (images to present to the screen)
            CreateSwapchain(swapchainCount);
            //Synchronization objects are used to sync the rendering and presenting
            CreateSynchronizationObjects();
        }
        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 #24
0
        public static void TrackMouseCursor(ref Vector2 mouseDelta, INativeWindow window, Action updateCamera, Action lockMouseCursor)
        {
            Rectangle screen = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;

            if (NavigationInfo.NavigationType != NavigationType.Examine)
            {
                if (window.WindowState == WindowState.Fullscreen)
                {
                    mouseDelta = new Vector2
                                 (
                        System.Windows.Forms.Cursor.Position.X - (screen.Width / 2.0f),
                        System.Windows.Forms.Cursor.Position.Y - (screen.Height / 2.0f)
                                 );

                    mouseDelta *= 0.005f;
                }
                else
                {
                    //mouseDelta = new Vector2
                    //(
                    //    window.Bounds.Left + (System.Windows.Forms.Cursor.Position.X - (window.Width / 2.0f) ),
                    //    window.Bounds.Top + (System.Windows.Forms.Cursor.Position.Y - (window.Height / 2.0f))
                    //);
                }

                updateCamera();

                lockMouseCursor();
            }
            else
            {
                if (window.WindowState == WindowState.Fullscreen)
                {
                    mouseDelta = new Vector2
                                 (
                        System.Windows.Forms.Cursor.Position.X - (screen.Width / 2.0f),
                        System.Windows.Forms.Cursor.Position.Y - (screen.Height / 2.0f)
                                 );

                    mouseDelta *= 0.005f;

                    updateCamera();

                    lockMouseCursor();
                }
                else
                {
                    mouseDelta = new Vector2
                                 (
                        System.Windows.Forms.Cursor.Position.X - screen.Width,
                        System.Windows.Forms.Cursor.Position.Y - screen.Height
                                 );

                    mouseDelta *= 0.0005f;

                    updateCamera();
                }
            }
        }
    public NativeWindow()
    {
#if UNITY_EDITOR
        m_platformWrapper = new NativeWindow_Editor();
#elif UNITY_STANDALONE_WIN
        m_platformWrapper = new NativeWindow_Windows();
#endif
    }
Exemple #26
0
        public void Update(INativeWindow window, float elapsedTime)
        {
            ImGuiIOPtr io = ImGui.GetIO();

            io.DisplaySize             = new Vector2(width / scaleFactor.X, height / scaleFactor.Y);
            io.DisplayFramebufferScale = scaleFactor;
            io.DeltaTime = elapsedTime;
        }
		void IDisposable.Dispose()
		{
			if (this.dummyWindow != null)
			{
				this.dummyWindow.Dispose();
				this.dummyWindow = null;
			}
		}
Exemple #28
0
 public DrawingContext(INativeWindow window, SpriteBatch spriteBatch)
 {
     this.window      = window;
     this.offset      = Point2D.Empty;
     this.offsetStack = new Stack <Point2D>();
     this.spriteBatch = spriteBatch;
     this.spriteBatch.Begin();
 }
Exemple #29
0
 void IDisposable.Dispose()
 {
     if (this.dummyWindow != null)
     {
         this.dummyWindow.Dispose();
         this.dummyWindow = null;
     }
 }
 protected NativeWindowBase(int width, int height, IMonitor monitor)
 {
     _monitor = monitor;
     _implementation = Platform.Factory.CreateWindow(width, height, monitor);
     _implementation.Resized += OnResize;
     _implementation.Load += OnLoad;
     _implementation.Update += OnUpdate;
     _implementation.Render += OnRender;
 }
Exemple #31
0
        public MouseState(INativeWindow window)
        {
            _click_position = new Point();
            _actions        = new List <Actions>();

            window.MouseUp   += Window_MouseUp;
            window.MouseDown += Window_MouseDown;
            window.MouseMove += Window_MouseMove;
        }
Exemple #32
0
        public App(INativeWindow window)
        {
            this.window = window;

            // Load settings to cache
            SettingsCache.Resize      = (SettingsCache.ResizeMode)Preferences.Get <byte>("Resize", (byte)SettingsCache.Resize);
            SettingsCache.MusicVolume = Preferences.Get <byte>("MusicVolume", (byte)(SettingsCache.MusicVolume * 100)) * 0.01f;
            SettingsCache.SfxVolume   = Preferences.Get <byte>("SfxVolume", (byte)(SettingsCache.SfxVolume * 100)) * 0.01f;
        }
Exemple #33
0
 public Input(INativeWindow window)
 {
     this.window       = window;
     window.KeyDown   += (s, a) => pressedButtons.Add(a.Key.ToString());
     window.KeyUp     += (s, a) => pressedButtons.Remove(a.Key.ToString());
     window.MouseDown += Window_MouseDown;
     window.MouseUp   += Window_MouseUp;
     window.MouseMove += Window_MouseMove;
 }
        public ContentProcessorContext(string workingDirectory = "")
        {
            this.WorkingDirectory = workingDirectory;
            //window = new GameWindow();
            window = new NativeWindow();

            ThreadingHelper.Initialize(window.WindowInfo, 3, 1, GraphicsContextFlags.Debug);
            GraphicsDevice = new GraphicsDevice(null, ThreadingHelper.context);
        }
 private static void CreateDefaultContext()
 {
     if (s_defaultContext == null)
     {
         s_defaultDummyNativeWindow = new NativeWindow();
         s_defaultContext           = new GraphicsContext(GraphicsMode.Default, s_defaultDummyNativeWindow.WindowInfo);
         s_defaultContext.LoadAll();
     }
 }
		public DummyNativeEditorGraphicsContext()
		{
			// Since the graphics backend probably needs some kind of graphics context, create an invisible dummy window.
			this.dummyWindow = DualityApp.GraphicsBackend.CreateWindow(new WindowOptions
			{
				Width = 640,
				Height = 480,
				ScreenMode = ScreenMode.Window,
				RefreshMode = RefreshMode.NoSync
			});
		}
Exemple #37
0
        public IGL_SlimDX9()
        {
            if (d3d == null)
            {
                d3d = new Direct3D();
            }

            //make an 'offscreen context' so we can at least do things without having to create a window
            OffscreenNativeWindow = new OpenTK.NativeWindow();
            OffscreenNativeWindow.ClientSize = new sd.Size(8, 8);

            CreateDevice();
        }
        public GUIEventSystem(GUIContainer root, MouseDevice mouse, KeyboardDevice keyboard, INativeWindow window)
        {
            this.root = root;

            mouse.Move += new EventHandler<OpenTK.Input.MouseMoveEventArgs>(mouse_Move);
            mouse.ButtonDown += new EventHandler<OpenTK.Input.MouseButtonEventArgs>(mouse_ButtonDown);
            mouse.ButtonUp += new EventHandler<OpenTK.Input.MouseButtonEventArgs>(mouse_ButtonUp);
            mouse.WheelChanged += new EventHandler<OpenTK.Input.MouseWheelEventArgs>(mouse_WheelChanged);

            this.keyboard = keyboard;
            keyboard.KeyDown += new EventHandler<KeyboardKeyEventArgs>(keyboard_KeyDown);
            keyboard.KeyUp += new EventHandler<KeyboardKeyEventArgs>(keyboard_KeyUp);
            window.KeyPress += new EventHandler<KeyPressEventArgs>(window_KeyPress);
        }
Exemple #39
0
        public IGL_TK()
        {
            //make an 'offscreen context' so we can at least do things without having to create a window
            OffscreenNativeWindow = new NativeWindow();
            OffscreenNativeWindow.ClientSize = new sd.Size(8, 8);
            this.GraphicsContext = new GraphicsContext(GraphicsMode.Default, OffscreenNativeWindow.WindowInfo, 2, 0, GraphicsContextFlags.Default);
            MakeDefaultCurrent();

            //this is important for reasons unknown
            this.GraphicsContext.LoadAll();

            //misc initialization
            CreateRenderStates();
            PurgeStateCache();
        }
Exemple #40
0
            public TemporaryContext(INativeWindow native)
            {
                Debug.WriteLine("[WGL] Creating temporary context to load extensions");

                if (native == null)
                    throw new ArgumentNullException();

                // Create temporary context and load WGL entry points
                // First, set a compatible pixel format to the device context
                // of the temp window
                WinWindowInfo window = native.WindowInfo as WinWindowInfo;
                WinGraphicsMode selector = new WinGraphicsMode(window.DeviceContext);
                WinGLContext.SetGraphicsModePFD(selector, GraphicsMode.Default, window);

                bool success = false;

                // Then, construct a temporary context and load all wgl extensions
                Context = new ContextHandle(Wgl.CreateContext(window.DeviceContext));
                if (Context != ContextHandle.Zero)
                {
                    // Make the context current.
                    // Note: on some video cards and on some virtual machines, wglMakeCurrent
                    // may fail with an errorcode of 6 (INVALID_HANDLE). The suggested workaround
                    // is to call wglMakeCurrent in a loop until it succeeds.
                    // See https://www.opengl.org/discussion_boards/showthread.php/171058-nVidia-wglMakeCurrent()-multiple-threads
                    // Sigh...
                    for (int retry = 0; retry < 5 && !success; retry++)
                    {
                        success = Wgl.MakeCurrent(window.DeviceContext, Context.Handle);
                        if (!success)
                        {
                            Debug.Print("wglMakeCurrent failed with error: {0}. Retrying", Marshal.GetLastWin32Error());
                            System.Threading.Thread.Sleep(10);
                        }
                    }
                }
                else
                {
                    Debug.Print("[WGL] CreateContext failed with error: {0}", Marshal.GetLastWin32Error());
                }

                if (!success)
                {
                    Debug.WriteLine("[WGL] Failed to create temporary context");
                }
            }
		public void BeforeTest(TestDetails details)
		{
			Console.WriteLine("----- Beginning Duality environment setup -----");

			// Set environment directory to Duality binary directory
			this.oldEnvDir = Environment.CurrentDirectory;
			string codeBaseURI = typeof(DualityApp).Assembly.CodeBase;
			string codeBasePath = codeBaseURI.StartsWith("file:") ? codeBaseURI.Remove(0, "file:".Length) : codeBaseURI;
			codeBasePath = codeBasePath.TrimStart('/');
			Environment.CurrentDirectory = Path.GetDirectoryName(codeBasePath);

			// Add some Console logs manually for NUnit
			if (!Log.Core.Outputs.OfType<TextWriterLogOutput>().Any(o => o.Target == Console.Out))
			{
				if (this.consoleLogOutput == null) this.consoleLogOutput = new TextWriterLogOutput(Console.Out);
				Log.AddGlobalOutput(this.consoleLogOutput);
			}

			// Initialize Duality
			DualityApp.Init(
				DualityApp.ExecutionEnvironment.Launcher, 
				DualityApp.ExecutionContext.Game, 
				new DefaultPluginLoader(),
				null);

			// Manually register pseudo-plugin for the Unit Testing Assembly
			this.unitTestPlugin = DualityApp.LoadPlugin(typeof(DualityTestsPlugin).Assembly, codeBasePath);

			// Create a dummy window, to get access to all the device contexts
			if (this.dummyWindow == null)
			{
				WindowOptions options = new WindowOptions
				{
					Width = 800,
					Height = 600
				};
				this.dummyWindow = DualityApp.OpenWindow(options);
			}

			// Load local testing memory
			TestHelper.LocalTestMemory = Serializer.TryReadObject<TestMemory>(TestHelper.LocalTestMemoryFilePath, typeof(XmlSerializer));

			Console.WriteLine("----- Duality environment setup complete -----");
		}
Exemple #42
0
        /// <summary>Constructs a new NativeWindow with the specified attributes.</summary>
        /// <param name="x">Horizontal screen space coordinate of the NativeWindow's origin.</param>
        /// <param name="y">Vertical screen space coordinate of the NativeWindow's origin.</param>
        /// <param name="width">The width of the NativeWindow in pixels.</param>
        /// <param name="height">The height of the NativeWindow in pixels.</param>
        /// <param name="title">The title of the NativeWindow.</param>
        /// <param name="options">GameWindow options specifying window appearance and behavior.</param>
        /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the NativeWindow.</param>
        /// <param name="device">The OpenTK.Graphics.DisplayDevice to construct the NativeWindow in.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">If width or height is less than 1.</exception>
        /// <exception cref="System.ArgumentNullException">If mode or device is null.</exception>
        public NativeWindow(int x, int y, int width, int height, string title, GameWindowFlags options, GraphicsMode mode, DisplayDevice device)
        {
            // TODO: Should a constraint be added for the position?
            if (width < 1)
                throw new ArgumentOutOfRangeException("width", "Must be greater than zero.");
            if (height < 1)
                throw new ArgumentOutOfRangeException("height", "Must be greater than zero.");
            if (mode == null)
                throw new ArgumentNullException("mode");
            if (device == null)
                throw new ArgumentNullException("device");

            this.options = options;
            this.device = device;

            implementation = Factory.Default.CreateNativeWindow(x, y, width, height, title, mode, options, this.device);

            if ((options & GameWindowFlags.Fullscreen) != 0)
            {
                this.device.ChangeResolution(width, height, mode.ColorFormat.BitsPerPixel, 0);
                WindowState = WindowState.Fullscreen;
            }
        }
Exemple #43
0
 private IEnumerable<GraphicsMode> GetModesPFD(INativeWindow native)
 {
     WinWindowInfo window = native.WindowInfo as WinWindowInfo;
       IntPtr deviceContext = window.DeviceContext;
       PixelFormatDescriptor pfd = new PixelFormatDescriptor();
       pfd.Size = API.PixelFormatDescriptorSize;
       pfd.Version = API.PixelFormatDescriptorVersion;
       pfd.Flags = PixelFormatDescriptorFlags.DRAW_TO_WINDOW | PixelFormatDescriptorFlags.SUPPORT_OPENGL;
       if (Environment.OSVersion.Version.Major >= 6)
     pfd.Flags |= PixelFormatDescriptorFlags.SUPPORT_COMPOSITION;
       // ISSUE: reference to a compiler-generated field
       this.\u003C\u003E7__wrapc = new bool[2]
       {
     false,
     true
       };
       bool[] flagArray;
       for (int index = 0; index < flagArray.Length; ++index)
       {
     bool generic_allowed = flagArray[index];
     int pixel = 0;
     while (WinGraphicsMode.DescribePixelFormat(deviceContext, ++pixel, (int) API.PixelFormatDescriptorSize, ref pfd) != 0)
     {
       if (generic_allowed || (pfd.Flags & PixelFormatDescriptorFlags.GENERIC_FORMAT) == (PixelFormatDescriptorFlags) 0)
       {
     GraphicsMode fmt = new GraphicsMode(new IntPtr?((IntPtr) pixel), new ColorFormat((int) pfd.RedBits, (int) pfd.GreenBits, (int) pfd.BlueBits, (int) pfd.AlphaBits), (int) pfd.DepthBits, (int) pfd.StencilBits, 0, new ColorFormat((int) pfd.AccumBits), (pfd.Flags & PixelFormatDescriptorFlags.DOUBLEBUFFER) != (PixelFormatDescriptorFlags) 0 ? 2 : 1, (pfd.Flags & PixelFormatDescriptorFlags.STEREO) != (PixelFormatDescriptorFlags) 0);
     yield return fmt;
       }
     }
       }
 }
        private void Initialize(Game game)
        {
            Game = game;
#if LINUX
            _init = false;
#endif

            GraphicsContext.ShareContexts = true;

            window = new NativeWindow();
            window.Closing += new EventHandler<CancelEventArgs>(OpenTkGameWindow_Closing);
            window.Resize += OnResize;
            window.KeyDown += new EventHandler<OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyDown);
            window.KeyUp += new EventHandler<OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyUp);
#if LINUX
            window.WindowBorder = WindowBorder.Resizable;
#endif
#if WINDOWS
            window.MouseEnter += OnMouseEnter;
            window.MouseLeave += OnMouseLeave;
#endif

            window.KeyPress += OnKeyPress;

            // Set the window icon.
            var assembly = Assembly.GetEntryAssembly();
            if(assembly != null)
                window.Icon = Icon.ExtractAssociatedIcon(assembly.Location);
            Title = MonoGame.Utilities.AssemblyHelper.GetDefaultWindowTitle();

            updateClientBounds = false;
            clientBounds = new Rectangle(window.ClientRectangle.X, window.ClientRectangle.Y,
                                         window.ClientRectangle.Width, window.ClientRectangle.Height);
            windowState = window.WindowState;            

            _windowHandle = window.WindowInfo.Handle;

            keys = new List<Keys>();

            // mouse
            // TODO review this when opentk 1.1 is released
#if WINDOWS || LINUX || ANGLE
            Mouse.setWindows(this);
#else
            Mouse.UpdateMouseInfo(window.Mouse);
#endif

            // Default no resizing
            AllowUserResizing = false;

            // Default mouse cursor hidden 
            SetMouseVisible(false);
        }
        private void Initialize(Game game)
        {
            Game = game;

            GraphicsContext.ShareContexts = true;

            window = new NativeWindow();
            window.WindowBorder = WindowBorder.Resizable;
            window.Closing += new EventHandler<CancelEventArgs>(OpenTkGameWindow_Closing);
            window.Resize += OnResize;
            window.KeyDown += new EventHandler<OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyDown);
            window.KeyUp += new EventHandler<OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyUp);

            window.KeyPress += OnKeyPress;

            //make sure that the game is not running on linux
            //on Linux people may want to use mkbundle to
            //create native Linux binaries
            if (CurrentPlatform.OS != OS.Linux)
            {
                // Set the window icon.
                var assembly = Assembly.GetEntryAssembly();
                if (assembly != null)
                    window.Icon = Icon.ExtractAssociatedIcon(assembly.Location);
                Title = MonoGame.Utilities.AssemblyHelper.GetDefaultWindowTitle();
            }

            updateClientBounds = false;
            clientBounds = new Rectangle(window.ClientRectangle.X, window.ClientRectangle.Y,
                                         window.ClientRectangle.Width, window.ClientRectangle.Height);
            windowState = window.WindowState;            

            _windowHandle = window.WindowInfo.Handle;

            keys = new List<Keys>();

            // mouse
            // TODO review this when opentk 1.1 is released
#if DESKTOPGL || ANGLE
            Mouse.setWindows(this);
#else
            Mouse.UpdateMouseInfo(window.Mouse);
#endif

            // Default no resizing
            AllowUserResizing = false;

            // Default mouse cursor hidden 
            SetMouseVisible(false);
        }
Exemple #46
0
        /// <summary>Constructs a new NativeWindow with the specified attributes.</summary>
        /// <param name="x">Horizontal screen space coordinate of the NativeWindow's origin.</param>
        /// <param name="y">Vertical screen space coordinate of the NativeWindow's origin.</param>
        /// <param name="width">The width of the NativeWindow in pixels.</param>
        /// <param name="height">The height of the NativeWindow in pixels.</param>
        /// <param name="title">The title of the NativeWindow.</param>
        /// <param name="options">GameWindow options specifying window appearance and behavior.</param>
        /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the NativeWindow.</param>
        /// <param name="device">The OpenTK.Graphics.DisplayDevice to construct the NativeWindow in.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">If width or height is less than 1.</exception>
        /// <exception cref="System.ArgumentNullException">If mode or device is null.</exception>
        public NativeWindow(int x, int y, int width, int height, string title, GameWindowFlags options, GraphicsMode mode, DisplayDevice device)
        {
            // TODO: Should a constraint be added for the position?
            if (width < 1)
                throw new ArgumentOutOfRangeException("width", "Must be greater than zero.");
            if (height < 1)
                throw new ArgumentOutOfRangeException("height", "Must be greater than zero.");
            if (mode == null)
                throw new ArgumentNullException("mode");

            this.options = options;
            this.device = device;

            this.thread_id = System.Threading.Thread.CurrentThread.ManagedThreadId;

            IPlatformFactory factory = Factory.Default;
            implementation = factory.CreateNativeWindow(x, y, width, height, title, mode, options, this.device);
            factory.RegisterResource(this);

            if ((options & GameWindowFlags.Fullscreen) != 0)
            {
                if (this.device != null)
                {
                    this.device.ChangeResolution(width, height, mode.ColorFormat.BitsPerPixel, 0);
                }
                WindowState = WindowState.Fullscreen;
            }

            if ((options & GameWindowFlags.FixedWindow) != 0)
            {
                WindowBorder = WindowBorder.Fixed;
            }
        }
Exemple #47
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 #48
0
        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;
                        }
                    }
                }
            }
        }
Exemple #49
0
        IEnumerable<GraphicsMode> GetModesPFD(INativeWindow native)
        {
            WinWindowInfo window = native.WindowInfo as WinWindowInfo;
            IntPtr deviceContext = ((WinWindowInfo)window).DeviceContext;
            Debug.WriteLine(String.Format("Device context: {0}", deviceContext));

            Debug.WriteLine("Retrieving PFD pixel formats... ");
            PixelFormatDescriptor pfd = new PixelFormatDescriptor();
            pfd.Size = API.PixelFormatDescriptorSize;
            pfd.Version = API.PixelFormatDescriptorVersion;
            pfd.Flags =
                PixelFormatDescriptorFlags.SUPPORT_OPENGL |
                PixelFormatDescriptorFlags.DRAW_TO_WINDOW;

            // Make sure we don't turn off Aero on Vista and newer.
            if (Environment.OSVersion.Version.Major >= 6)
            {
                pfd.Flags |= PixelFormatDescriptorFlags.SUPPORT_COMPOSITION;
            }

            foreach (bool generic_allowed in new bool[] { false, true })
            {
                // Iterate through all accelerated formats first. Afterwards, iterate through non-accelerated formats.
                // This should fix issue #2224, which causes OpenTK to fail on VMs without hardware acceleration.
                int pixel = 0;
                while (DescribePixelFormat(deviceContext, ++pixel, API.PixelFormatDescriptorSize, ref pfd) != 0)
                {
                    // Ignore non-accelerated formats.
                    if (!generic_allowed && (pfd.Flags & PixelFormatDescriptorFlags.GENERIC_FORMAT) != 0)
                        continue;

                    GraphicsMode fmt = new GraphicsMode((IntPtr)pixel,
                        new ColorFormat(pfd.RedBits, pfd.GreenBits, pfd.BlueBits, pfd.AlphaBits),
                        pfd.DepthBits,
                        pfd.StencilBits,
                        0,
                        new ColorFormat(pfd.AccumBits),
                        (pfd.Flags & PixelFormatDescriptorFlags.DOUBLEBUFFER) != 0 ? 2 : 1,
                        (pfd.Flags & PixelFormatDescriptorFlags.STEREO) != 0);

                    yield return fmt;
                }
            }
        }
Exemple #50
0
 private IEnumerable<GraphicsMode> GetModesARB(INativeWindow native)
 {
     using ((IGraphicsContext) new GraphicsContext(new GraphicsMode(new IntPtr?(new IntPtr(2)), new ColorFormat(), 0, 0, 0, new ColorFormat(), 2, false), native.WindowInfo, 1, 0, GraphicsContextFlags.Default))
       {
     WinWindowInfo window = (WinWindowInfo) native.WindowInfo;
     if (Wgl.Delegates.wglChoosePixelFormatARB == null || Wgl.Delegates.wglGetPixelFormatAttribivARB == null)
     {
       // ISSUE: reference to a compiler-generated method
       this.System\u002EIDisposable\u002EDispose();
     }
     else
     {
       // ISSUE: reference to a compiler-generated field
       this.\u003Cattribs\u003E5__13 = new int[18]
       {
     8195,
     8213,
     8215,
     8217,
     8219,
     8212,
     8226,
     8227,
     8257,
     8258,
     8222,
     8223,
     8224,
     8225,
     8221,
     8209,
     8210,
     0
       };
       int[] attribs;
       int[] values = new int[attribs.Length];
       // ISSUE: reference to a compiler-generated field
       this.\u003Cattribs_values\u003E5__15 = new int[8]
       {
     8195,
     8231,
     8208,
     1,
     8193,
     1,
     0,
     0
       };
       int[] num_formats = new int[1];
       int[] attribs_values;
       if (Wgl.Arb.ChoosePixelFormat(window.DeviceContext, attribs_values, (float[]) null, 0, (int[]) null, num_formats))
       {
     int[] pixel = new int[num_formats[0]];
     if (Wgl.Arb.ChoosePixelFormat(window.DeviceContext, attribs_values, (float[]) null, pixel.Length, pixel, num_formats))
     {
       foreach (int iPixelFormat in pixel)
       {
         if (Wgl.Arb.GetPixelFormatAttrib(window.DeviceContext, iPixelFormat, 0, attribs.Length - 1, attribs, values))
         {
           GraphicsMode mode = new GraphicsMode(new IntPtr?(new IntPtr(iPixelFormat)), 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);
           yield return mode;
         }
       }
     }
       }
     }
       }
 }
		/// <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();
			}
		}
 private void CreateContext()
 {
     window = new GameWindow();
     context = new GraphicsContext(GraphicsMode.Default, window.WindowInfo);
     context.MakeCurrent(window.WindowInfo);
 }
Exemple #53
0
 void IDisposable.Dispose()
 {
     //TODO - a lot of analysis here
     OffscreenNativeWindow.Dispose(); OffscreenNativeWindow = null;
     GraphicsContext.Dispose(); GraphicsContext = null;
 }
Exemple #54
0
        private void Initialize(Game game)
        {
            Game = game;

            GraphicsContext.ShareContexts = true;

            window = new NativeWindow();
            window.WindowBorder = WindowBorder.Resizable;
            window.Closing += new EventHandler<CancelEventArgs>(OpenTkGameWindow_Closing);
            window.Resize += OnResize;
            window.KeyDown += new EventHandler<OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyDown);
            window.KeyUp += new EventHandler<OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyUp);

            window.KeyPress += OnKeyPress;

            var assembly = Assembly.GetEntryAssembly();
            var t = Type.GetType ("Mono.Runtime");

            Title = assembly != null ? AssemblyHelper.GetDefaultWindowTitle() : "MonoGame Application";

            // In case when DesktopGL dll is compiled using .Net, and you
            // try to load it using Mono, it will cause a crash because of this.
            try
            {
                if (t == null && assembly != null)
                    window.Icon = Icon.ExtractAssociatedIcon(assembly.Location);
                else {
                    using (var stream = Assembly.GetEntryAssembly().GetManifestResourceStream(string.Format("{0}.Icon.ico", Assembly.GetEntryAssembly().EntryPoint.DeclaringType.Namespace)) ?? 
                            Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.Xna.Framework.monogame.ico")) {
                        if (stream != null)
                           window.Icon = new Icon(stream);
                    }
                }
            }
            catch { }

            updateClientBounds = false;
            clientBounds = new Rectangle(window.ClientRectangle.X, window.ClientRectangle.Y,
                                         window.ClientRectangle.Width, window.ClientRectangle.Height);
            windowState = window.WindowState;            

            _windowHandle = window.WindowInfo.Handle;

            keys = new List<Keys>();

            // mouse
            // TODO review this when opentk 1.1 is released
#if DESKTOPGL || ANGLE
            Mouse.setWindows(this);
#else
            Mouse.UpdateMouseInfo(window.Mouse);
#endif

            // Default no resizing
            AllowUserResizing = false;

            // Default mouse cursor hidden 
            SetMouseVisible(false);
        }