Example #1
0
	public Sprite2DBatch( GraphicsContext graphics, int maxSpriteCount )
	{
		int maxVertexCount = maxSpriteCount * 4 ;
		int maxIndexCount = maxSpriteCount * 6 ;

		graphicsContext = graphics ;
		#if !RESIZE_VERTEX_BUFFER
		vertexBuffer = new VertexBuffer( maxVertexCount, maxIndexCount, vertexFormats ) ;
		spriteCapacity = maxSpriteCount ;
		#endif // RESIZE_VERTEX_BUFFER
		vertexData = new Vertex[ maxVertexCount ] ;
		indexData = new ushort[ maxIndexCount ] ;

		spriteList = new Sprite2D[ maxSpriteCount ] ;
		sortedList = new Sprite2D[ maxSpriteCount ] ;
			
		#if ENABLE_SIN_TABLE
		if ( sinTable == null ) {
			sinTable = new float[ 4096 ] ;
			for ( int i = 0 ; i < 4096 ; i ++ ) {
				sinTable[ i ] = FMath.Sin( i * ( FMath.PI / 2048.0f ) ) ;
			}
		}
		#endif // ENABLE_SIN_TABLE
	}
Example #2
0
        public CoordinateMarkerRenderer(GraphicsContext graphicsContext)
        {
            _vertexRenderer = graphicsContext.CreateVertexRenderer<TexturedColouredVertex4>(6);
            _noTexture = graphicsContext.GetTexture("noTexture.png");

            PopululateBuffer();
        }
        static void Main(string[] args)
        {
            graphics = new GraphicsContext(960,544,PixelFormat.Rgba,PixelFormat.Depth16,MultiSampleMode.None);
            UISystem.Initialize(graphics);

            MainScene scene = new MainScene();
            SetupListNum(scene.RootWidget);
            scene.SetWidgetLayout(LayoutOrientation.Horizontal);
            UISystem.SetScene(scene);
            for (; ; )
            {
                SystemEvents.CheckEvents();

                // update
                {
                    List<TouchData> touchDataList = Touch.GetData(0);
                    var gamePad = GamePad.GetData (0);
                    UISystem.Update(touchDataList, ref gamePad);
                }

                // draw
                {
                    graphics.SetViewport(0, 0, graphics.Screen.Width, graphics.Screen.Height);
                    graphics.SetClearColor(
                        0xFF,
                        0xFF,
                        0xFF,
                        0xff);
                    graphics.Clear();

                    UISystem.Render();
                    graphics.SwapBuffers();
                }
            }
        }
Example #4
0
        public DrawEngine2d(GraphicsContext graphicsContext)
        {
            if (graphicsContext == null)
                throw new ArgumentNullException();

            Initialize(graphicsContext);
        }
Example #5
0
        public Sprite(GraphicsContext graphics, Texture2D texture)
        {
            if(shaderProgram == null)
            {
                shaderProgram = new ShaderProgram("/Application/shaders/Sprite.cgx");
                shaderProgram.SetUniformBinding(0, "u_WorldMatrix");
            }

            if (texture == null)
            {
                throw new Exception("ERROR: texture is null.");
            }

            this.graphics = graphics;
            this.texture = texture;
            this.width = texture.Width;
            this.height = texture.Height;

            indices = new ushort[indexSize];
            indices[0] = 0;
            indices[1] = 1;
            indices[2] = 2;
            indices[3] = 3;

            vertexBuffer = new VertexBuffer(4, indexSize, VertexFormat.Float3,
                                            VertexFormat.Float2, VertexFormat.Float4);
        }
Example #6
0
 public ModelInstanceRenderer(
     GraphicsContext graphicsContext)
 {
     _graphicsContext = graphicsContext;
     _vertexRenderers = new Dictionary<int, IVertexRenderer<TexturedColouredVertex4>>();
     _lastTextureName = null;
 }
Example #7
0
        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();
        }
Example #8
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Closing += Form1_Closing;

            WindowInfo = Utilities.CreateWindowsWindowInfo(panel1.Handle);
            var WindowMode = new GraphicsMode(32, 24, 0, 0, 0, 2);
            WindowContext = new GraphicsContext(WindowMode, WindowInfo, 2, 0, GraphicsContextFlags.Debug);

            WindowContext.MakeCurrent(WindowInfo);
            WindowContext.LoadAll(); // as IGraphicsContextInternal)

            WindowContext.SwapInterval = 1;
            GL.Viewport(0, 0, panel1.Width, panel1.Height);

            GL.Enable(EnableCap.DepthTest);
            GL.Disable(EnableCap.CullFace);
            GL.ClearColor(Color.DarkBlue);

            try
            {
                state.LoadCLRPackage();
                state.DoString(@" import ('LUA', 'LUA') ");
            }
            catch (LuaException ex)
            {
                MessageBox.Show(ex.Message, "LUA Package Exception", MessageBoxButtons.OK);
            }

            state["x"] = 0.0;
            state["y"] = 1.0;
            state["fn"] = 0;
            script = textBox1.Text;

            timer1.Enabled = true;
        }
Example #9
0
 public Saucer(GraphicsContext g, Texture2D t, Vector3 p, Player pl)
     : base(g,t,p, pl)
 {
     player = pl;
     vel= (new Vector3(.5f*(float)gen.Next(3,5),.7f*(float)gen.Next(3,5),0));
     graphics=g;
 }
Example #10
0
        public CanvasBrush(GraphicsContext graphics)
        {
            if (graphics == null)
                throw new ArgumentNullException("graphics");

            this.Grahpics = graphics;
        }
        public GraphicsContextEventArgs(GraphicsContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            this.Graphics = context;
        }
Example #12
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="graphics"></param>
        /// <param name="maxSprites">The maximum number of sprites which can be batched.</param>
        public SpriteRenderer(GraphicsContext graphics, int maxSprites)
        {
            if (graphics == null)
                throw new ArgumentNullException("graphics");

            if (maxSprites <= 0)
                throw new ArgumentOutOfRangeException("maxSprites", "MaxSprites must be >= 1.");

            this.graphics = graphics;

            this.vertices = new Vertex[maxSprites * 4];

            this.vertexBuffer = new DynamicVertexBuffer<Vertex>(this.graphics);

            ushort[] indices = new ushort[1024 * 6];
            for (ushort i = 0, vertex = 0; i < indices.Length; i += 6, vertex += 4)
            {
                indices[i] = vertex;
                indices[i + 1] = (ushort)(vertex + 1);
                indices[i + 2] = (ushort)(vertex + 3);
                indices[i + 3] = (ushort)(vertex + 1);
                indices[i + 4] = (ushort)(vertex + 2);
                indices[i + 5] = (ushort)(vertex + 3);
            }

            this.indexBuffer = new StaticIndexBuffer<ushort>(this.graphics, indices);

            this.transform = new Matrix4()
            {
                M33 = 1f,
                M44 = 1f,
                M41 = -1f,
                M42 = 1f
            };
        }
Example #13
0
 protected override void PaintVerticalBar(GraphicsContext context, SizeF size, SizeF knobSize)
 {
     var rect = new RectangleF (new PointF (), new SizeF (knobSize.Width, size.Height - knobSize.Height));
     var brush = new LinearGradientBrush (rect, Color.Black, Color.Black,
         LinearGradientMode.Vertical);
     DrawBar (context, brush, rect);
 }
