Instances of this class implement the OpenTK.INativeWindow interface on the current platform.
Inheritance: INativeWindow
Exemple #1
0
        public unsafe SampleWindow()
        {
            int desiredWidth = 960, desiredHeight = 540;
            _nativeWindow = new NativeWindow(desiredWidth, desiredHeight, "ImGui.NET", GameWindowFlags.Default, OpenTK.Graphics.GraphicsMode.Default, DisplayDevice.Default);
            _scaleFactor = _nativeWindow.Width / desiredWidth;

            GraphicsContextFlags flags = GraphicsContextFlags.Default;
            _graphicsContext = new GraphicsContext(GraphicsMode.Default, _nativeWindow.WindowInfo, 3, 0, flags);
            _graphicsContext.MakeCurrent(_nativeWindow.WindowInfo);
            ((IGraphicsContextInternal)_graphicsContext).LoadAll(); // wtf is this?
            GL.ClearColor(Color.Black);
            _nativeWindow.Visible = true;
            _nativeWindow.X = _nativeWindow.X; // Work around OpenTK bug (?) on Ubuntu.

            _nativeWindow.KeyDown += OnKeyDown;
            _nativeWindow.KeyUp += OnKeyUp;
            _nativeWindow.KeyPress += OnKeyPress;

            ImGui.GetIO().FontAtlas.AddDefaultFont();

            SetOpenTKKeyMappings();

            _textInputBufferLength = 1024;
            _textInputBuffer = Marshal.AllocHGlobal(_textInputBufferLength);
            long* ptr = (long*)_textInputBuffer.ToPointer();
            for (int i = 0; i < 1024 / sizeof(long); i++)
            {
                ptr[i] = 0;
            }

            CreateDeviceObjects();
        }
        public RayTracerWindow(int width, int height)
        {
            _nativeWindow = new NativeWindow(width, height, "", GameWindowFlags.Default, GraphicsMode.Default, DisplayDevice.Default);
            GraphicsContextFlags flags = GraphicsContextFlags.Default;
            #if DEBUG
            //flags |= GraphicsContextFlags.Debug;
            #endif
            _graphicsContext = new GraphicsContext(GraphicsMode.Default, _nativeWindow.WindowInfo, 3, 0, flags);
            _graphicsContext.MakeCurrent(_nativeWindow.WindowInfo);
            ((IGraphicsContextInternal)_graphicsContext).LoadAll(); // wtf is this?

            SetInitialStates();
            SetViewport();

            _nativeWindow.Resize += OnGameWindowResized;
            _nativeWindow.Closing += OnWindowClosing;
            _nativeWindow.KeyDown += OnKeyDown;

            _scene = Scene.TwoPlanes;
            _scene.Camera.ReflectionDepth = DefaultReflectionDepth;

            SetTitle();

            _renderTexture = new RenderTexture(_nativeWindow.Width, _nativeWindow.Height);

            _scenes = typeof(Scene).GetProperties()
                .Where(pi => pi.PropertyType == typeof(Scene))
                .Select(pi => pi.GetValue(null))
                .Cast<Scene>().ToList();
        }
        public void Run()
        {
            GraphicsMode gmode = new GraphicsMode(GraphicsMode.Default.ColorFormat, GraphicsMode.Default.Depth, GraphicsMode.Default.Stencil, 0);

            DisplayDevice dd = DisplayDevice.Default;

            NativeWindow nw = new NativeWindow(Width, Height, "Test", GameWindowFlags.Default, gmode, dd);

            GraphicsContext glContext = new GraphicsContext(gmode, nw.WindowInfo, 3, 0, GraphicsContextFlags.Default);
            glContext.LoadAll();

            glContext.MakeCurrent(nw.WindowInfo);

            if (Load())
            {
                nw.Visible = true;
                while (nw.Visible)
                {
                    Frame();

                    glContext.SwapBuffers();

                    Thread.Sleep(1000 / 60); //"60" fps (not really...)

                    nw.ProcessEvents();
                }

                nw.Visible = false;
            }

            Unload();
        }
