File: GraphicsDevice.cs

package info (click to toggle)
monogame 2.5.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 6,060 kB
  • ctags: 10,325
  • sloc: cs: 65,996; xml: 591; makefile: 22; ansic: 8
file content (898 lines) | stat: -rw-r--r-- 31,780 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
#region License
/*
Microsoft Public License (Ms-PL)
MonoGame - Copyright © 2009 The MonoGame Team

All rights reserved.

This license governs use of the accompanying software. If you use the software, you accept this license. If you do not
accept the license, do not use the software.

1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under 
U.S. copyright law.

A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.

2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, 
each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, 
each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.

3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, 
your patent license from such contributor to the software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution 
notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only under this license by including 
a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object 
code form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees
or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent
permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular
purpose and non-infringement.
*/
#endregion License
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

using MonoMac.OpenGL;

using Microsoft.Xna.Framework;

namespace Microsoft.Xna.Framework.Graphics
{	
	public class GraphicsDevice : IDisposable
	{
		private All _preferedFilter;
		private int _activeTexture = -1;
		private Viewport _viewport;
		private bool _isDisposed = false;
		private RenderState _renderState;

		public TextureCollection Textures { get; set; }

		private BlendState _blendState = BlendState.Opaque;
		private DepthStencilState _depthStencilState = DepthStencilState.Default;
		private SamplerStateCollection _samplerStates = new SamplerStateCollection ();
		internal List<IntPtr> _pointerCache = new List<IntPtr> ();
		private VertexBuffer _vertexBuffer = null;
		private IndexBuffer _indexBuffer = null;

		private uint VboIdArray;
		private uint VboIdElement;

		public RasterizerState RasterizerState { get; set; }
		
		private RenderTargetBinding[] currentRenderTargets;
		
		internal All PreferedFilter {
			get {
				return _preferedFilter;
			}
			set {
				_preferedFilter = value;
			}

		}

		internal int ActiveTexture {
			get {
				return _activeTexture;
			}
			set {
				_activeTexture = value;
			}
		}

		public bool IsDisposed { 
			get {
				return _isDisposed;
			}
		}

		public bool IsContentLost { 
			get {
				// We will just return IsDisposed for now
				// as that is the only case I can see for now
				return IsDisposed;
			}
		}

		public GraphicsDevice ()
		{	
			// Initialize the main viewport
			_viewport = new Viewport ();
			_viewport.X = 0;
			_viewport.Y = 0;						
			_viewport.Width = DisplayMode.Width;
			_viewport.Height = DisplayMode.Height;
			_viewport.MinDepth = 0.0f;
			_viewport.MaxDepth = 1.0f;
			Textures = new TextureCollection();
			// Init RenderState
			//_renderState = new RenderState ();
			RasterizerState = new RasterizerState();
		}

		public BlendState BlendState {
			get { return _blendState; }
			set { 
				// ToDo check for invalid state
				_blendState = value;
			}
		}

		public DepthStencilState DepthStencilState {
			get { return _depthStencilState; }
			set { 
				_depthStencilState = value;
			}
		}

		public SamplerStateCollection SamplerStates { 
			get {
				var temp = _samplerStates;
				return temp;
			} 
		}		

		public void Clear (Color color)
		{
			Clear (ClearOptions.Target, color.ToVector4(), 0, 0);
		}

		public void Clear (ClearOptions options, Color color, float depth, int stencil)
		{
			Clear (options, color.ToVector4 (), depth, stencil);
		}

		public void Clear (ClearOptions options, Vector4 color, float depth, int stencil)
		{
			GL.ClearColor (color.X, color.Y, color.Z, color.W);
			GL.Clear (CreateClearOptions(options, depth, stencil));
		}

		private ClearBufferMask CreateClearOptions (ClearOptions clearOptions, float depth, int stencil)
		{
			ClearBufferMask bufferMask = 0;
			if (clearOptions.HasFlag(ClearOptions.Target)) {
				bufferMask = bufferMask | ClearBufferMask.ColorBufferBit;
			}
			if (clearOptions.HasFlag(ClearOptions.Stencil)) {
				GL.ClearStencil (stencil);
				bufferMask = bufferMask | ClearBufferMask.StencilBufferBit;
			}
			if (clearOptions.HasFlag(ClearOptions.DepthBuffer)) {
				GL.ClearDepth (depth);
				bufferMask = bufferMask | ClearBufferMask.DepthBufferBit;
			}

			return bufferMask;
		}