Example #14
0
        /// <summary>コンストラクタ。</summary>
        public SimpleSprite(GraphicsContext graphics, Texture2D texture)
        {
            if(shaderProgram == null)
            {
                shaderProgram=CreateSimpleSpriteShader();
            }

            if (texture == null)
            {
                throw new Exception("ERROR: texture is null.");
            }

            this.graphics = graphics;
            this.texture = texture;
            this.width = texture.Width;
            this.height = texture.Height;

            indices = new ushort[indexSize];
            indices[0] = 0;
            indices[1] = 1;
            indices[2] = 2;
            indices[3] = 3;

            //@e                                                Vertex coordinate,               Texture coordinate,     Vertex color
            //@j                                                頂点座標,                テクスチャ座標,     頂点色
            vertexBuffer = new VertexBuffer(4, indexSize, VertexFormat.Float3, VertexFormat.Float2, VertexFormat.Float4);
        }
        /// フィルタ処理の実行
        public void Filter( GraphicsContext graphics )
        {
            texRenderer.BindGraphicsContext( graphics );
            FrameBuffer oldBuffer = graphics.GetFrameBuffer();

            bool isSwap = false;
            int width = oldBuffer.Width;
            int height = oldBuffer.Height;

            if( this.Target != null ){
            graphics.SetFrameBuffer( this.Target );
            width = this.Target.Width;
            height = this.Target.Height;
            isSwap = true;
            }
            graphics.SetViewport( 0, 0, width, height );

            texRenderer.Begin( shaderDOF );
            graphics.SetTexture( 2, texDepth );
            texRenderer.Render( texScene,
                            texBlur,
                            0, 0, 0, 0, width, height );
            texRenderer.End();
            if( isSwap ){
            graphics.SetFrameBuffer( oldBuffer );
            }
        }
Example #16
0
 public Collision(GraphicsContext g)
 {
     blist = new List<Bullet>();
     elist = new List<Enemy>();
     ilist = new List<Item>();
     graphics = g;
 }
 public void RenderAllEffects(GraphicsContext graphicsContext, ParticleEngine particleEngine)
 {
     for (int i = 0; i < particleEngine.ParticleEffects.Count; i++)
     {
         this.RenderEffect(graphicsContext, particleEngine.ParticleEffects[i]);
     }
 }
Example #18
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();
        }
Example #19
0
 public Star(GraphicsContext g, Texture2D t, Vector3 p, Player pl)
     : base(g,t,p)
 {
     graphics=g;
     player = pl;
     vel= (new Vector3(.5f*(float)gen.Next(1,5),.7f*(float)gen.Next(1,5),0));
 }
Example #20
0
        public PatternGrid(GraphicsContext graphics, Texture2D texture, Vector2 position, Vector2 size)
        {
            if(shaderProgram == null)
            {
                //shaderProgram=CreateSimpleSpriteShader();
                shaderProgram = new ShaderProgram("/Application/shaders/Sprite.cgx");
                shaderProgram.SetUniformBinding(0, "u_WorldMatrix");
            }

            //if (texture == null)
            //{
            //	throw new Exception("ERROR: texture is null.");
            //}

            this.graphics = graphics;
            //this.texture = texture;
            this.texture = new Texture2D("/Application/resources/textures512.png", false);
            this.width = size.X;
            this.height = size.Y;
            this.origin = position;

            //@e                                                Vertex coordinate,               Texture coordinate,     Vertex color
            //vertexBuffer = new VertexBuffer(4, indexSize, VertexFormat.Float3, VertexFormat.Float2, VertexFormat.Float4);
            vertexBuffer = new VertexBuffer(NUMVERTICES, VertexFormat.Float3, VertexFormat.Float2, VertexFormat.Float4);
        }
Example #21
0
        public static void Main(string[] args)
        {
            //Initialize ();

            GraphicsContext graphics = new GraphicsContext();
            UISystem.Initialize(graphics);

            window = new HighScoreApp.MainWindow();
            UISystem.SetScene(window);
            socket = new Sockets();

            while (true) {
                SystemEvents.CheckEvents();

                List<TouchData> touchData = Touch.GetData(0);
                UISystem.Update (touchData);

                Update ();

                graphics.SetViewport(0, 0, graphics.Screen.Width, graphics.Screen.Height);
                graphics.SetClearColor(new Vector4(0,0,0,1));
                graphics.SetClearDepth(1.0f);
                graphics.Clear();

                UISystem.Render ();
                graphics.SwapBuffers();
            }
        }
Example #22
0
 private void InitGL()
 {
     windowInfo = Utilities.CreateWindowsWindowInfo(window.Handle);
     context = new GraphicsContext(GraphicsMode.Default, windowInfo);
     context.MakeCurrent(windowInfo);
     context.LoadAll();
 }
Example #23
0
        public static void Initialize()
        {
            // Set up the graphics system
            graphics = new GraphicsContext ();

            // UI System Initialize
            UISystem.Initialize(graphics);

            // データロード
            FileIO.LoadData();

            // UIツールキット使用のシーン作成
            Scenes.InitUIScenes();

            // 音関係初期化
            Sounds.InitSound();

            Sounds.PlayTitle();
            UISystem.SetScene(Scenes.titleScene);

            // ディレクター初期化
            Sce.PlayStation.HighLevel.GameEngine2D.Director.Initialize(1000, 800, graphics);

            Scenes.InitGameEngine2dScene();

            Game.InitGame(graphics);

            Global.setSkill = SkillID.Default;
            Global.isInitGame = true;
            Global.isStartGame = false;
        }
Example #24
0
        public DebugString(GraphicsContext graphics, Texture2D texture, int charaWidth, int charaHeight)
        {
            if(shaderProgram == null)
            {
                shaderProgram=CreateSimpleSpriteShader();
            }

            this.graphics = graphics;

            this.texture = texture;

            this.charaWidth = charaWidth;
            this.charaHeight = charaHeight;

            charaPositions = new float[maxNumOfCharactor * 4 * 3];
            charaTexcoords = new float[maxNumOfCharactor * 4 * 2];
            charaColors = new float[maxNumOfCharactor * 4 * 4];
            charaIndices = new ushort[maxNumOfCharactor * indexSize];

            vertices = new VertexBuffer(maxNumOfCharactor * 4, maxNumOfCharactor * indexSize,
                VertexFormat.Float3, VertexFormat.Float2, VertexFormat.Float4);

            PixelScreenPosition = new Vector3(0.0f, 0.0f, 0.0f);

            ImageRect rectPixelScreen = graphics.GetViewport();

            //@j ピクセルの座標系をスクリーンの座標系に変換する行列。
            //@e Line to convert a pixel coordinate system into a screen coordinate system.
            unitScreenMatrix = new Matrix4(
                 2.0f/rectPixelScreen.Width,	0.0f,	0.0f, 0.0f,
                 0.0f, -2.0f/rectPixelScreen.Height,	0.0f, 0.0f,
                 0.0f,	0.0f, 1.0f, 0.0f,
                -1.0f, 1.0f, 0.0f, 1.0f
            );
        }