Exemple #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="nginz.MouseBuffer"/> class.
        /// </summary>
        public MouseBuffer(NativeWindow window, Game game = null, bool shouldCenterMouse = false, bool mouseVisible = true)
        {
            // Set the window
            this.window = window;
            this.game = game;

            // Initialize wheel and delta values
            Wheel = 0.0f;
            DeltaX = 0.0f;
            DeltaY = 0.0f;
            DeltaZ = 0.0f;

            // Initialize mouse coordinates
            X = window.Width / 2f;
            Y = window.Height / 2f;

            // Initialize mouse state
            State = Mouse.GetState ();

            // Initialize mouse client rectangle
            MouseClientRect = new Rectangle (State.X, State.Y, 1, 1);

            // Set mouse centered state
            ShouldCenterMouse = shouldCenterMouse;

            // Set mouse visible state
            CursorVisible = mouseVisible;

            // Center the mouse
            CenterMouse ();
        }
Exemple #5
0
        public unsafe EditorWindow()
        {
            int desiredWidth = 960, desiredHeight = 540;

            _nativeWindow = new OpenTK.NativeWindow(desiredWidth, desiredHeight, "ImGui.NET", GameWindowFlags.Default, OpenTK.Graphics.GraphicsMode.Default, DisplayDevice.Default);
            _scaleFactor  = _nativeWindow.Width / desiredWidth;

            GraphicsContextFlags flags = GraphicsContextFlags.Default;

            _graphicsContext = new GraphicsContext(GraphicsMode.Default, _nativeWindow.WindowInfo, 3, 0, flags);
            _graphicsContext.MakeCurrent(_nativeWindow.WindowInfo);
            _graphicsContext.LoadAll(); // wtf is this?
            GL.ClearColor(Color.Black);
            _nativeWindow.Visible = true;
            _nativeWindow.X       = _nativeWindow.X; // Work around OpenTK bug (?) on Ubuntu.
            ImGui.GetIO().FontAtlas.AddDefaultFont();
            SetOpenTkKeyMappings();

            _textInputBufferLength = 1024;
            _textInputBuffer       = Marshal.AllocHGlobal(_textInputBufferLength);
            long *ptr = (long *)_textInputBuffer.ToPointer();

            for (int i = 0; i < 1024 / sizeof(long); i++)
            {
                ptr[i] = 0;
            }
            ce = new CodeEditor(_nativeWindow);

            CreateDeviceObjects();
        }