		public void Clear (ClearOptions options, Color color, float depth, int stencil, Rectangle[] regions)
		{
			throw new NotImplementedException ();
		}

		public void Clear (ClearOptions options, Vector4 color, float depth, int stencil, Rectangle[] regions)
		{
			throw new NotImplementedException ();
		}

		public void Dispose ()
		{
			_isDisposed = true;
		}

		protected virtual void Dispose (bool aReleaseEverything)
		{
			if (aReleaseEverything) {

			}

			_isDisposed = true;
		}

		public void Present ()
		{
			GL.Flush ();
		}

		public void Present (Rectangle? sourceRectangle, Rectangle? destinationRectangle, IntPtr overrideWindowHandle)
		{
			throw new NotImplementedException ();
		}

		public void Reset ()
		{
			throw new NotImplementedException ();
		}

		public void Reset (Microsoft.Xna.Framework.Graphics.PresentationParameters presentationParameters)
		{
			throw new NotImplementedException ();
		}

		public void Reset (Microsoft.Xna.Framework.Graphics.PresentationParameters presentationParameters, GraphicsAdapter graphicsAdapter)
		{
			throw new NotImplementedException ();
		}

		public Microsoft.Xna.Framework.Graphics.DisplayMode DisplayMode {
			get {
				return GraphicsAdapter.DefaultAdapter.CurrentDisplayMode;
			}
		}

		public Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities GraphicsDeviceCapabilities {
			get {
				throw new NotImplementedException ();
			}
		}

		public Microsoft.Xna.Framework.Graphics.GraphicsDeviceStatus GraphicsDeviceStatus {
			get {
				throw new NotImplementedException ();
			}
		}

		public Microsoft.Xna.Framework.Graphics.PresentationParameters PresentationParameters {
			get;
			set;
		}

		public Microsoft.Xna.Framework.Graphics.Viewport Viewport {
			get {
				return _viewport;
			}
			set {
				_viewport = value;
			}
		}	

		public Microsoft.Xna.Framework.Graphics.GraphicsProfile GraphicsProfile { 
			get; 
			set;
		}

		public VertexDeclaration VertexDeclaration { 
			get; 
			set; 
		}

		Rectangle _scissorRectangle;

		public Rectangle ScissorRectangle { 
			get {
				return _scissorRectangle;
			}
			set {
				_scissorRectangle = value;

				switch (this.PresentationParameters.DisplayOrientation) 
				{
					case DisplayOrientation.Portrait :
					{
						_scissorRectangle.Y = _viewport.Height - _scissorRectangle.Y - _scissorRectangle.Height;
						break;
					}

					case DisplayOrientation.LandscapeLeft :
					{		
						var x = _scissorRectangle.X;
						_scissorRectangle.X = _viewport.Width - _scissorRectangle.Height - _scissorRectangle.Y;
						_scissorRectangle.Y = _viewport.Height - _scissorRectangle.Width - x;
					
						// Swap Width and Height
						var w = _scissorRectangle.Width;
						_scissorRectangle.Width = _scissorRectangle.Height;
						_scissorRectangle.Height = w;	
						break;
					}

					case DisplayOrientation.LandscapeRight :
					{			
						var x = _scissorRectangle.X;
						_scissorRectangle.X = _scissorRectangle.Y;
						_scissorRectangle.Y = x;
						var w = _scissorRectangle.Width;
						_scissorRectangle.Width = _scissorRectangle.Height;
						_scissorRectangle.Height = w;
						break;
					}
					
					case DisplayOrientation.PortraitUpsideDown :
					{
						_scissorRectangle.Y = _scissorRectangle.X;
						_scissorRectangle.X = _viewport.Width - _scissorRectangle.X - _scissorRectangle.Width;
						break;
					}
					
					case DisplayOrientation.Default :
					{
						_scissorRectangle.Y = _viewport.Height - _scissorRectangle.Y - _scissorRectangle.Height;
						break;
					}
				}
			}
		}