Example #25
0
 public static void InitGraphicsContext()
 {
     if (null != sm_GraphicsContext) {
     return;
     }
     sm_GraphicsContext = new GraphicsContext();
 }
Example #26
0
		public static void Initialize ()
		{
			// Set up the graphics system
			graphics = new GraphicsContext ();
#if BUILD_FOR_PSV
			program = new ShaderProgram("/Application/shaders/Texture.cgx");
#else
			program = new ShaderProgram("/Application/shaders/Texture_sim.cgx");
#endif
			program.SetUniformBinding(0, "WorldViewProj");
			program.SetAttributeBinding(0, "a_Position");
			program.SetAttributeBinding(1, "a_TexCoord");
			vertices = new VertexBuffer(4, VertexFormat.Float3, VertexFormat.Float2);

			float[] positions = {
				-1.0f, 1.0f, 0.0f,
				-1.0f, -1.0f, 0.0f,
				1.0f, 1.0f, 0.0f,
				1.0f, -1.0f, 0.0f,
			};
			float[] texcoords = {
				0.0f, 0.0f,
				0.0f, 1.0f,
				1.0f, 0.0f,
				1.0f, 1.0f,
			};
			vertices.SetVertices(0, positions);
			vertices.SetVertices(1, texcoords);
			texture = new Texture2D(256, 224, false, PixelFormat.Rgb565);
			
			SampleDraw.Init(graphics);
			
		}
Example #27
0
        public static void Initialize()
        {
            // Set up the graphics system
            graphics = new GraphicsContext ();
            // Set up background sprite
            ImageRect rectScreen = graphics.Screen.Rectangle;
            Console.WriteLine("Screen size: " + rectScreen.Width + " x " + rectScreen.Height);

            texture = new Texture2D("/Application/resources/bg.png", false);
            bgSprite = new Sprite(graphics, texture);
            bgSprite.Position.X = 0.0f; //rectScreen.Width/2.0f;
            bgSprite.Position.Y = 0.0f; //rectScreen.Height/2.0f;
            bgSprite.Position.Z = 0.0f;

            patternGrid = new PatternGrid(graphics, texture, new Vector2(240.0f, 144.0f), new Vector2(720.0f, 400.0f));
            patternGrid.Update(currentPattern);

            textWriter = new Text(graphics, 16.0f);

            m_song.Load("/Documents/songs/flowers1.xds");

            // Start playback thread
            //simStart = false;
            playbackThread = new Thread(new ThreadStart(playbackThreadMain));
            playbackThread.Start();
        }
Example #28
0
        public void Filter( GraphicsContext graphics )
        {
            // Y軸方向へのガウス
            // uniform
            int idReciprocalTexHeight = shaderGaussianY.FindUniform( "ReciprocalTexHeight" );
            if( idReciprocalTexHeight >= 0 ){
            shaderGaussianY.SetUniformValue( idReciprocalTexHeight, 1.0f / texScene.Height );
            }
            int idWeight = shaderGaussianY.FindUniform( "Weight" );
            if( idWeight >= 0 ){
            shaderGaussianY.SetUniformValue( idWeight, 0, gaussianWeightTable );
            }
            int idOffset = shaderGaussianY.FindUniform( "Offset" );
            if( idOffset >= 0 ){
            Vector2 offset = new Vector2( 0.0f, 16.0f / texScene.Height );
            shaderGaussianY.SetUniformValue( idOffset, ref offset );
            }

            // render
            FrameBuffer oldBuffer = graphics.GetFrameBuffer();

            if( this.Target != null ){
            graphics.SetFrameBuffer( this.Target );
            }

            texRenderer.BindGraphicsContext( graphics );
            texRenderer.Begin( shaderGaussianY );
            texRenderer.Render( texScene );
            texRenderer.End();

            if( this.Target != null ){
            graphics.SetFrameBuffer( oldBuffer );
            }
        }
        public static void Initialize()
        {
            // Set up the graphics system
            _graphics = new GraphicsContext ();

            _texture = new Texture2D("/Application/32.png", false);

            _spriteBatch = new MonoGameSpriteBatch(_graphics, 256);
            //_spriteBatch = new MonoGameSpriteBatchNoIndex(_graphics, 256);
            //_spriteBatch = new MonoGameSpriteBatchVector3(_graphics, 256);
            //_spriteBatch = new MonoGameSpriteBatchUnpacked(_graphics, 256);

            //_spriteBatch = new DoubleBufferedSpriteBatch(new MonoGameSpriteBatch(_graphics, 256), new MonoGameSpriteBatch(_graphics, 256));
            //_spriteBatch = new TripleBufferedSpriteBatch(new MonoGameSpriteBatch(_graphics, 256), new MonoGameSpriteBatch(_graphics, 256), new MonoGameSpriteBatch(_graphics, 256));

            //_spriteBatch = new DoubleBufferedSpriteBatch(
            //	new DoubleBufferedSpriteBatch(new MonoGameSpriteBatch(_graphics, 256), new MonoGameSpriteBatch(_graphics, 256)),
            //	new DoubleBufferedSpriteBatch(new MonoGameSpriteBatch(_graphics, 256), new MonoGameSpriteBatch(_graphics, 256)));

            //_spriteBatch = new TripleBufferedSpriteBatch(
            //	new TripleBufferedSpriteBatch(new MonoGameSpriteBatch(_graphics, 256), new MonoGameSpriteBatch(_graphics, 256), new MonoGameSpriteBatch(_graphics, 256)),
            //	new TripleBufferedSpriteBatch(new MonoGameSpriteBatch(_graphics, 256), new MonoGameSpriteBatch(_graphics, 256), new MonoGameSpriteBatch(_graphics, 256)),
            //	new TripleBufferedSpriteBatch(new MonoGameSpriteBatch(_graphics, 256), new MonoGameSpriteBatch(_graphics, 256), new MonoGameSpriteBatch(_graphics, 256)));

            //_spriteBatch2 = new MonoGameSpriteBatch(_graphics, 256);
        }
Example #30
0
 public Claw(GraphicsContext g, Texture2D t, Vector3 p)
     : base(g,t,p)
 {
     graphics = g;
     sprite.Position = p;
     vel= (new Vector3(0, -1, 0));
 }
 /// <inheritdoc/>
 protected override void OnPaint(GameTime time, GraphicsContext gfx)
 {
     gfx.DrawRectangle(0, 0, Width, Height, Theme.GetAccentColor() * _colorFade);
 }
Example #32
0
 /// <summary>
 /// Draw a number of instances of the attributes of this vertex array.
 /// </summary>
 /// <param name="ctx">
 /// The <see cref="GraphicsContext"/> used for rendering.
 /// </param>
 /// <param name="instances">
 /// A <see cref="UInt32"/> that specify the number of instances to draw.
 /// </param>
 public virtual void DrawInstanced(GraphicsContext ctx, uint instances)
 {
     DrawInstanced(ctx, null, instances);
 }
Example #33
0
 /// <summary>
 /// Draw all elements.
 /// </summary>
 /// <param name="ctx">
 /// The <see cref="GraphicsContext"/> used for rendering.
 /// </param>
 /// <param name="shader">
 /// The <see cref="ShaderProgram"/> used for drawing the vertex arrays.
 /// </param>
 public void Draw(GraphicsContext ctx, ShaderProgram shader)
 {
     Draw(ctx, shader, null);
 }