Exemple #6
0
        public Window(int width, int height, string title, WindowType type, int display, bool visible)
        {
            NativeWindow = new NativeWindow(width, height, title, GameWindowFlags.Default, GraphicsMode.Default, DisplayDevice.GetDisplay((DisplayIndex)display));
            NativeWindow.Closing += WindowClosing;
            NativeWindow.Resize += WindowResize;

            Keyboard = new Keyboard(this);
            Mouse = new Mouse(this);

            Type = type;
            Visible = visible;
        }
        static void Main(string[] args)
        {
            Application.SetCompatibleTextRenderingDefault(false);

            EditorWindow w;

            try
            {
                long offset = 0;

                var launcherDir = Environment.CurrentDirectory;
                if (args.Length > 0)
                {
                    launcherDir = "";
                    var i = 0;
                    foreach (string argument in args.ToList <string>())
                    {
                        i++;
                        if (i == 1)
                        {
                            launcherDir = argument;
                        }
                        else
                        {
                            launcherDir += " " + argument;
                        }
                    }
                }

                w = new EditorWindow(offset, launcherDir);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            MODLOADER();

            using (w)
            {
                w.Run();
            }

            INativeWindow window = new OpenTK.NativeWindow(1080, 600, "Timings Setup", GameWindowFlags.Default, new GraphicsMode(32, 8, 0, 8), DisplayDevice.Default);
        }
Exemple #8
0
        public unsafe SampleWindow()
        {
            int desiredWidth = 960, desiredHeight = 540;

            _nativeWindow = new OpenTK.NativeWindow(desiredWidth, desiredHeight, "ImGui.NET", GameWindowFlags.Default, OpenTK.Graphics.GraphicsMode.Default, DisplayDevice.Default);
            _scaleFactor  = _nativeWindow.Width / desiredWidth;

            GraphicsContextFlags flags = GraphicsContextFlags.Default;

            _graphicsContext = new GraphicsContext(GraphicsMode.Default, _nativeWindow.WindowInfo, 3, 0, flags);
            _graphicsContext.MakeCurrent(_nativeWindow.WindowInfo);
            ((IGraphicsContextInternal)_graphicsContext).LoadAll(); // wtf is this?
            GL.ClearColor(Color.Black);
            _nativeWindow.Visible = true;
            _nativeWindow.X       = _nativeWindow.X; // Work around OpenTK bug (?) on Ubuntu.

            _nativeWindow.KeyDown  += OnKeyDown;
            _nativeWindow.KeyUp    += OnKeyUp;
            _nativeWindow.KeyPress += OnKeyPress;

            ImGui.GetIO().FontAtlas.AddDefaultFont();

            SetOpenTKKeyMappings();

            _textInputBufferLength = 1024;
            _textInputBuffer       = Marshal.AllocHGlobal(_textInputBufferLength);
            long *ptr = (long *)_textInputBuffer.ToPointer();

            for (int i = 0; i < 1024 / sizeof(long); i++)
            {
                ptr[i] = 0;
            }

            _memoryEditorData = new byte[1024];
            var rnd = new Random();

            for (int i = 0; i < _memoryEditorData.Length; i++)
            {
                _memoryEditorData[i] = (byte)rnd.Next(255);
            }

            CreateDeviceObjects();
        }
        // Creates a context and starts processing the GL class.
        // The processing takes place in the background to avoid hanging the GUI.
        void StartAsync(object sender, EventArgs e)
        {
            Application.Idle -= StartAsync;

            // Create a context to load all GL entry points.
            // The loading part is handled automatically by OpenTK.
            using (INativeWindow window = new OpenTK.NativeWindow())
                using (IGraphicsContext context = new GraphicsContext(GraphicsMode.Default, window.WindowInfo, 3, 0, GraphicsContextFlags.Default))
                {
                    window.ProcessEvents();
                    context.MakeCurrent(window.WindowInfo);
                    (context as IGraphicsContextInternal).LoadAll();

                    TextBoxVendor.Text   = GL.GetString(StringName.Vendor);
                    TextBoxRenderer.Text = GL.GetString(StringName.Renderer);
                    TextBoxVersion.Text  = GL.GetString(StringName.Version);
                }

            backgroundWorker1.RunWorkerAsync();
            TextBoxSupport.Text = "processing... (please be patient)";
        }
Exemple #10
0
        public unsafe EditorWindow()
        {
            int desiredWidth = 960, desiredHeight = 540;

            _nativeWindow = new OpenTK.NativeWindow(desiredWidth, desiredHeight, "BadgerEdit", GameWindowFlags.Default, OpenTK.Graphics.GraphicsMode.Default, DisplayDevice.Default);
            _scaleFactor  = _nativeWindow.Width / desiredWidth;

            GraphicsContextFlags flags = GraphicsContextFlags.Default;

            _graphicsContext = new GraphicsContext(GraphicsMode.Default, _nativeWindow.WindowInfo, 3, 0, flags);
            _graphicsContext.MakeCurrent(_nativeWindow.WindowInfo);
            _graphicsContext.LoadAll();
            GL.ClearColor(Color.Black);
            _nativeWindow.Visible = true;
            _nativeWindow.X       = _nativeWindow.X; // Work around OpenTK bug (?) on Ubuntu.

            //SquaredDisplay looks nice but is really flimsy
            //ImGui.GetIO().FontAtlas.AddFontFromFileTTF("fonts/SquaredDisplay.ttf", 13);
            ImGui.GetIO().FontAtlas.AddDefaultFont();

            SetOpenTKKeyMappings();

            _textInputBufferLength = 1024;
            _textInputBuffer       = Marshal.AllocHGlobal(_textInputBufferLength);
            long *ptr = (long *)_textInputBuffer.ToPointer();

            for (int i = 0; i < 1024 / sizeof(long); i++)
            {
                ptr[i] = 0;
            }
            editor = new Editor();

            Renderer = new EditorRenderer(_nativeWindow, editor);

            _nativeWindow.KeyPress += NativeWindowOnKeyPress;
            _nativeWindow.KeyDown  += NativeWindowOnKeyDown;
            _nativeWindow.KeyUp    += NativeWindowOnKeyUp;
            CreateDeviceObjects();
        }
        public unsafe SimpleGLWindow(string title, int desiredWidth, int desiredHeight)
        {
            _nativeWindow = new NativeWindow(desiredWidth, desiredHeight, title, GameWindowFlags.Default, GraphicsMode.Default, DisplayDevice.Default);
            _scaleFactor = NativeWindow.Width / desiredWidth;

            GraphicsContextFlags flags = GraphicsContextFlags.Default;
            _graphicsContext = new GraphicsContext(GraphicsMode.Default, NativeWindow.WindowInfo, 3, 0, flags);
            _graphicsContext.MakeCurrent(NativeWindow.WindowInfo);
            ((IGraphicsContextInternal)_graphicsContext).LoadAll(); // wtf is this?
            GL.ClearColor(Color.Black);

            NativeWindow.Closing += OnWindowClosing;

            NativeWindow.KeyDown += OnKeyDown;
            NativeWindow.KeyUp += OnKeyUp;
            NativeWindow.KeyPress += OnKeyPress;

            ImGui.LoadDefaultFont();

            SetOpenTKKeyMappings();

            CreateDeviceObjects();
        }
        public static void Main()
        {
            using (var window = new NativeWindow())
            {
                Trace.WriteLine(String.Format("Window bounds: {0}", window.Bounds));
                Trace.WriteLine(String.Format("Window client: {0}", window.ClientRectangle));

                Point pclient = new Point(100, 100);
                Point pscreen = window.PointToScreen(pclient);
                Point ptest = window.PointToClient(pscreen);
                Trace.WriteLine(String.Format("Client: {0} -> Screen: {1} -> Client: {2}",
                    pclient, pscreen, ptest));
                Trace.WriteLine(String.Format("Test {0}",
                    ptest == pclient ? "succeeded" : "failed"));

                pscreen = new Point(100, 100);
                pclient = window.PointToClient(pscreen);
                ptest = window.PointToScreen(pclient);
                Trace.WriteLine(String.Format("Screen: {0} -> Client: {1} -> Screen: {2}",
                    pscreen, pclient, ptest));
                Trace.WriteLine(String.Format("Test {0}",
                    ptest == pscreen ? "succeeded" : "failed"));
            }
        }
Exemple #13
0
		protected override void dispose( bool disposeManagedResources )
		{
			if ( !IsDisposed )
			{
				if ( disposeManagedResources )
				{
					if ( glContext != null ) // Do We Not Have A Rendering Context?
					{
						glContext.SetCurrent();
						glContext.Dispose();
						glContext = null;
					}

					if ( _window != null )
					{
						if ( fullScreen )
							displayDevice.RestoreResolution();

						_window.Close();
						_window = null;
					}
				}

				// There are no unmanaged resources to release, but
				// if we add them, they need to be released here.
			}
			// If it is available, make the call to the
			// base class's Dispose(Boolean) method
			base.dispose( disposeManagedResources );
		}
Exemple #14
0
		/// <summary>
		///		Creates &amp; displays the new window.
		/// </summary>
		/// <param name="name"></param>
		/// <param name="width">The width of the window in pixels.</param>
		/// <param name="height">The height of the window in pixels.</param>
		/// <param name="fullScreen">If true, the window fills the screen, with no title bar or border.</param>
		/// <param name="miscParams">A variable number of platform-specific arguments.
		/// The actual requirements must be defined by the implementing subclasses.</param>
		public override void Create( string name, int width, int height, bool fullScreen, NamedParameterList miscParams )
		{
			string title = name;
			bool vsync = false;
			int depthBuffer = GraphicsMode.Default.Depth;
			float displayFrequency = 60f;
			string border = "resizable";

			this.name = name;
			this.width = width;
			this.height = height;
			this.colorDepth = 32;
			this.fullScreen = fullScreen;
			displayDevice = DisplayDevice.Default;

			#region Parameter Handling

			if ( miscParams != null )
			{
				foreach ( KeyValuePair<string, object> entry in miscParams )
				{
					switch ( entry.Key )
					{
						case "title":
							title = entry.Value.ToString();
							break;
						case "left":
							left = Int32.Parse( entry.Value.ToString() );
							break;
						case "top":
							top = Int32.Parse( entry.Value.ToString() );
							break;
						case "fsaa":
							fsaa = Int32.Parse( entry.Value.ToString() );
							break;
						case "colourDepth":
						case "colorDepth":
							colorDepth = Int32.Parse( entry.Value.ToString() );
							break;
						case "vsync":
							vsync = entry.Value.ToString() == "No" ? false : true;
							break;
						case "displayFrequency":
							displayFrequency = Int32.Parse( entry.Value.ToString() );
							break;
						case "depthBuffer":
							depthBuffer = Int32.Parse( entry.Value.ToString() );
							break;
						case "border":
							border = entry.Value.ToString().ToLower();
							break;

						case "externalWindowInfo":
							glContext = new OpenTKGLContext( (OpenTK.Platform.IWindowInfo)entry.Value );
							break;

						case "externalWindowHandle":
							object handle = entry.Value;
							IntPtr ptr = IntPtr.Zero;
							if ( handle.GetType() == typeof( IntPtr ) )
							{
								ptr = (IntPtr)handle;
							}
							else if ( handle.GetType() == typeof( System.Int32 ) )
							{
								ptr = new IntPtr( (int)handle );
							}
							//glContext = new OpenTKGLContext(Control.FromHandle(ptr), Control.FromHandle(ptr).Parent);

							WindowEventMonitor.Instance.RegisterWindow( this );
							fullScreen = false;
							IsActive = true;
							break;

						case "externalWindow":
							//glContext = new OpenTKGLContext((Control)entry.Value, ((Control)entry.Value).Parent);
							WindowEventMonitor.Instance.RegisterWindow( this );
							fullScreen = false;
							IsActive = true;
							break;

						default:
							break;
					}
				}
			}

			#endregion Parameter Handling

			if ( glContext == null )
			{
				// create window
				_window = new NativeWindow( width, height, title, GameWindowFlags.Default, new GraphicsMode( GraphicsMode.Default.ColorFormat, depthBuffer, GraphicsMode.Default.Stencil, FSAA ), displayDevice );
				glContext = new OpenTKGLContext( _window.WindowInfo );

				FileSystem.FileInfoList ico = ResourceGroupManager.Instance.FindResourceFileInfo( ResourceGroupManager.DefaultResourceGroupName, "AxiomIcon.ico" );
				if ( ico.Count != 0 )
				{
					_window.Icon = System.Drawing.Icon.ExtractAssociatedIcon( ico[ 0 ].Filename );
				}

				if ( fullScreen )
				{
					displayDevice.ChangeResolution( width, height, ColorDepth, displayFrequency );
					_window.WindowState = WindowState.Fullscreen;
					IsFullScreen = true;
				}
				else
				{
					_window.WindowState = WindowState.Normal;

					if ( border == "fixed" )
						_window.WindowBorder = WindowBorder.Fixed;
					else if ( border == "resizable" )
						_window.WindowBorder = WindowBorder.Resizable;
					else if ( border == "none" )
						_window.WindowBorder = WindowBorder.Hidden;
				}

				_window.Title = title;

				WindowEventMonitor.Instance.RegisterWindow( this );

				// lets get active!
				IsActive = true;
				glContext.VSync = vsync;
				_window.Visible = true;
			}
		}
Exemple #15
0
        /// <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.CultureName);

                    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();
            }
        }
        public void Run()
        {
            Window = new NativeWindow( 480, 480, Program.AppName, 0,
                                      GraphicsMode.Default, DisplayDevice.Default );
            Window.Visible = true;
            Drawer = new GdiPlusDrawer2D( null );
            Init();
            platformDrawer.Init( Window.WindowInfo );

            if( !ResourceFetcher.CheckAllResourcesExist() ) {
                SetScreen( new ResourcesScreen( this ) );
            } else {
                SetScreen( new MainScreen( this ) );
            }

            while( true ) {
                Window.ProcessEvents();
                if( !Window.Exists ) break;

                screen.Tick();
                if( Dirty || screen.Dirty )
                    Display();
                Thread.Sleep( 1 );
            }
        }
        public void Run()
        {
            Window = new NativeWindow( 640, 400, Program.AppName, 0,
                                      GraphicsMode.Default, DisplayDevice.Default );
            Window.Visible = true;
            Drawer = new GdiPlusDrawer2D( null );
            Init();
            TryLoadTexturePack();
            platformDrawer.Init( Window.WindowInfo );

            string audioPath = Path.Combine( Program.AppDirectory, "audio" );
            BinUnpacker.Unpack( audioPath, "dig" );
            BinUnpacker.Unpack( audioPath, "step" );

            fetcher = new ResourceFetcher();
            fetcher.CheckResourceExistence();
            checkTask = new UpdateCheckTask();
            checkTask.CheckForUpdatesAsync();
            if( !fetcher.AllResourcesExist )
                SetScreen( new ResourcesScreen( this ) );
            else
                SetScreen( new MainScreen( this ) );

            while( true ) {
                Window.ProcessEvents();
                if( !Window.Exists ) break;
                if( ShouldExit ) {
                    if( Screen != null )
                        Screen.Dispose();
                    break;
                }

                Screen.Tick();
                if( Dirty || Screen.Dirty )
                    Display();
                Thread.Sleep( 1 );
            }

            if( Options.Load() ) {
                LauncherSkin.SaveToOptions();
                Options.Save();
            }

            if( ShouldUpdate )
                Updater.Patcher.LaunchUpdateScript();
            if( Window.Exists )
                Window.Close();
        }