		public void SetRenderTarget (RenderTarget2D renderTarget) 
		{

			// We check if the rendertarget being passed is null or if we already have a rendertarget
			// NetRumble sample does not set the the renderTarget to null before setting another
			// rendertarget.  We handle that by checking first if we have a current render target set
			// if we do then we unbind the current rendertarget, reset the viewport and set the
			// rendertarget to the new one being passed if it is not null
			if (renderTarget == null || currentRenderTargets != null) {

				GL.DrawBuffer(DrawBufferMode.ColorAttachment0);
				// Detach the render buffers
				GL.FramebufferRenderbuffer(FramebufferTarget.FramebufferExt, FramebufferAttachment.DepthAttachmentExt,
						RenderbufferTarget.RenderbufferExt, 0);
				// delete the RBO's
				GL.DeleteRenderbuffers(renderBufferIDs.Length,renderBufferIDs);
				// delete the FBO
				GL.DeleteFramebuffers(frameBufferIDs.Length, frameBufferIDs);
				// Set the frame buffer back to the system window buffer
				GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0);				

				// We need to reset our GraphicsDevice viewport back to what it was
				// before rendering.
				Viewport = savedViewport;

				if (renderTarget == null)
					currentRenderTargets = null;
				else {
					SetRenderTargets(new RenderTargetBinding(renderTarget));
				}
			}
			else {
				SetRenderTargets(new RenderTargetBinding(renderTarget));
			}
		}

		int[] frameBufferIDs;
		int[] renderBufferIDs;

		// TODO: We need to come up with a state save and restore of the GraphicsDevice
		//  This would probably work with a Stack that allows pushing and popping of the current
		//  Graphics device state.
		//  Right now here is the list of state values that should be implemented
		//  Viewport - Used for RenderTargets
		//  Depth and Stencil formats	- To be determined
		Viewport savedViewport;