Example #34
0
        /// <summary>
        /// Set the vertex arrays state for the shader program.
        /// </summary>
        /// <param name="ctx">
        /// A <see cref="GraphicsContext"/> on which the shader program is bound.
        /// </param>
        /// <param name="shaderProgram">
        /// A <see cref="ShaderProgram"/> on which the vertex arrays shall be bound.
        /// </param>
        private void SetVertexArrayState(GraphicsContext ctx, ShaderProgram shaderProgram)
        {
            CheckThisExistence(ctx);

            // Set vertex array state all at once...
            ctx.Bind(this, true);

            if (shaderProgram != null)
            {
                ICollection <string> activeAttributes = shaderProgram.ActiveAttributes;
                uint attributesSet = 0;

                // Set vertex array state
                foreach (string attributeName in activeAttributes)
                {
                    IVertexArray shaderVertexArray = GetVertexArray(attributeName, shaderProgram);
                    if (shaderVertexArray == null)
                    {
                        continue;
                    }

                    ShaderProgram.AttributeBinding attributeBinding = shaderProgram.GetActiveAttribute(attributeName);

                    IVertexArray currentVertexArray = _VertexArrayState[attributeBinding.Location];
                    //if (ReferenceEquals(shaderVertexArray, currentVertexArray) == false) {
                    shaderVertexArray.SetVertexAttribute(ctx, attributeBinding, attributeName);
                    _VertexArrayState[attributeBinding.Location] = shaderVertexArray;
                    //}

                    attributesSet++;
                }

                if (attributesSet == 0)
                {
                    throw new InvalidOperationException("no attribute is set");
                }
            }
            else
            {
                IVertexArray attributeArray;

                // No shader program: using fixed pipeline program. ATM enable all attributes having a semantic
                if ((attributeArray = GetVertexArray(VertexArraySemantic.Position)) == null)
                {
                    throw new InvalidOperationException("no position semantic array defined");
                }
                attributeArray.SetVertexAttribute(ctx, null, VertexArraySemantic.Position);

                // Optional attributes
                if ((attributeArray = GetVertexArray(VertexArraySemantic.Color)) != null)
                {
                    attributeArray.SetVertexAttribute(ctx, null, VertexArraySemantic.Color);
                }
                if ((attributeArray = GetVertexArray(VertexArraySemantic.Normal)) != null)
                {
                    attributeArray.SetVertexAttribute(ctx, null, VertexArraySemantic.Normal);
                }
                if ((attributeArray = GetVertexArray(VertexArraySemantic.TexCoord)) != null)
                {
                    attributeArray.SetVertexAttribute(ctx, null, VertexArraySemantic.TexCoord);
                }
            }
        }
Example #35
0
        public void Render()
        {
            // First take exclusivity on the OpenGL context.
            GraphicsContext.MakeCurrent(WindowInfo);

            _renderer.Initialize();

            // Shader cache setup.
            string basePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Ryujinx");
            string workPath = System.IO.Path.Combine(basePath, "games", _device.System.TitleIdText, "cache", "gpu");

            _device.Gpu.SetShaderCachePath(workPath);
            _device.Gpu.LoadShaderCache();

            // Make sure the first frame is not transparent.
            GL.ClearColor(OpenTK.Color.Black);
            GL.Clear(ClearBufferMask.ColorBufferBit);
            SwapBuffers();

            while (IsActive)
            {
                if (IsStopped)
                {
                    return;
                }

                _ticks += _chrono.ElapsedTicks;

                _chrono.Restart();

                if (_device.WaitFifo())
                {
                    _device.ProcessFrame();
                }

                if (_ticks >= _ticksPerFrame)
                {
                    _device.PresentFrame(SwapBuffers);

                    _device.Statistics.RecordSystemFrameTime();

                    double hostFps = _device.Statistics.GetSystemFrameRate();
                    double gameFps = _device.Statistics.GetGameFrameRate();

                    string titleNameSection = string.IsNullOrWhiteSpace(_device.System.TitleName) ? string.Empty
                        : " | " + _device.System.TitleName;

                    string titleIdSection = string.IsNullOrWhiteSpace(_device.System.TitleIdText) ? string.Empty
                        : " | " + _device.System.TitleIdText.ToUpper();

                    _newTitle = $"Ryujinx {Program.Version}{titleNameSection}{titleIdSection} | Host FPS: {hostFps:0.0} | Game FPS: {gameFps:0.0} | " +
                                $"Game Vsync: {(_device.EnableDeviceVsync ? "On" : "Off")}";

                    _titleEvent = true;

                    _device.System.SignalVsync();

                    _device.VsyncEvent.Set();

                    _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
                }
            }
        }
 public virtual void MakeCurrent()
 {
     AssertValid();
     AssertContext();
     GraphicsContext.MakeCurrent(WindowInfo);
 }
Example #37
0
 protected override void Draw(GraphicsContext graphicsContext)
 {
     graphicsContext.Draw(_trianglePrimitive);
     base.Draw(graphicsContext);
 }
Example #38
0
            static GraphicsMemoryRegion <GraphicsResource> CreateConstantBufferRegion(GraphicsContext graphicsContext, GraphicsBuffer constantBuffer)
            {
                var constantBufferRegion = constantBuffer.Allocate(SizeOf <Matrix4x4>(), alignment: 256);
                var pConstantBuffer      = constantBuffer.Map <Matrix4x4>(in constantBufferRegion);

                pConstantBuffer[0] = Matrix4x4.Identity;

                constantBuffer.UnmapAndWrite(in constantBufferRegion);
                return(constantBufferRegion);
            }
Example #39
0
 /// <summary>
 /// Create the texture, using this technique.
 /// </summary>
 /// <param name="ctx">
 /// A <see cref="GraphicsContext"/> used for allocating resources.
 /// </param>
 public abstract void Create(GraphicsContext ctx);
 /// <inheritdoc/>
 public void Draw(GameTime time, GraphicsContext gfx)
 {
 }
Example #41
0
 /// <summary>
 /// Create a Texture name.
 /// </summary>
 /// <param name="ctx">
 /// A <see cref="GraphicsContext"/> used for creating this object name.
 /// </param>
 /// <returns>
 /// It returns a valid object name for this Texture.
 /// </returns>
 protected override uint CreateName(GraphicsContext ctx)
 {
     // Generate texture name
     return(Gl.GenTexture());
 }
Example #42
0
 /// <summary>
 /// Delete a Texture name.
 /// </summary>
 /// <param name="ctx">
 /// A <see cref="GraphicsContext"/> used for deleting this object name.
 /// </param>
 /// <param name="name">
 /// A <see cref="UInt32"/> that specify the object name to delete.
 /// </param>
 protected override void DeleteName(GraphicsContext ctx, uint name)
 {
     // Delete texture name
     Gl.DeleteTextures(name);
 }
Example #43
0
 internal override void Draw(GraphicsContext gfx)
 {
     gfx.Color = Color;
     gfx.DrawPolygon(_worldPolygon);
 }