Exemple #18
0
        void TextureThread()
        {
            try
            {
                OpenTK.INativeWindow newwindow = new OpenTK.NativeWindow();
                OpenTK.INativeWindow window = newwindow;

                OpenTK.Graphics.IGraphicsContext newcontext = new OpenTK.Graphics.GraphicsContext(GLMode, window.WindowInfo);
                OpenTK.Graphics.IGraphicsContext context = newcontext;
                context.MakeCurrent(window.WindowInfo);

                TextureThreadContextReady.Set();
                PendingTextures.Open();

                Logger.DebugLog("Started Texture Thread");

                while (window.Exists && TextureThreadRunning)
                {
                    window.ProcessEvents();

                    TextureLoadItem item = null;

                    if (!PendingTextures.Dequeue(Timeout.Infinite, ref item)) continue;

                    if (LoadTexture(item.TeFace.TextureID, ref item.Data.Texture, false))
                    {
                        OpenTK.Graphics.OpenGL.GL.GenTextures(1, out item.Data.TexturePointer);
                        OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, item.Data.TexturePointer);

                        Bitmap bitmap = new Bitmap(item.Data.Texture);

                        bool hasAlpha;

                        if (item.Data.Texture.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
                        {
                            hasAlpha = true;
                        }
                        else
                        {
                            hasAlpha = false;
                        }

                        item.Data.IsAlpha = hasAlpha;

                        bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
                        Rectangle rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);


                        BitmapData bitmapData =
                            bitmap.LockBits(
                            rectangle,
                            ImageLockMode.ReadOnly,
                            hasAlpha ? System.Drawing.Imaging.PixelFormat.Format32bppArgb : System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                        OpenTK.Graphics.OpenGL.GL.TexImage2D(
                            OpenTK.Graphics.OpenGL.TextureTarget.Texture2D,
                            0,
                            hasAlpha ? OpenTK.Graphics.OpenGL.PixelInternalFormat.Rgba : OpenTK.Graphics.OpenGL.PixelInternalFormat.Rgb8,
                            bitmap.Width,
                            bitmap.Height,
                            0,
                            hasAlpha ? OpenTK.Graphics.OpenGL.PixelFormat.Bgra : OpenTK.Graphics.OpenGL.PixelFormat.Bgr,
                            OpenTK.Graphics.OpenGL.PixelType.UnsignedByte,
                            bitmapData.Scan0);

                        //// Auto detect if mipmaps are supported
                        //int[] MipMapCount = new int[1];
                        //OpenTK.Graphics.OpenGL.GL.GetTexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.GetTextureParameter.TextureMaxLevel, out MipMapCount[0]);

                        //OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMagFilter, (int)OpenTK.Graphics.OpenGL.TextureMagFilter.Linear);

                        //if (MipMapCount[0] == 0) // if no MipMaps are present, use linear Filter
                        //{
                        //    OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear);
                        //}
                        //else
                        //{
                        //    OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, (int)OpenTK.Graphics.OpenGL.TextureMinFilter.LinearMipmapLinear);
                        //    OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapS, (int)OpenTK.Graphics.OpenGL.TextureWrapMode.Repeat);
                        //    OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapT, (int)OpenTK.Graphics.OpenGL.TextureWrapMode.Repeat);
                        //    OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.GenerateMipmap, 1);
                        //    OpenTK.Graphics.OpenGL.GL.GenerateMipmap(OpenTK.Graphics.OpenGL.GenerateMipmapTarget.Texture2D);
                        //}

                        //if (!enablemipmapd)

                        if (instance.Config.CurrentConfig.DisableMipmaps)
                        {
                            OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear);
                        }
                        else
                        {
                            if (MipmapsSupported)
                            {
                                try
                                {
                                    OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, (int)OpenTK.Graphics.OpenGL.TextureMinFilter.LinearMipmapLinear);
                                    OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapS, (int)OpenTK.Graphics.OpenGL.TextureWrapMode.Repeat);
                                    OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapT, (int)OpenTK.Graphics.OpenGL.TextureWrapMode.Repeat);
                                    OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.GenerateMipmap, 1);
                                    OpenTK.Graphics.OpenGL.GL.GenerateMipmap(OpenTK.Graphics.OpenGL.GenerateMipmapTarget.Texture2D);
                                }
                                catch
                                {
                                    OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear);

                                    if (!msgdisplayed)
                                    {
                                        //Logger.Log("META3D TextureThread: Your video card does not support Mipmap. Try disabling Mipmaps from META3D tab under the Application/Preferences menu", Helpers.LogLevel.Warning);
                                        MessageBox.Show("Your video card does not support Mipmaps.\nDisable Mipmaps from the META3D tab under\nthe Application/Preferences menu");
                                        msgdisplayed = true;
                                    }
                                }
                            }
                            else
                            {
                                OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear);

                                if (!msgdisplayed)
                                {
                                    MessageBox.Show("Your video card does not support Mipmaps.\nDisable Mipmaps from the META3D tab under\nthe Application/Preferences menu");
                                    msgdisplayed = true;
                                }
                            }
                        }

                        bitmap.UnlockBits(bitmapData);
                        bitmap.Dispose();

                        OpenTK.Graphics.OpenGL.GL.Flush();

                        GLInvalidate();
                    }
                }

                newcontext.Dispose();
                newwindow.Dispose();

                //Logger.DebugLog("Texture thread exited");
            }
            catch (Exception ex)
            {
                Logger.Log("META3D TextureThread: " + ex.Message, Helpers.LogLevel.Warning);
            }
        }
 static FinalizerThreadContextGL3x()
 {
     _window = new NativeWindow();
     _context = new GraphicsContext(new GraphicsMode(32, 24, 8), _window.WindowInfo, 3, 2, GraphicsContextFlags.ForwardCompatible | GraphicsContextFlags.Debug);
 }