		public void SetRenderTargets (params RenderTargetBinding[] renderTargets) 
		{
			
			currentRenderTargets = renderTargets;
			
			if (currentRenderTargets != null) {


				// TODO: For speed we need to consider using FBO switching instead
				// of multiple FBO's if they are the same size.

				// http://www.songho.ca/opengl/gl_fbo.html
				
				frameBufferIDs = new int[currentRenderTargets.Length];
				
				renderBufferIDs = new int[currentRenderTargets.Length];
				GL.GenRenderbuffers(currentRenderTargets.Length, renderBufferIDs);
				
				for (int i = 0; i < currentRenderTargets.Length; i++) {
					RenderTarget2D target = (RenderTarget2D)currentRenderTargets[i].RenderTarget;

					// create a renderbuffer object to store depth info
					GL.BindRenderbuffer(RenderbufferTarget.RenderbufferExt, renderBufferIDs[i]);

					ClearOptions clearOptions = ClearOptions.Target | ClearOptions.DepthBuffer;

					// create framebuffer
					GL.GenFramebuffers(1, out frameBufferIDs[i]);
					GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, frameBufferIDs[i]);

					// attach stencil buffer
					switch (target.DepthStencilFormat) {
					case DepthFormat.Depth16:
						GL.RenderbufferStorage(RenderbufferTarget.RenderbufferExt, RenderbufferStorage.DepthComponent16,
							target.Width, target.Height);
						break;
					case DepthFormat.Depth24:
						GL.RenderbufferStorage(RenderbufferTarget.RenderbufferExt, RenderbufferStorage.DepthComponent24,
							target.Width, target.Height);
						break;
					case DepthFormat.Depth24Stencil8:
						GL.RenderbufferStorage(RenderbufferTarget.RenderbufferExt, RenderbufferStorage.Depth24Stencil8,
							target.Width, target.Height);
						GL.FramebufferRenderbuffer(FramebufferTarget.FramebufferExt, FramebufferAttachment.StencilAttachmentExt,
							RenderbufferTarget.RenderbufferExt, renderBufferIDs[i]);
						clearOptions = clearOptions | ClearOptions.Stencil;
						break;
					default:
						GL.RenderbufferStorage(RenderbufferTarget.RenderbufferExt, RenderbufferStorage.DepthComponent24,
							target.Width, target.Height);
						break;
					}
					
					// attach the texture to FBO color attachment point
					GL.FramebufferTexture2D(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0,
						TextureTarget.Texture2D, target.ID,0);
					
					// attach the renderbuffer to depth attachment point
					GL.FramebufferRenderbuffer(FramebufferTarget.FramebufferExt, FramebufferAttachment.DepthAttachmentExt,
						RenderbufferTarget.RenderbufferExt, renderBufferIDs[i]);					
					
					if (target.RenderTargetUsage == RenderTargetUsage.DiscardContents)
						Clear (clearOptions, Color.Transparent, 0, 0);
					
					GL.BindRenderbuffer(RenderbufferTarget.RenderbufferExt, 0);
				}
				
				FramebufferErrorCode status = GL.CheckFramebufferStatus(FramebufferTarget.FramebufferExt);
				
				if (status != FramebufferErrorCode.FramebufferComplete)
					throw new Exception("Error creating framebuffer: " + status);

				// We need to start saving off the ViewPort and setting the current ViewPort to
				// the width and height of the texture.  Then when we pop off the rendertarget
				// it needs to be reset.  This causes drawing problems if we do not set the viewport.
				// Makes sense once you follow the flow (hits head on desk)
				// For an example of this take a look at NetRumble's sample for the BloomPostprocess

				// Save off the current viewport to be reset later
				savedViewport = Viewport;

				// Create a new Viewport
				Viewport renderTargetViewPort = new Viewport();

				// Set the new viewport to the width and height of the render target
				Texture2D target2 = (Texture2D)currentRenderTargets[0].RenderTarget;
				renderTargetViewPort.Width = target2.Width;
				renderTargetViewPort.Height = target2.Height;

				// now we set our viewport to the new rendertarget viewport just created.
				Viewport = renderTargetViewPort;
			}						
		}

		public RenderTargetBinding[] GetRenderTargets ()
		{
			return currentRenderTargets;
		}
		
		public void ResolveBackBuffer (ResolveTexture2D resolveTexture)
		{
		}

		public BeginMode PrimitiveTypeGL11 (PrimitiveType primitiveType)
		{
			switch (primitiveType) {
			case PrimitiveType.LineList:
				return BeginMode.Lines;
			case PrimitiveType.LineStrip:
				return BeginMode.LineStrip;
			case PrimitiveType.TriangleList:
				return BeginMode.Triangles;
			case PrimitiveType.TriangleStrip:
				return BeginMode.TriangleStrip;
			}

			throw new NotImplementedException ();
		}

		public void SetVertexBuffer (VertexBuffer vertexBuffer)
		{
			_vertexBuffer = vertexBuffer;
			//GL.BindBuffer (BufferTarget.ArrayBuffer, vertexBuffer._bufferStore);
		}

		private void SetIndexBuffer (IndexBuffer indexBuffer)
		{
			_indexBuffer = indexBuffer;
			//GL.BindBuffer (BufferTarget.ElementArrayBuffer, indexBuffer._bufferStore);
		}

		public IndexBuffer Indices { set { SetIndexBuffer (value); } }


		internal void SetGraphicsStates ()
		{
			GL.PushMatrix();
			// Set up our Rasterizer States
			GLStateManager.SetRasterizerStates(RasterizerState);
			GLStateManager.SetBlendStates(BlendState);
		}

		bool resetVertexStates = false;
		internal void UnsetGraphicsStates ()
		{
			// Make sure we are not user any shaders
			GL.UseProgram(0);

			// if primitives were used then we need to reset them
			if (resetVertexStates) {
				GLStateManager.VertexArray(false);
				GLStateManager.ColorArray(false);
				GLStateManager.NormalArray(false);
				GLStateManager.TextureCoordArray(false);
				resetVertexStates = false;
			}
				GL.PopMatrix();

		}

		public void DrawIndexedPrimitives (PrimitiveType primitiveType, int baseVertex, int minVertexIndex, int numbVertices, int startIndex, int primitiveCount)
		{
			if (minVertexIndex > 0 || baseVertex > 0)
				throw new NotImplementedException ("baseVertex > 0 and minVertexIndex > 0 are not supported");

			// we need to reset vertex states afterwards
			resetVertexStates = true;

			// Set up our Graphics States
			SetGraphicsStates();

            // Unbind the VBOs
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

            //Create VBO if not created already
            if (VboIdArray == 0)
                GL.GenBuffers(1, out VboIdArray);
            if (VboIdElement == 0)
                GL.GenBuffers(1, out VboIdElement);

            // Bind the VBO
            GL.BindBuffer(BufferTarget.ArrayBuffer, VboIdArray);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, VboIdElement);
            ////Clear previous data
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)0, (IntPtr)null, BufferUsageHint.DynamicDraw);
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)0, (IntPtr)null, BufferUsageHint.DynamicDraw);

			//Get VertexDeclaration
			var vd = _vertexBuffer.VertexDeclaration;
			if (vd == null) {

				vd = VertexDeclaration.FromType(_vertexBuffer._type);
			}

            //Pin data
            var handle = GCHandle.Alloc(_vertexBuffer, GCHandleType.Pinned);
            var handle2 = GCHandle.Alloc(_vertexBuffer, GCHandleType.Pinned);

            //Buffer data to VBO; This should use stream when we move to ES2.0
            GL.BufferData(BufferTarget.ArrayBuffer,
				(IntPtr)(vd.VertexStride * GetElementCountArray(primitiveType, primitiveCount)),
				_vertexBuffer._bufferPtr,
				BufferUsageHint.DynamicDraw);

            GL.BufferData(BufferTarget.ElementArrayBuffer,
				(IntPtr)(sizeof(ushort) * GetElementCountArray(primitiveType, primitiveCount)),
				_indexBuffer._bufferPtr,
				BufferUsageHint.DynamicDraw);

            //Setup VertexDeclaration
            VertexDeclaration.PrepareForUse(vd);

            //Draw
            GL.DrawElements(PrimitiveTypeGL11(primitiveType),
				GetElementCountArray(primitiveType, primitiveCount),
				DrawElementsType.UnsignedShort,
				(IntPtr)(startIndex * sizeof(ushort)));


            // Free resources
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
            handle.Free();
            handle2.Free();

			UnsetGraphicsStates();
		}

		public void DrawUserPrimitives<T> (PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int primitiveCount) where T : struct, IVertexType
		{


			// we need to reset vertex states afterwards
			resetVertexStates = true;

			// Set up our Graphics States
			SetGraphicsStates();

           // Unbind the VBOs
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

            //Create VBO if not created already
            if (VboIdArray == 0)
                GL.GenBuffers(1, out VboIdArray);

            // Bind the VBO
            GL.BindBuffer(BufferTarget.ArrayBuffer, VboIdArray);
            ////Clear previous data
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)0, (IntPtr)null, BufferUsageHint.DynamicDraw);

            //Get VertexDeclaration
            var vd = VertexDeclaration.FromType(typeof(T));

            //Pin data
            var handle = GCHandle.Alloc(vertexData, GCHandleType.Pinned);

            //Buffer data to VBO; This should use stream when we move to ES2.0
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vd.VertexStride * GetElementCountArray(primitiveType, primitiveCount)), vertexData,BufferUsageHint.DynamicDraw);

            //Setup VertexDeclaration
            VertexDeclaration.PrepareForUse(vd);

            //Draw
            GL.DrawArrays(PrimitiveTypeGL11(primitiveType), vertexOffset, GetElementCountArray(primitiveType, primitiveCount));

            // Free resources
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
            handle.Free();

			// Unset our Graphics States
			UnsetGraphicsStates();


		}

		public void DrawUserPrimitives<T> (PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct, IVertexType
		{

			// we need to reset vertex states afterwards
			resetVertexStates = true;

			// Set up our Graphics States
			SetGraphicsStates();

           // Unbind the VBOs
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

            //Create VBO if not created already
            if (VboIdArray == 0)
                GL.GenBuffers(1, out VboIdArray);

            // Bind the VBO
            GL.BindBuffer(BufferTarget.ArrayBuffer, VboIdArray);
            ////Clear previous data
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)0, (IntPtr)null, BufferUsageHint.DynamicDraw);

            //Get VertexDeclaration
            //var vd = VertexDeclaration.FromType(typeof(T));

            //Pin data
            var handle = GCHandle.Alloc(vertexData, GCHandleType.Pinned);

            //Buffer data to VBO; This should use stream when we move to ES2.0
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertexDeclaration.VertexStride * GetElementCountArray(primitiveType, primitiveCount)), vertexData,BufferUsageHint.DynamicDraw);

            //Setup VertexDeclaration
            VertexDeclaration.PrepareForUse(vertexDeclaration);

            //Draw
            GL.DrawArrays(PrimitiveTypeGL11(primitiveType), vertexOffset, GetElementCountArray(primitiveType, primitiveCount));

            // Free resources
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
            handle.Free();

			// Unset our Graphics States
			UnsetGraphicsStates();
		}

		public void DrawPrimitives (PrimitiveType primitiveType, int vertexStart, int primitiveCount)
		{

			// we need to reset vertex states afterwards
			resetVertexStates = true;

			// Set up our Graphics States
			SetGraphicsStates();

           // Unbind the VBOs
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

            //Create VBO if not created already
            if (VboIdArray == 0)
                GL.GenBuffers(1, out VboIdArray);

            // Bind the VBO
            GL.BindBuffer(BufferTarget.ArrayBuffer, VboIdArray);
            ////Clear previous data
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)0, (IntPtr)null, BufferUsageHint.DynamicDraw);

			//Get VertexDeclaration
			var vd = _vertexBuffer.VertexDeclaration;
			if (vd == null) {

				vd = VertexDeclaration.FromType(_vertexBuffer._type);
			}
            //Pin data
            var handle = GCHandle.Alloc(_vertexBuffer, GCHandleType.Pinned);

            //Buffer data to VBO; This should use stream when we move to ES2.0
            GL.BufferData(BufferTarget.ArrayBuffer,
				(IntPtr)(vd.VertexStride * GetElementCountArray(primitiveType, primitiveCount)),
				_vertexBuffer._bufferPtr,
				BufferUsageHint.DynamicDraw);

            //Setup VertexDeclaration
            VertexDeclaration.PrepareForUse(vd);

            //Draw
            GL.DrawArrays(PrimitiveTypeGL11(primitiveType), vertexStart, GetElementCountArray(primitiveType, primitiveCount));

            // Free resources
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
            handle.Free();

			// Unset our Graphics States
			UnsetGraphicsStates();
		}

        public void DrawUserIndexedPrimitives<T>(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int vertexCount, short[] indexData, int indexOffset, int primitiveCount) where T : struct, IVertexType
        {

			// we need to reset vertex states afterwards
			resetVertexStates = true;

			// Set up our Graphics States
			SetGraphicsStates();

            // Unbind the VBOs
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

            //Create VBO if not created already
            if (VboIdArray == 0)
                GL.GenBuffers(1, out VboIdArray);
            if (VboIdElement == 0)
                GL.GenBuffers(1, out VboIdElement);

            // Bind the VBO
            GL.BindBuffer(BufferTarget.ArrayBuffer, VboIdArray);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, VboIdElement);
            ////Clear previous data
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)0, (IntPtr)null, BufferUsageHint.DynamicDraw);
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)0, (IntPtr)null, BufferUsageHint.DynamicDraw);

            //Get VertexDeclaration
            var vd = VertexDeclaration.FromType(typeof(T));

            //Pin data
            var handle = GCHandle.Alloc(vertexData, GCHandleType.Pinned);
            var handle2 = GCHandle.Alloc(vertexData, GCHandleType.Pinned);

            //Buffer data to VBO; This should use stream when we move to ES2.0