Example #44
0
        /// <summary>
        /// Allocate resources for rendering.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ObjectsControl_ContextCreated(object sender, GlControlEventArgs e)
        {
            // Wrap GL context with GraphicsContext
            _Context = new GraphicsContext(e.DeviceContext, e.RenderContext);
            // Scene
            _CubeScene = new SceneGraph(
                SceneGraphFlags.CullingViewFrustum | SceneGraphFlags.StateSorting | SceneGraphFlags.Lighting | SceneGraphFlags.ShadowMaps
                //| SceneGraphFlags.BoundingVolumes
                );
            _CubeScene.SceneRoot = new SceneObjectGeometry();
            _CubeScene.SceneRoot.ObjectState.DefineState(new DepthTestState(DepthFunction.Less));

            _CubeScene.CurrentView = new SceneObjectCamera();
            _CubeScene.SceneRoot.Link(_CubeScene.CurrentView);

            fontTitle = FontFactory.CreateFont(System.Drawing.FontFamily.GenericSerif, 24, System.Drawing.FontStyle.Regular, FontFactory.FontType.Textured, new FontFxShadow());
            fontTitle.Create(_Context);

            fontTitleV = FontFactory.CreateFont(System.Drawing.FontFamily.GenericSerif, 24, System.Drawing.FontStyle.Regular, FontFactory.FontType.Vector, new FontFxShadow());
            fontTitleV.Create(_Context);

            fontPatch = FontFactory.CreateFont(System.Drawing.FontFamily.GenericMonospace, 16, System.Drawing.FontStyle.Regular, FontFactory.FontType.Vector);
            fontPatch.Create(_Context);

            // Global lighting
            SceneObjectLightZone globalLightZone = new SceneObjectLightZone();

            _GlobalLightObject           = new SceneObjectLightDirectional();
            _GlobalLightObject.Direction = (-Vertex3f.UnitX + Vertex3f.UnitY - Vertex3f.UnitZ).Normalized;
            //globalLightZone.Link(_GlobalLightObject);

            spotLight = new SceneObjectLightSpot();
            spotLight.LocalModel.Translate(0.0f, 35.0f, 0.0f);
            spotLight.Direction       = -Vertex3f.UnitY;
            spotLight.FalloffAngle    = 10.5f;
            spotLight.FalloffExponent = 0.0f;
            globalLightZone.Link(spotLight);

            SceneObjectLightPoint localLightObject = new SceneObjectLightPoint();

            localLightObject.LocalModel.Translate(0.0, -5.0f, 0.0);
            localLightObject.AttenuationFactors.Y = 0.1f;
            //globalLightZone.AddChild(localLightObject);

            _CubeScene.SceneRoot.Link(globalLightZone);

            // Horizontal plane
            globalLightZone.Link(CreatePlane());

            // Cube
            float       Size       = (float)Math.Sqrt(1);
            const float Multiplier = 10.0f;

            int materialIndex = 0;

            for (float x = -Size / 2.0f * Multiplier; x < Size / 2.0f * Multiplier; x += Multiplier)
            {
                for (float y = -Size / 2.0f * Multiplier; y < Size / 2.0f * Multiplier; y += Multiplier, materialIndex++)
                {
                    SceneObjectGeometry cubeInstance = CreateCubeGeometry();

                    cubeInstance.LocalModel.Translate(x, 0.0f, y);
                    cubeInstance.LocalModel.Scale(0.25f);

                    // materialIndex = 1;

                    // Enable/Disable blending
                    if ((materialIndex % 2) == 0)
                    {
                        cubeInstance.ObjectState.DefineState(new BlendState(BlendEquationMode.FuncAdd, BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha));
                    }

                    // Enable/Disable blending
                    switch (materialIndex % 3)
                    {
                    case 0:
                        cubeInstance.ProgramTag = ShadersLibrary.Instance.CreateProgramTag("OpenGL.Standard+Color");
                        break;

                    case 1:
                        cubeInstance.ProgramTag = ShadersLibrary.Instance.CreateProgramTag("OpenGL.Standard+LambertVertex", new ShaderCompilerContext("GLO_COLOR_PER_VERTEX"));
                        break;

                    case 2:
                        cubeInstance.ProgramTag = ShadersLibrary.Instance.CreateProgramTag("OpenGL.Standard+PhongFragment");
                        break;
                    }

                    globalLightZone.Link(cubeInstance);
                }
            }

            //SceneObjectGeometry cubeLambert = CreateCubeGeometry();
            //cubeLambert.ProgramTag = ShadersLibrary.Instance.CreateProgramTag("OpenGL.Standard+LambertVertex", new ShaderCompilerContext("GLO_COLOR_PER_VERTEX"));
            //globalLightZone.Link(cubeLambert);

            //SceneObjectGeometry cubeBlinn = CreateCubeGeometry();
            //cubeBlinn.ProgramTag = ShadersLibrary.Instance.CreateProgramTag("OpenGL.Standard+PhongFragment", new ShaderCompilerContext("GLO_COLOR_PER_VERTEX"));
            //cubeBlinn.LocalModel.Translate(0.0f, 10.0f, 0.0f);
            //globalLightZone.Link(cubeBlinn);

            //SceneObjectGeometry cubeColored = CreateCubeGeometry();
            //cubeColored.ProgramTag = ShadersLibrary.Instance.CreateProgramTag("OpenGL.Standard+Color");
            //cubeColored.LocalModel.Translate(0.0f, 5.0f, 0.0f);
            //globalLightZone.Link(cubeColored);

            globalLightZone.Link(CreateBumbleBeeVH());
            globalLightZone.Link(CreateBumbleBeeRB());
            // globalLightZone.Link(CreateSphere("squarebricks"));

            // Skybox
            //if ((sceneObject = CreateSkyBoxObject()) != null)
            //	_CubeScene.AddChild(sceneObject);

            _CubeScene.Create(_Context);

            Gl.ClearColor(0.1f, 0.1f, 0.1f, 0.0f);

            Gl.Enable(EnableCap.Multisample);
        }
Example #45
0
 /// <summary>
 /// Unbind this GraphicsSurface for reading.
 /// </summary>
 /// <param name="ctx">
 /// A <see cref="GraphicsContext"/> to wich disassociate its read result from this GraphicsSurface.
 /// </param>
 public virtual void UnbindRead(GraphicsContext ctx)
 {
 }