Exemple #20
0
		public ToeGraphicsContext(IResourceManager resourceManager)
		{
			this.resourceManager = resourceManager;
			this.debugMaterial = new Material(this.resourceManager)
				{ ColEmissive = Color.FromArgb(255, 255, 255, 255), SpecularPower = 0 };
			GraphicsContext.ShareContexts = true;
			var currentContext = GraphicsContext.CurrentContext;
			if (currentContext != null)
			{
				currentContext.MakeCurrent(null);
			}
			//EventWaitHandle context_ready = new EventWaitHandle(false, EventResetMode.AutoReset);

			//this.resourceContextThread = new Thread(
			//	() =>
			//		{
			this.window = new NativeWindow();
			GraphicsContext.ShareContexts = true;
			this.context = new GraphicsContext(GraphicsMode.Default, this.window.WindowInfo);
			this.context.MakeCurrent(this.window.WindowInfo);

			this.window.ProcessEvents();
			//context_ready.Set();
			//while (this.window.Exists)
			//{
			//    this.window.ProcessEvents();

			//    // Perform your processing here

			//    Thread.Sleep(1); // Limit CPU usage, if necessary
			//}
			//});
			//this.resourceContextThread.IsBackground = true;
			//this.resourceContextThread.Start();

			//context_ready.WaitOne();
		}