//			int vds = vd.VertexStride;
//			int ec = GetElementCountArray(primitiveType, primitiveCount);
//			int sec = vd.VertexStride * GetElementCountArray(primitiveType, primitiveCount);
//			IntPtr ip = (IntPtr)(vd.VertexStride * GetElementCountArray(primitiveType, primitiveCount));
//			IntPtr ip2 = new IntPtr(handle.AddrOfPinnedObject().ToInt64() + (vertexOffset * vd.VertexStride));

            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vd.VertexStride * GetElementCountArray(primitiveType, primitiveCount)),
				new IntPtr(handle.AddrOfPinnedObject().ToInt64() + (vertexOffset * vd.VertexStride)), BufferUsageHint.DynamicDraw);
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(sizeof(ushort) * GetElementCountArray(primitiveType, primitiveCount)), indexData, BufferUsageHint.DynamicDraw);

            //Setup VertexDeclaration
            VertexDeclaration.PrepareForUse(vd);

            //Draw
            GL.DrawElements(PrimitiveTypeGL11(primitiveType), GetElementCountArray(primitiveType, primitiveCount),DrawElementsType.UnsignedShort, (IntPtr)(indexOffset * sizeof(ushort)));


            // Free resources
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
            handle.Free();
            handle2.Free();

			// Unset our Graphics States
			UnsetGraphicsStates();

        }

        public void DrawUserIndexedPrimitives<T>(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int vertexCount, int[] indexData, int indexOffset, int primitiveCount) where T : struct, IVertexType
        {

			// we need to reset vertex states afterwards
			resetVertexStates = true;

			// Set up our Graphics States
			SetGraphicsStates();


            // Unbind the VBOs
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

            //Create VBO if not created already
            if (VboIdArray == 0)
                GL.GenBuffers(1, out VboIdArray);
            if (VboIdElement == 0)
                GL.GenBuffers(1, out VboIdElement);

            // Bind the VBO
            GL.BindBuffer(BufferTarget.ArrayBuffer, VboIdArray);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, VboIdElement);
            ////Clear previous data
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)0, (IntPtr)null, BufferUsageHint.DynamicDraw);
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)0, (IntPtr)null, BufferUsageHint.DynamicDraw);

            //Get VertexDeclaration
            var vd = VertexDeclaration.FromType(typeof(T));

            //Pin data
            var handle = GCHandle.Alloc(vertexData, GCHandleType.Pinned);
            var handle2 = GCHandle.Alloc(vertexData, GCHandleType.Pinned);

            //Buffer data to VBO; This should use stream when we move to ES2.0
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vd.VertexStride * GetElementCountArray(primitiveType, primitiveCount)), new IntPtr(handle.AddrOfPinnedObject().ToInt64() + (vertexOffset * vd.VertexStride)), BufferUsageHint.DynamicDraw);
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(sizeof(uint) * GetElementCountArray(primitiveType, primitiveCount)), indexData, BufferUsageHint.DynamicDraw);

            //Setup VertexDeclaration
            VertexDeclaration.PrepareForUse(vd);

            //Draw
            GL.DrawElements(PrimitiveTypeGL11(primitiveType), GetElementCountArray(primitiveType, primitiveCount),DrawElementsType.UnsignedInt, (IntPtr)(indexOffset * sizeof(uint)));


            // Free resources
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
            handle.Free();
            handle2.Free();

			// Unset our Graphics States
			UnsetGraphicsStates();

        }

		public int GetElementCountArray (PrimitiveType primitiveType, int primitiveCount)
		{
			//TODO: Overview the calculation
			// Please see comments made by kjpou1 below.  The samples would not work correctly so
			//  modified the values below.  This is what got the samples working so if they
			//  are not correct please modify but make sure samples are working.
			//  TextureQuad and PrimitivesTest are the ones to check
			switch (primitiveType) {
			case PrimitiveType.LineList:
				return primitiveCount * 2;
			case PrimitiveType.LineStrip:
				// Was causing extra lines
				return primitiveCount + 1;//     3 + (primitiveCount - 1); // ???
			case PrimitiveType.TriangleList:
				// The primitiveCount * 2 was causing some lines not to show up
				//  changing it to 3 activated those lines.  For a quad map only the first
				//  triangle was showing instead of the full quad.
				return primitiveCount * 3;  //primitiveCount * 2;
			case PrimitiveType.TriangleStrip:
				// This is a test --- changed by kjpou1 -- modified from what is below
				// as I really did not understand it.
				//   If the change does not work then please move back to what was below
				//3 + (primitiveCount - 1); // ???
				return primitiveCount + 2;
			}

			throw new NotSupportedException ();
		}

	}
}