Example #46
0
        /// <summary>
        /// Apply this state to a shader program.
        /// </summary>
        /// <param name="ctx">
        /// A <see cref="GraphicsContext"/> used to share common state between shaders.
        /// </param>
        /// <param name="uniformContainer">
        /// A <see cref="IShaderUniformContainer"/> that specify this uniform state.
        /// </param>
        /// <param name="uniformScope">
        /// A <see cref="String"/> that specify the scope the uniform variable.
        /// </param>
        private void ApplyState(GraphicsContext ctx, IShaderUniformContainer uniformContainer, string uniformScope, IEnumerable <UniformStateMember> uniforms, object instance)
        {
            if (uniformContainer == null)
            {
                throw new ArgumentNullException("shaderProgram");
            }
            if (uniforms == null)
            {
                throw new ArgumentNullException("uniforms");
            }
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            foreach (UniformStateMember uniform in uniforms)
            {
                // Set the program uniform
                string uniformPattern = uniformScope != null?String.Format("{0}.{1}", uniformScope, uniform.UniformName) : uniform.UniformName;

                // Matches also partial uniform variables (i.e. glo_Struct[0] or glo_Struct while glo_Struct[0].Member is active)
                // Indeed quite efficient when structures are not active (skip all members)
                if (uniformContainer.IsActiveUniform(uniformPattern) == false)
                {
                    continue;
                }

                object uniformValue = uniform.GetUniformValue(instance);

                // Silently skip null references
                if (uniformValue == null)
                {
                    continue;
                }

                Type uniformValueType = uniformValue.GetType();

                if (uniformValueType.IsArray)
                {
                    Array uniformArray = (Array)uniformValue;

                    for (int i = 0; i < uniformArray.Length; i++)
                    {
                        string uniformArrayPattern = String.Format("{0}[{1}]", uniformPattern, i);

                        if (uniformContainer.IsActiveUniform(uniformArrayPattern) == false)
                        {
                            continue;
                        }

                        object uniformArrayValue = uniformArray.GetValue(i);

                        // Silently skip null references
                        if (uniformArrayValue == null)
                        {
                            continue;
                        }

                        ApplyUniform(ctx, uniformContainer, uniformArrayPattern, uniformArrayValue);
                    }
                }
                else
                {
                    ApplyUniform(ctx, uniformContainer, uniformPattern, uniformValue);
                }
            }
        }
Example #47
0
 /// <summary>
 /// Clear all Surface buffers.
 /// </summary>
 /// <param name="ctx">
 /// A <see cref="GraphicsContext"/> used for clearing buffers.
 /// </param>
 public void Clear(GraphicsContext ctx)
 {
     Clear(ctx, ClearBufferMask.ColorBufferBit);
 }
        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);
                        }
                    }
                }
            }
        }
Example #49
0
 /// <summary>
 /// Apply this MaterialState
 /// </summary>
 /// <param name="ctx">
 /// A <see cref="GraphicsContext"/> which has defined the shader program <paramref name="shaderProgram"/>.
 /// </param>
 /// <param name="shaderProgram">
 /// The <see cref="ShaderProgram"/> which has the state set.
 /// </param>
 public void ApplyState(GraphicsContext ctx, ShaderProgram shaderProgram, string prefix)
 {
     shaderProgram.SetUniform(ctx, prefix + ".AmbientLighting", AmbientLighting);
 }
Example #50
0
 /// <summary>
 /// Unbind this GraphicsSurface for drawing.
 /// </summary>
 /// <param name="ctx">
 /// A <see cref="GraphicsContext"/> to wich disassociate its rendering result from this GraphicsSurface.
 /// </param>
 public virtual void UnbindDraw(GraphicsContext ctx)
 {
 }
Example #51
0
        public ThumbnailGenerator(EffectCompilerBase effectCompiler)
        {
            // create base services
            Services = new ServiceRegistry();
            Services.AddService(MicrothreadLocalDatabases.ProviderService);
            ContentManager = new ContentManager(Services);
            Services.AddService <IContentManager>(ContentManager);
            Services.AddService(ContentManager);

            GraphicsDevice      = GraphicsDevice.New();
            GraphicsContext     = new GraphicsContext(GraphicsDevice);
            GraphicsCommandList = GraphicsContext.CommandList;
            Services.AddService(GraphicsContext);
            sceneSystem = new SceneSystem(Services);
            Services.AddService(sceneSystem);
            fontSystem = new GameFontSystem(Services);
            Services.AddService(fontSystem.FontSystem);
            Services.AddService <IFontFactory>(fontSystem.FontSystem);

            GraphicsDeviceService = new GraphicsDeviceServiceLocal(Services, GraphicsDevice);
            Services.AddService(GraphicsDeviceService);

            var uiSystem = new UISystem(Services);

            Services.AddService(uiSystem);

            var physicsSystem = new PhysicsSystem(Services);

            Services.AddService <IPhysicsSystem>(physicsSystem);

            gameSystems = new GameSystemCollection(Services)
            {
                fontSystem, uiSystem, physicsSystem
            };
            Services.AddService <IGameSystemCollection>(gameSystems);
            Simulation.DisableSimulation = true; //make sure we do not simulate physics within the editor

            // initialize base services
            gameSystems.Initialize();

            // create remaining services
            EffectSystem = new EffectSystem(Services);
            Services.AddService(EffectSystem);

            gameSystems.Add(EffectSystem);
            gameSystems.Add(sceneSystem);
            EffectSystem.Initialize();

            // Mount the same database for the cache
            EffectSystem.Compiler = EffectCompilerFactory.CreateEffectCompiler(effectCompiler.FileProvider, EffectSystem);

            // Deactivate the asynchronous effect compilation
            ((EffectCompilerCache)EffectSystem.Compiler).CompileEffectAsynchronously = false;

            // load game system content
            gameSystems.LoadContent();

            // create the default fonts
            var fontItem = OfflineRasterizedSpriteFontFactory.Create();

            fontItem.FontType.Size = 22;
            DefaultFont            = OfflineRasterizedFontCompiler.Compile(fontSystem.FontSystem, fontItem, true);

            // create utility members
            nullGameTime = new GameTime();
            SpriteBatch  = new SpriteBatch(GraphicsDevice);
            UIBatch      = new UIBatch(GraphicsDevice, null, null);

            // create the pipeline
            SetUpPipeline();
        }
Example #52
0
 private void ApplyStateCore(GraphicsContext ctx, ShaderProgram program)
 {
     Gl.PixelStore(PixelStoreParameter.PackAlignment, PackAlignment);
     Gl.PixelStore(PixelStoreParameter.UnpackAlignment, UnpackAlignment);
 }
Example #53
0
 /// <summary>
 /// Delete a Shader name.
 /// </summary>
 /// <param name="ctx">
 /// A <see cref="GraphicsContext"/> used for deleting this object name.
 /// </param>
 /// <param name="name">
 /// A <see cref="UInt32"/> that specify the object name to delete.
 /// </param>
 protected override void DeleteName(GraphicsContext ctx, uint name)
 {
     // Delete shader object
     Gl.DeleteShader(name);
 }