Exemple #21
0
        private void Init(int x, int y, int width, int height, String title, GameWindowFlags options, GraphicsMode mode, DisplayDevice display)
        {
            // window thread
            m_window = new NativeWindow(x, y, width, height, title, options, mode, display);
            m_renderables = new List<IRenderable>();
            m_components = new List<IGameComponent>();
            m_context = new GraphicsContext(mode, m_window.WindowInfo);

            m_window.Closing += window_Exiting;
            m_window.WindowStateChanged += window_WindowStateChanged;
            SetupWindow();
            m_window.Visible = true;
        }
Exemple #22
0
        /// <summary>
        /// Initializes the game internally.
        /// </summary>
        void InternalInitialize()
        {
            // Initialize graphics mode to default
            graphicsMode = GraphicsMode.Default;

            // Start with default window flags
            var flags = GameWindowFlags.Default;

            // Set Fullscreen flag if requested
            if (Configuration.Fullscreen && !flags.HasFlag (GameWindowFlags.Fullscreen))
                flags |= GameWindowFlags.Fullscreen;

            // Set FixedWindow flag if requested
            if (Configuration.FixedWindow && !flags.HasFlag (GameWindowFlags.FixedWindow))
                flags |= GameWindowFlags.FixedWindow;

            // Create window
            this.Log ("Creating native window");
            window = new NativeWindow (
                width: Configuration.Width,
                height: Configuration.Height,
                title: Configuration.WindowTitle,
                options: flags,
                mode: GraphicsMode.Default,
                device: DisplayDevice.Default
            );

            // Update the resolution
            UpdateResolution ();

            // Register events
            window.KeyDown += Keyboard.RegisterKeyDown;
            window.KeyUp += Keyboard.RegisterKeyUp;
            window.KeyPress += delegate { };

            // Initialize startTime and lastTime
            startTime = DateTime.UtcNow;
            lastTime = startTime;

            // Initialize the mouse buffer
            Mouse = new MouseBuffer (window, this);

            // Start the sound manager
            SoundManager = new SoundManager();

            // Initialize the context manager
            Content = new ContentManager (AppDomain.CurrentDomain.BaseDirectory);
            Content.ContentRoot = this.Configuration.ContentRoot;
            ContentManager = Content;
            RegisterProviders ();

            Instance = this;
        }
        private void StartJobThread()
        {
            Context.MakeCurrent(null);
            var contextReady = new AutoResetEvent(false);
            var thread = new Thread(() =>
            {
                var window = new NativeWindow();
                var context = new GraphicsContext(Context.GraphicsMode, window.WindowInfo);
                context.MakeCurrent(window.WindowInfo);
                contextReady.Set();

                while (true)
                {
                    var action = JobDispatcher.Instance.Dequeue();
                    action();
                }
            });

            thread.IsBackground = true;
            thread.Start();
            contextReady.WaitOne();
            MakeCurrent();
        }