Example #54
0
        /// <summary>
        /// Apply this TransformState.
        /// </summary>
        /// <param name="ctx">
        /// A <see cref="GraphicsContext"/> which has defined the shader program <paramref name="shaderProgram"/>.
        /// </param>
        /// <param name="shaderProgram">
        /// The <see cref="ShaderProgram"/> which has the state set.
        /// </param>
        public override void Apply(GraphicsContext ctx, ShaderProgram shaderProgram)
        {
            GraphicsResource.CheckCurrentContext(ctx);

            if (!ctx.Extensions.UniformBufferObject_ARB)
            {
                if (shaderProgram == null)
                {
                    // Fixed pipeline rendering requires server state
                    throw new NotImplementedException();
                }
                else
                {
                    // Custom implementation
                    ctx.Bind(shaderProgram);

                    if (shaderProgram.IsActiveUniform("glo_LightModel"))
                    {
                        LightModel.ApplyState(ctx, shaderProgram, "glo_LightModel");
                    }

                    for (int i = 0; i < Lights.Count; i++)
                    {
                        string uniformName = "glo_Light[" + i + "]";

                        if (shaderProgram.IsActiveUniform(uniformName) == false)
                        {
                            break;
                        }

                        Lights[i].ApplyState(ctx, shaderProgram, uniformName);
                    }

                    shaderProgram.SetUniform(ctx, "glo_LightsCount", LightsCount);
                }
            }
            else
            {
                base.Apply(ctx, shaderProgram);                         // Uniform block
            }
            // Dummy shadow map: Texture2d
            // Note: necessary to avoid undefined behavior on glo_ShadowMap2D samplers
            string resourceClassId = "OpenGL.Objects.ShadowMap.DummyTexture2d";

            Texture2d dummyShadowMap = (Texture2d)ctx.GetSharedResource(resourceClassId);

            if (dummyShadowMap == null)
            {
                dummyShadowMap = new Texture2d(1, 1, PixelLayout.Depth16);
                dummyShadowMap.SamplerParams.CompareMode = true;
                dummyShadowMap.SamplerParams.CompareFunc = DepthFunction.Never;
                dummyShadowMap.Create(ctx);

                ctx.SetSharedResource(resourceClassId, dummyShadowMap);
            }

            // Dummy shadow map: TextureCube

            // Apply depth maps
            bool[] tex2dSet = new bool[4];

            for (int i = 0; i < tex2dSet.Length; i++)
            {
                if (i >= Lights.Count || Lights[i].ShadowMap2D == null)
                {
                    continue;
                }

                int shadowMapIndex = Lights[i].ShadowMapIndex;

                shaderProgram.SetUniform(ctx, "glo_ShadowMap2D[" + shadowMapIndex + "]", Lights[i].ShadowMap2D);
                tex2dSet[shadowMapIndex] = true;
            }

            // Avoid undefined behavior
            for (int i = 0; i < tex2dSet.Length; i++)
            {
                if (tex2dSet[i] == false)
                {
                    shaderProgram.SetUniform(ctx, "glo_ShadowMap2D[" + i + "]", dummyShadowMap);
                }
            }
        }
Example #55
0
        /// <summary>
        /// Compiles this Shader.
        /// </summary>
        /// <param name="ctx">
        /// The <see cref="GraphicsContext"/> holding the required resources.
        /// </param>
        private void Compile(GraphicsContext ctx)
        {
            if (_CompilationParams == null)
            {
                throw new InvalidOperationException("no compiler parameters");
            }

            // Using a deep copy of the shader compiler context, since it will be modified by this ShaderProgram
            // instance and the attached Shader instances
            ShaderCompilerContext cctx = new ShaderCompilerContext(_CompilationParams);

            Log("=== Compilation of shader object '{0}'.", _SourcePath);

            CompiledStrings = GenerateSource(ctx, cctx).ToArray();                    // Source generation!

            // Set shader source
            Gl.ShaderSource(ObjectName, CompiledStrings);

#if !MONODROID
            if (ctx.Extensions.ShadingLanguageInclude_ARB)
            {
                string[] includePaths = new string[cctx.Includes.Count];

                cctx.Includes.CopyTo(includePaths, 0);

                // Compile shader object (specifying include paths)
                Gl.CompileShaderIncludeARB(ObjectName, includePaths, null);
            }
            else
            {
                // Compile shader object (includes are already preprocessed)
                Gl.CompileShader(ObjectName);
            }
#else
            // Compile shader object (includes are already preprocessed)
            Gl.CompileShader(ObjectName);
#endif

            // Check for compilation errors
            int compilationStatus;

            Gl.GetShader(ObjectName, ShaderParameterName.CompileStatus, out compilationStatus);

            if (compilationStatus != Gl.TRUE)
            {
                StringBuilder sb = GetInfoLog();

                // Stop compilation process
                Log("Shader object \"{0}\" compilation failed:\n{1}", _SourcePath ?? "<Hardcoded>", sb.ToString());

                // Log the source code referred to the shader log
                Log("Source code for shader '{0}' that has generated the compiler error.", _SourcePath);
                Log("--------------------------------------------------------------------------------");
                uint sourcelineNo = 0;
                foreach (string sourceline in CompiledStrings)
                {
                    Log("{0,4} | {1}", ++sourcelineNo, sourceline.Length > 0 ? sourceline.Remove(sourceline.Length - 1, 1) : string.Empty);
                }
                Log("--------------------------------------------------------------------------------");

                throw new ShaderException("shader object is not valid. Compiler output for {0}: {1}\n", _SourcePath, sb.ToString());
            }
            else
            {
                StringBuilder sb = GetInfoLog();

                if (sb.Length > 0)
                {
                    Log("Shader object \"{0}\" compilation warning: {1}", _SourcePath ?? "<Hardcoded>", sb.ToString());
                }
            }

            IsCompiled = true;
        }
Example #56
0
 //This is where your scene is able to render content to the screen.
 //Treat this as a place to render your backdrop, since child components will render on-top of it.
 protected override void OnDraw(GameTime time, GraphicsContext gfx)
 {
     gfx.Clear(Color.CornflowerBlue); //In true MonoGame fashion.
 }
Example #57
0
 /// <summary>
 /// Draw a specific element set.
 /// </summary>
 /// <param name="ctx">
 /// The <see cref="GraphicsContext"/> used for rendering.
 /// </param>
 /// <param name="shader">
 /// The <see cref="ShaderProgram"/> used for drawing the vertex arrays.
 /// </param>
 /// <param name="elementIndex">
 /// A <see cref="Int32"/> that specifies the index of the element to draw. If it is less than 0, it draws
 /// all elements set. The index can be obtained by the value returned by <see cref="SetElementArray"/>.
 /// </param>
 public void Draw(GraphicsContext ctx, ShaderProgram shader, int elementIndex)
 {
     Draw(ctx, shader, GetElementArray(elementIndex));
 }
Example #58
0
 /// <summary>
 /// Create a Shader name.
 /// </summary>
 /// <param name="ctx">
 /// A <see cref="GraphicsContext"/> used for creating this object name.
 /// </param>
 /// <returns>
 /// It returns a valid object name for this Shader.
 /// </returns>
 protected override uint CreateName(GraphicsContext ctx)
 {
     // Create shader
     return(Gl.CreateShader(ObjectStage));
 }
Example #59
0
        private void VisionControl_ContextCreated(object sender, OpenGL.GlControlEventArgs e)
        {
            // Create GL context abstraction
            _GraphicsContext = new GraphicsContext(e.DeviceContext, e.RenderContext);

            // Create texture
            _FramebufferTexture = new Texture2d(1024, 1024, PixelLayout.RGB24);
            _FramebufferTexture.SamplerParams.MagFilter = TextureMagFilter.Linear;
            _FramebufferTexture.SamplerParams.MinFilter = TextureMinFilter.Linear;
            _FramebufferTexture.Create(_GraphicsContext);

            // Create framebuffer
            _Framebuffer = new Framebuffer();
            _Framebuffer.AttachColor(0, _FramebufferTexture);
            _Framebuffer.Create(_GraphicsContext);

            // Create shader (standard)
            _ProgramStd = _GraphicsContext.CreateProgram("OpenGL.Standard");
            _ProgramStd.Create(_GraphicsContext);

            // Create program (standard + texture)
            _ProgramStdTex = _GraphicsContext.CreateProgram("OpenGL.Standard+Texture");
            _ProgramStdTex.Create(_GraphicsContext);

            // Create vertex arrays (square)
            ArrayBuffer <Vertex2f> quadBuffer = new ArrayBuffer <Vertex2f>(BufferUsage.StaticDraw);

            quadBuffer.Create(new Vertex2f[] {
                new Vertex2f(-0.5f, +0.5f),
                new Vertex2f(-0.5f, -0.5f),
                new Vertex2f(+0.5f, +0.5f),
                new Vertex2f(+0.5f, -0.5f),
            });

            _ArraysQuad = new VertexArrays();
            _ArraysQuad.SetArray(quadBuffer, VertexArraySemantic.Position);
            _ArraysQuad.SetElementArray(PrimitiveType.TriangleStrip);
            _ArraysQuad.Create(_GraphicsContext);

            // Create vertex arrays (square)
            ArrayBuffer <Vertex2f> postquadBuffer = new ArrayBuffer <Vertex2f>(BufferUsage.StaticDraw);

            postquadBuffer.Create(new Vertex2f[] {
                new Vertex2f(0.0f, 1.0f),
                new Vertex2f(0.0f, 0.0f),
                new Vertex2f(1.0f, 1.0f),
                new Vertex2f(1.0f, 0.0f),
            });

            _ArraysPostQuad = new VertexArrays();
            _ArraysPostQuad.SetArray(postquadBuffer, VertexArraySemantic.Position);
            _ArraysPostQuad.SetArray(postquadBuffer, VertexArraySemantic.TexCoord);
            _ArraysPostQuad.SetElementArray(PrimitiveType.TriangleStrip);
            _ArraysPostQuad.Create(_GraphicsContext);

            // Create vertex arrays (optical markers)
            _BufferOpticalMarkers = new ArrayBuffer <Vertex2f>(BufferUsage.DynamicDraw);
            _BufferOpticalMarkers.Create(10000 * 2);

            _ArraysOpticalMarkers = new VertexArrays();
            _ArraysOpticalMarkers.SetArray(_BufferOpticalMarkers, VertexArraySemantic.Position);
            _ArraysOpticalMarkers.SetElementArray(PrimitiveType.Lines);
            _ArraysOpticalMarkers.Create(_GraphicsContext);
        }
Example #60
0
        /// <summary>
        /// Generate Shader source.
        /// </summary>
        /// <param name="ctx">
        /// A <see cref="GraphicsContext"/> used for the compilation process.
        /// </param>
        /// <param name="cctx">
        /// A <see cref="ShaderCompilerContext"/> that specify the information required for compiling this Shader.
        /// </param>
        /// <returns>
        /// It returns a <see cref="List{T}"/> which represent this Shader source. This source text is ready to be compiled.
        /// </returns>
        private List <string> GenerateSource(GraphicsContext ctx, ShaderCompilerContext cctx)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }
            if (cctx == null)
            {
                throw new ArgumentNullException("cctx");
            }
            if (_SourceStrings == null)
            {
                throw new InvalidOperationException("no source loaded");
            }

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

            // Initial status: original
            AppendSourceStrings(sourceLines, _SourceStrings.ToArray());

            // Append imposed header - Every source shall compile with this header
            int headerLine = 0;

            if (ctx.ShadingVersion.Api == KhronosVersion.ApiGlsl)
            {
                // Automatically prepend required shader version, if necessary
                if (sourceLines.Count > 0 && !Regex.IsMatch(sourceLines[0], @"\s*#version \d+.*"))
                {
                    int version = cctx.ShaderVersion.VersionId;

                    if (version >= 150)
                    {
                        // Starting from GLSL 1.50, profiles are implemented

                        if ((ctx.Flags & GraphicsContextFlags.ForwardCompatible) != 0)
                        {
                            sourceLines.Insert(headerLine++, $"#version {version} core\n");
                        }
                        else
                        {
                            sourceLines.Insert(headerLine++, $"#version {version} compatibility\n");
                        }
                    }
                    else
                    {
                        sourceLines.Insert(headerLine++, $"#version {version}\n");
                    }
                }
                else
                {
                    headerLine++;                               // #version already specified by implementor
                }
                // #extension
                if (ctx.Extensions.ShadingLanguageInclude_ARB)
                {
                    sourceLines.Insert(headerLine++, "#extension GL_ARB_shading_language_include : require\n");
                }

                if (ctx.Extensions.UniformBufferObject_ARB)
                {
                    sourceLines.Insert(headerLine++, "#extension GL_ARB_uniform_buffer_object : enable\n");
                }
                else
                {
                    sourceLines.Insert(headerLine++, "#define DISABLE_GL_ARB_uniform_buffer_object\n");
                }

                if (ObjectStage == ShaderType.GeometryShader && ctx.Extensions.GeometryShader4_ARB)
                {
                    sourceLines.Insert(headerLine++, "#extension GL_ARB_geometry_shader4 : enable\n");
                }

                if (ctx.Extensions.ShaderDrawParameters_ARB)
                {
                    sourceLines.Insert(headerLine++, "#extension GL_ARB_shader_draw_parameters : enable\n");
                }

                foreach (ShaderExtension shaderExtension in cctx.Extensions)
                {
                    // Do not include any #extension directive on extensions not supported by driver
                    if (ctx.Extensions.HasExtensions(shaderExtension.Name) == false)
                    {
                        continue;
                    }
                    sourceLines.Insert(headerLine++, $"#extension {shaderExtension.Name} : {shaderExtension.Behavior.ToString().ToLowerInvariant()}\n");
                }

                // #pragma
#if DEBUG
                // Debug directives
                sourceLines.Insert(headerLine++, "#pragma optimization(off)\n");
                sourceLines.Insert(headerLine++, "#pragma debug(on)\n");
#else
                sourceLines.Insert(headerLine++, "#pragma optimization(on)\n");
                sourceLines.Insert(headerLine++, "#pragma debug(off)\n");
#endif
            }
            else
            {
                switch (ObjectStage)
                {
                case ShaderType.FragmentShader:
                    sourceLines.Insert(headerLine++, "precision mediump float;\n");
                    break;
                }
            }

            // Append required #define statments
            if (cctx.Defines != null)
            {
                foreach (string def in cctx.Defines)
                {
                    sourceLines.Insert(headerLine++, $"#define {def} 1\n");
                    Log("  Symbol: {0}", def);
                }
            }

            // Remove comment lines
            sourceLines = CleanSource(sourceLines);

            // Preprocessing
            // Manage #include preprocessor directives in the case GL_ARB_shading_language_include is not supported
            // When #include are replaced, conditionals are processed too
            if (!ctx.Extensions.ShadingLanguageInclude_ARB)
            {
                sourceLines = ShaderPreprocessor.Process(sourceLines, cctx, ctx.IncludeLibrary, ShaderPreprocessor.Stage.All);
                sourceLines = CleanSource(sourceLines);
            }

            return(sourceLines);
        }