Exemple #24
0
        public WaitHandle GenerateOccluder(Action <VoxelizationProgress> progress, Action done)
        {
            ManualResetEvent waitHandle = new ManualResetEvent(false);

            if (Context == null || Context.OriginalMesh == null)
            {
                Logger.DisplayError("Please Open a mesh first.");
                waitHandle.Set();
                return(waitHandle);
            }

            Input.Octree       = Context.Octree;
            Input.OriginalMesh = Context.OriginalMesh;

            VoxelizationInput  input  = Input.Clone();
            VoxelizationOutput output = null;

            IOccluderGenerator occluder;

            switch (input.Type)
            {
            case OcclusionType.Octree:
                occluder = new OccluderOctree();
                break;

            case OcclusionType.BoxExpansion:
                occluder = new OccluderBoxExpansion();
                break;

            //case OcclusionType.SimulatedAnnealing:
            //    occluder = new OccluderBoxExpansion();
            //    break;
            case OcclusionType.BruteForce:
                occluder = new OccluderBoxExpansion();
                break;

            default:
                throw new Exception("Unknown occluder type.");
            }

            Thread thread = new Thread(() =>
            {
                INativeWindow window = new OpenTK.NativeWindow();
                IGraphicsContext gl  = new GraphicsContext(new GraphicsMode(32, 24, 8), window.WindowInfo);
                gl.MakeCurrent(window.WindowInfo);

                while (window.Exists)
                {
                    window.ProcessEvents();

                    try
                    {
                        RobustVoxelizer voxelizer = new RobustVoxelizer(512, 512);
                        output = voxelizer.Voxelize(input, progress);
                        voxelizer.Dispose();

                        output = occluder.Generate(input, progress);
                    }
                    catch (System.Exception ex)
                    {
                        Debug.WriteLine(ex.ToString());
                    }

                    window.Close();
                    break;
                }

                gl.MakeCurrent(null);

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

                Context.Octree             = output.Octree;
                Context.OccluderMesh       = output.OccluderMesh;
                Context.VoxelizationOutput = output;

                waitHandle.Set();

                done();
            });

            thread.IsBackground = true;
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

            return(waitHandle);
        }