示例#1
1
        public static Vector4 UnProject(ref Matrix4 projection, Matrix4 view, Size viewport, MouseDevice mouse)
        {
            Vector4 vec;

            if (mouse.X > 0)
            {
                vec = new Vector4();
            }
            vec.X = 2.0f * mouse.X / (float)viewport.Width -1;
            vec.Y = -(2.0f * mouse.Y / (float)viewport.Height -1);
            vec.Z = 0;
            vec.W = 1.0f;

            Matrix4 viewInv = Matrix4.Invert(view);
            Matrix4 projInv = Matrix4.Invert(projection);

            Vector4.Transform(ref vec, ref projInv, out vec);
            Vector4.Transform(ref vec, ref viewInv, out vec);

            if (vec.W > float.Epsilon || vec.W < float.Epsilon)
            {
                vec.X /= vec.W;
                vec.Y /= vec.W;
                vec.Z /= vec.W;
            }

            return (vec);
        }
示例#2
0
文件: GuiRoot.cs 项目: Lazzu/Hatzap
 void gw_Resize(object sender, EventArgs e)
 {
     Projection = Matrix4.CreateOrthographicOffCenter(0, gw.Width, gw.Height, 0, -100, 100);
     widgets.Size = new Vector2(gw.Width, gw.Height);
     if (widgets.ChildWidgetCount > 0)
         widgets.Dirty = true;
 }
示例#3
0
 public BeamRenderer(int count, IDrawable part, Vector3 dist)
 {
     Count = count;
     Part = part;
     Distance = dist;
     Offset = Matrix4Extensions.FromTranslation(Distance);
 }
示例#4
0
 /// 行列との掛け算
 public static Vector3 Mult( ref Vector3 pos, Matrix4 mtx )
 {
     calPos.X = (mtx.M11 * pos.X) + (mtx.M21 * pos.Y) + ( mtx.M31 * pos.Z ) + ( mtx.M41 * 0.0f );
     calPos.Y = (mtx.M12 * pos.X) + (mtx.M22 * pos.Y) + ( mtx.M32 * pos.Z ) + ( mtx.M42 * 0.0f );
     calPos.Z = (mtx.M13 * pos.X) + (mtx.M23 * pos.Y) + ( mtx.M33 * pos.Z ) + ( mtx.M43 * 0.0f );
     return calPos;
 }
示例#5
0
        public ColorScale(float min, float max, int width, int height)
        {
            this.width = width;
            this.height = height;
            this.min = min;
            this.max = max;
            length = 400.0f;
            barHeight = 25.0f;
            bottom = -height / 2.0f + 30.0f;
            left = -length / 2.0f;
            NumOfVertices = 0;
            cm = new Dictionary<float, Vector3>();
            popis_txt = new Text2D(width,height);
            popis_dic = new Dictionary<string, Vector4>();

            VAO = new int[1];
            VBO = new int[2];
            projectionMatrix = Matrix4.Identity;
            modelViewMatrix = Matrix4.Identity;

            VertexShader = new Shaders.Shader();
            FragmentShader = new Shaders.Shader();
            spMain = new Shaders.ShaderProgram();

            SetColorScale();
            SetText();
            Init();
        }
示例#6
0
 /// 行列との掛け算
 public static Vector4 Mult( ref Vector4 pos, Matrix4 mtx )
 {
     calPos4.X = (mtx.M11 * pos.X) + (mtx.M21 * pos.Y) + ( mtx.M31 * pos.Z ) + ( mtx.M41 * pos.W );
     calPos4.Y = (mtx.M12 * pos.X) + (mtx.M22 * pos.Y) + ( mtx.M32 * pos.Z ) + ( mtx.M42 * pos.W );
     calPos4.Z = (mtx.M13 * pos.X) + (mtx.M23 * pos.Y) + ( mtx.M33 * pos.Z ) + ( mtx.M43 * pos.W );
     return calPos4;
 }
示例#7
0
文件: Variable.cs 项目: silky/sledge
 public void Set(Matrix4[] matrix)
 {
     if (Value != null && Value.Equals(matrix)) return;
     Value = matrix;
     //GL.UniformMatrix4(Location, false, ref matrix);
     GL.UniformMatrix4(Location, matrix.Length, false, ref matrix[0].Row0.X);
 }
        // UnProject takes a window-local mouse-coordinate, and a Z-coordinate depth [0,1] and
        // unprojects it, returning the point in world space. To get a ray, UnProject the
        // mouse coordinates at two different z-values.
        //
        // http://www.opentk.com/node/1276#comment-13029
        public static Vector3 UnProject(
			ref Matrix4 projection, 
			Matrix4 view, 
			System.Drawing.Size viewport, 
			Vector3 mouse)
        {
            Vector4 vec;

            vec.X = 2.0f * mouse.X / (float)viewport.Width - 1;
            vec.Y = -(2.0f * mouse.Y / (float)viewport.Height - 1);
            vec.Z = mouse.Z;
            vec.W = 1.0f;

            Matrix4 viewInv = Matrix4.Invert(view);
            Matrix4 projInv = Matrix4.Invert(projection);

            Vector4.Transform(ref vec, ref projInv, out vec);
            Vector4.Transform(ref vec, ref viewInv, out vec);

            if (vec.W > float.Epsilon || vec.W < float.Epsilon)
            {
                vec.X /= vec.W;
                vec.Y /= vec.W;
                vec.Z /= vec.W;
            }

            return new Vector3(vec.X,vec.Y,vec.Z);
        }
示例#9
0
        public void compute_matrices_from_input()
        {
            Cursor.Position = new Point(Game.Center.X, Game.Center.Y);

            _horzAngle -= MouseSpeed * (float)Game.DeltaTime.TotalSeconds * _mouseDelta.X;
            _vertAngle -= MouseSpeed * (float)Game.DeltaTime.TotalSeconds * _mouseDelta.Y;

            _right.X = (float)Math.Sin(_horzAngle - 3.14f / 2.0f);
            _right.Y = 0;
            _right.Z = (float)Math.Cos(_horzAngle - 3.14f / 2.0f);

            _direction.X = (float)(Math.Cos(_vertAngle) * Math.Sin(_horzAngle));
            _direction.Y = (float)Math.Sin(_vertAngle);
            _direction.Z = (float)(Math.Cos(_vertAngle) * Math.Cos(_horzAngle));

            _up = Vector3.Cross(_right, _direction);

            _fov = InitFov - (5 * Mouse.GetState().ScrollWheelValue);

            if (Movements.Count > 0) Move();

            Projection = Matrix4.CreatePerspectiveFieldOfView(((float)(Math.PI * _fov) / 180), 4.0f / 3.0f, 0.1f, 100.0f);

            View = Matrix4.LookAt(_position, _position + _direction, _up);
        }
示例#10
0
 public virtual void ApplyProjectionMatrix(ref Matrix4 pickMatrix)
 {
     CalculateProjectionMatrix();
     Matrix4 result = ProjectionMatrix * pickMatrix;
     GL.MatrixMode(MatrixMode.PROJECTION);
     GL.LoadMatrix(ref result);
 }
示例#11
0
 public void viewportSize(int viewportWidth, int viewportHeight)
 {
     this.Width = viewportWidth;
     this.Height = viewportHeight;
     float aspectRatio = Width / (float)Height;
     projectionMatrix = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, 1.0f, 4096.0f);
 }
 public unsafe static void SetWorldTransform(this MotionState obj, ref Matrix4 transform)
 {
     fixed (Matrix4* value = &transform)
     {
         obj.SetWorldTransform(ref *(Matrix*)value);
     }
 }
示例#13
0
 public Transform()
 {
     rotation = Quaternion.Identity;
     matrix = Matrix4.Identity;
     position = Vector3.Zero;
     scale = Vector3.One;
 }
示例#14
0
        /// <summary>
        /// position is top left of box.
        /// </summary>
        /// <param name="position"></param>
        /// <param name="size"></param>
        /// <param name="color"></param>
        public ColorBox(Vector2 position, Vector2 size, Color4 color)
        {
            this.position = position;
            this.size = size;
            model = Matrix4.CreateTranslation(position.X, position.Y, 0);
            Color = color;

            float[] vertices = new float[]
            {
                0, 0,
                0, size.Y,
                size.X, 0,
                size.X, size.Y
            };

            uint[] indices = new uint[]
            {
                0, 1, 2, 3
            };

            VBO vert = new VBO(), ind = new VBO();
            vert.SetData(ref vertices, BufferUsageHint.StaticDraw);
            ind.SetData(ref indices, BufferUsageHint.StaticDraw);

            bufSet = new BufferSet();
            bufSet.VertexBuffer = vert;
            bufSet.IndexBuffer = ind;
            bufSet.VertexSize = 2;
            bufSet.DrawMode = BeginMode.TriangleStrip;
            bufSet.SetDrawState(DrawStates.Vertex);
        }
        public void Render(TerrainTile tile, TerrainGlobal terrainGlobal, Matrix4 projection, Matrix4 view, Vector3 eyePos)
        {
            var boxparam = tile.GetBoxParam();

            Vector3 eyePosTileCoords = Vector4.Transform(new Vector4(eyePos, 0.0f), tile.InverseModelMatrix).Xyz;

            GL.Enable(EnableCap.CullFace);
            GL.CullFace(CullFaceMode.Front);  // we only want to render back-faces

            tile.HeightTexture.Bind(TextureUnit.Texture0);
            tile.ParamTexture.Bind(TextureUnit.Texture1);
            tile.NormalTexture.Bind(TextureUnit.Texture2);

            this.boundingBoxProgram
                .UseProgram()
                .SetUniform("projection_matrix", projection)
                .SetUniform("model_matrix", tile.ModelMatrix)
                .SetUniform("view_matrix", view)
                .SetUniform("heightTex", 0)
                .SetUniform("paramTex", 1)
                .SetUniform("normalTex", 2)
                .SetUniform("eyePos", eyePos)
                .SetUniform("nEyePos", eyePosTileCoords)
                .SetUniform("boxparam", boxparam);
            this.vertexVBO.Bind(this.boundingBoxProgram.VariableLocation("vertex"));
            this.boxcoordVBO.Bind(this.boundingBoxProgram.VariableLocation("in_boxcoord"));
            this.indexVBO.Bind();
            GL.DrawElements(BeginMode.Triangles, this.indexVBO.Length, DrawElementsType.UnsignedInt, 0);
            Sampler.Unbind(TextureUnit.Texture0);
        }
示例#16
0
        public WorldRenderer(MainClass In, World For, float Aspect)
        {
            _for = For;
            _hmap = new HeightmapRenderer(this, _for.Terrain);
            FragmentShader fsimple = new FragmentShader("res/shader/simple.frag");
            FragmentShader fwater = new FragmentShader("res/shader/water.frag");
            FragmentShader fuwater = new FragmentShader("res/shader/underwater.frag");

            _simple = new ShaderProgram();
            _simple.AddFragShader(fsimple);
            GLUtil.PrintGLError("Simple");

            _underwater = new ShaderProgram();
            _underwater.AddFragShader(fuwater);
            GLUtil.PrintGLError("Underwater");

            _water = new ShaderProgram();
            _water.AddFragShader(fwater);
            GLUtil.PrintGLError("Water");

            _curr = _simple;

            _aspect = Aspect;
            _projectionMatrix = Matrix4.CreatePerspectiveFieldOfView((float)(FOV), _aspect, 0.01f, MAX_DEPTH);
            _modelview = Matrix4.CreateTranslation(-10f, -5f, -10f);
            _pos = new Vector3(10, 2, 10);
            _mviewstack = new Stack<Matrix4>();
            _in = In;
            _oldwidth = 0;
            _oldheight = 0;
        }
        public void AddCube(Matrix4 transform)
        {
            // Create VAO
            var vao = GL.GenVertexArray();
            GL.BindVertexArray(vao);

            // Create new buffer
            var buffer = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.ArrayBuffer, buffer);
            float[] vertices =
            {
                -1f, -1f, -1f, 1f, -1f, -1f, -1f, -1f, 1f, -1f, -1f, 1f, 1f, -1f, -1f, 1f, -1f, 1f, //Front face
                1f, 1f, -1f, -1f, 1f, -1f, -1f, 1f, 1f, 1f, 1f, -1f, -1f, 1f, 1f, 1f, 1f, 1f, //Back face
                1f, -1f, -1f, 1f, 1f, -1f, 1f, -1f, 1f, 1f, -1f, 1f, 1f, 1f, -1f, 1f, 1f, 1f, //Right face
                -1f, 1f, -1f, -1f, -1f, -1f, -1f, -1f, 1f, -1f, 1f, -1f, -1f, -1f, 1f, -1f, 1f, 1f, //Left face
                -1f, -1f, 1f, 1f, -1f, 1f, -1f, 1f, 1f, -1f, 1f, 1f, 1f, -1f, 1f, 1f, 1f, 1f, //Top face
                1f, -1f, -1f, -1f, -1f, -1f, -1f, 1f, -1f, 1f, -1f, -1f, -1f, 1f, -1f, 1f, 1f, -1f //Bottom face
            };
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(sizeof(float) * vertices.Length), vertices, BufferUsageHint.StaticDraw);

            var posAttribute = GL.GetAttribLocation(shaderProgram, "aVertexPos");
            GL.EnableVertexAttribArray(posAttribute);
            GL.VertexAttribPointer(posAttribute, 3, VertexAttribPointerType.Float, false, Vector3.SizeInBytes, 0);

            GL.BindVertexArray(0);

            objects.Add(new DebugObject(vao, vertices.Length / 3, transform));
        }
示例#18
0
        public override void Apply(ref Matrix4 transform)
        {
            if (this.Texture == null)
                throw new InvalidOperationException("TextureBrush.Texture is null.");

            Rectangle? source = this.Source;

            this.Grahpics.ShaderProgram = this.shader;
            this.shader.SetValue("vertTransform", ref transform);
            this.shader.SetValue("fragTexture", this.Texture);
            this.shader.SetValue("fragTextureWidth", this.Texture.Width);
            this.shader.SetValue("fragTextureHeight", this.Texture.Height);

            if (source != null)
            {
                this.shader.SetValue("fragTextureSourceX", source.Value.X);
                this.shader.SetValue("fragTextureSourceY", source.Value.Y);
                this.shader.SetValue("fragTextureSourceWidth", source.Value.Width);
                this.shader.SetValue("fragTextureSourceHeight", source.Value.Height);
            }
            else
            {
                this.shader.SetValue("fragTextureSourceX", 0);
                this.shader.SetValue("fragTextureSourceY", 0);
                this.shader.SetValue("fragTextureSourceWidth", this.Texture.Width);
                this.shader.SetValue("fragTextureSourceHeight", this.Texture.Height);
            }

            this.shader.SetValue("fragTint", ref this.tint);
        }
示例#19
0
        public static Matrix4 ToMatrix4(this float[] array)
        {
            Matrix4 matrix = new Matrix4();

            matrix.M11 = array[00];
            matrix.M12 = array[01];
            matrix.M13 = array[02];
            matrix.M14 = array[03];

            matrix.M21 = array[04];
            matrix.M22 = array[05];
            matrix.M23 = array[06];
            matrix.M24 = array[07];

            matrix.M31 = array[08];
            matrix.M32 = array[09];
            matrix.M33 = array[10];
            matrix.M34 = array[11];

            matrix.M41 = array[12];
            matrix.M42 = array[13];
            matrix.M43 = array[14];
            matrix.M44 = array[15];

            return matrix;
        }
示例#20
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="pos"></param>
 /// <param name="orient"></param>
 /// <param name="radius"></param>
 /// <param name="length"></param>
 public Capsule(Vector3 pos,Matrix4 orient,float radius, float length)
     : base((int)PrimitiveType.Capsule)
 {
     this.transform = new Transform(pos, orient);
     this.length = length;
     this.radius = radius;
 }
示例#21
0
 public Camera3D()
 {
     Matrix = Matrix4.Identity;
     rotation = Matrix4.Identity;
     translation = Matrix4.Identity;
     scale = Matrix4.Identity;
 }
示例#22
0
 public static void ReadMatrix4(this BinaryReader reader, ref Matrix4 matrix)
 {
     ReadVector4(reader, ref matrix.Row0);
     ReadVector4(reader, ref matrix.Row1);
     ReadVector4(reader, ref matrix.Row2);
     ReadVector4(reader, ref matrix.Row3);
 }
        public static void GetCurrentOrthogProjection(out bool isOrthog, out float left, out float right, out float bottom, out float top)
        {
            Matrix4 matrix = new Matrix4();
            GL.GetFloat(GetPName.ProjectionMatrix, out matrix.Row0.X);

			Helper.IsMatrixOrthogonal (out isOrthog, out left, out right, out bottom, out top, matrix);
        }
 public static Vector2 UnprojectPoint(Vector2 point, int screenWidth, int screenHeight, Matrix4 invProjection)
 {
     var x = (point.X * 2.0f / screenWidth) - 1.0f;
     var y = 1.0f - (point.Y * 2.0f / screenHeight);
     var p = new Vector3(x, y, -1.0f);
     return Vector3.Transform(p, invProjection).Xy;
 }
        public static void CreateBillboard(ref Vector3 objectPosition, ref Vector3 cameraPosition,
            ref Vector3 cameraUpVector, Vector3 cameraForwardVector, out Matrix4 result)
        {
            Vector3 look = cameraPosition - objectPosition;
            look = look.Normalize();

            Vector3 right = cameraUpVector.Cross(look).Normalize();
            Vector3 up = look.Cross(right).Normalize();
            //Matrix4 mat = Matrix4.LookAt(cameraPosition, cameraForwardVector, cameraUpVector);
            //Vector3 right = new Vector3(mat.M11, mat.M21, mat.M31);
            //right = right.Normalize();

            //Vector3 up = new Vector3(mat.M12, mat.M22, mat.M32);
            //up = up.Normalize();

            result.M11 = right.X;
            result.M12 = right.Y;
            result.M13 = right.Z;
            result.M14 = 0;
            result.M21 = up.X;
            result.M22 = up.Y;
            result.M23 = up.Z;
            result.M24 = 0;
            result.M31 = look.X;
            result.M32 = look.Y;
            result.M33 = look.Z;
            result.M34 = 0;
            result.M41 = objectPosition.X;
            result.M42 = objectPosition.Y;
            result.M43 = objectPosition.Z;
            result.M44 = 1;
        }
示例#26
0
文件: OpenGLControl.cs 项目: GNZ/CG
        public void OpenGLControl_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            switch (e.KeyChar)
            {
                case 'w':
                    camera.position.growTheta();
                    break;
                case 's':
                    camera.position.shrinkTheta();
                    break;
                case 'd':
                    camera.position.growPhi();
                    break;
                case 'a':
                    camera.position.shrinkPhi();
                    break;
                case '-':
                    camera.position.growRadio();
                    break;
                case '+':
                    camera.position.shrinkRadio();
                    break;
            }

            zoomMatrix = camera.lookAt();
            this.Invalidate();
        }
示例#27
0
        public void Render(GameClient gameClient, RenderInfo renderInfo)
        {
            _currentFrameTime = GameTime.Now();

            GL.ClearColor(0.5f, 0.6f, 0.9f, 1f);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.CullFace);

            var offset = gameClient.PositionData.Placement.Pos - EntityPos.Origin;
            SetProjectionMatrix(renderInfo);

            _modelViewMatrix = Matrix4.Identity
                * Matrix4.CreateTranslation((float)-offset.X, (float)-offset.Y - gameClient.PhysicsValues.PlayerEyeHeight, (float)-offset.Z)
                * Matrix4.CreateRotationY((float)-gameClient.PositionData.Placement.Orientation.Horizontal)
                * Matrix4.CreateRotationX((float)gameClient.PositionData.Placement.Orientation.Vertical);

            _textureAtlas.Bind();

            RenderHighlightedFace(gameClient);

            RenderBlocks(gameClient);

            RenderEntities(gameClient);

            _outlineRenderer.RenderOutlines(renderInfo);
        }
示例#28
0
 /// 平行移動の代入
 public static void SetTranslate( ref Matrix4 mtx, Vector3 pos )
 {
     mtx.M41 = pos.X;
     mtx.M42 = pos.Y;
     mtx.M43 = pos.Z;
     mtx.M44 = 1.0f;
 }
示例#29
0
            /// 視線方向を向く(upベクトルがY軸プラス方向に固定版)
            public static void LookTrgVec( ref Matrix4 mtx, Vector3 lookVec )
            {
                Vector3 upVec = new Vector3( 0.0f, 1.0f, 0.0f );

                if( lookVec.X == 0.0f && lookVec.Z == 0.0f){
                lookVec.Z = 1.0f;
                }
                // Z軸のセット
                lookVec = lookVec.Normalize();
                mtx.M31 = lookVec.X;
                mtx.M32 = lookVec.Y;
                mtx.M33 = lookVec.Z;
                mtx.M34 = 0;

                // X軸のセット
                Vector3 calVecX = Common.VectorUtil.Cross2( upVec, lookVec );
                calVecX = calVecX.Normalize();
                mtx.M11 = calVecX.X;
                mtx.M12 = calVecX.Y;
                mtx.M13 = calVecX.Z;
                mtx.M14 = 0;

                // Y軸のセット
                Vector3 calVecY = VectorUtil.Cross2( lookVec, calVecX );
                calVecY = calVecY.Normalize();
                mtx.M21 = calVecY.X;
                mtx.M22 = calVecY.Y;
                mtx.M23 = calVecY.Z;
                mtx.M24 = 0;
            }
示例#30
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
            };
        }
示例#31
0
 public void applyPaintTransform(Matrix4 transform)
 {
     transform.translate(this.paintOffset.dx, this.paintOffset.dy);
 }
示例#32
0
 public TransFormInfo(Matrix4 r, float z, int dw, int dh, float sq, Vector3 cm)
 {
     resmat = r; znear = z; dwidth = dw; dheight = dh; sqlylimit = sq; campos = cm;
 }
示例#33
0
 public void Translate(float x, float y, float z)
 {
     mMatrix = Matrix4.CreateTranslation(x, y, z) * mMatrix;
 }
示例#34
0
        public void Rotate(float degree, Vector3 axis)
        {
            var rad = degree * Math.PI / 180;

            mMatrix = Matrix4.CreateFromAxisAngle(axis, (float)rad) * mMatrix;
        }
示例#35
0
 public void PopMatrix()
 {
     mMatrix = Matrixs.Pop();
 }
示例#36
0
 /// <summary>モデル行列を初期化する。</summary>
 public void IdentityMatrix()
 {
     mMatrix = Matrix4.Identity;
 }
示例#37
0
 /// <summary>
 /// Creates a new raycast based wheel shape.
 /// </summary>
 /// <param name="graphicalRadius">Graphical radius of the wheel.
 /// This is not used for simulation.  It is only used in
 /// determining aesthetic properties of a vehicle wheel,
 /// like position and orientation.</param>
 /// <param name="localGraphicTransform">Local graphic transform of the wheel shape.
 /// This transform is applied first when creating the shape's worldTransform.</param>
 public RaycastWheelShape(float graphicalRadius, Matrix4 localGraphicTransform)
 {
     Radius = graphicalRadius;
     LocalGraphicTransform = localGraphicTransform;
 }
示例#38
0
        static void Main(string[] args)
        {
            Matrix4 test = Matrix4.Identity;

            new GameWindow().Run(60);
        }
示例#39
0
 public void StartUsing(ref Matrix4 a_m4Model)
 {
     GL.UseProgram(m_iShaderProgramHandle);
     GL.UniformMatrix4(m_aiShaderMatrixLocations[2], false, ref a_m4Model);
 }
示例#40
0
 public TransFormInfo(Matrix4 r, float z, int dw, int dh, float zm)
 {
     resmat = r; znear = z; dwidth = dw; dheight = dh; zoom = zm;
 }
示例#41
0
        /// <summary>   Constructor. </summary>
        /// <param name="a_szVertShaderFile">   The Vertex shader file. </param>
        /// <param name="a_szFragShaderFile">   The fragment shader file. </param>
        //public GLEffect(string a_szVertShaderFile, string a_szFragShaderFile)
        //{
        //    // Load Shader source files:
        //    string szVertShaderSource = "";
        //    if (System.IO.File.Exists(a_szVertShaderFile))
        //    {
        //        System.IO.StreamReader oVertFile = new System.IO.StreamReader(a_szVertShaderFile);
        //        szVertShaderSource = oVertFile.ReadToEnd();
        //        oVertFile.Close();
        //    }
        //    else
        //    {
        //        logger.Error("Could not load vertex shader file: " + a_szVertShaderFile);
        //        // Set a default shader in the hopes that it will work. its better than nothing *shrug*
        //        switch (OpenTKUtilities.Instance.SupportedOpenGLVersion)
        //        {
        //            case OpenTKUtilities.GLVersion.OpenGL2X:
        //                szVertShaderSource = m_szVertexShaderVer120;
        //                break;
        //            default:
        //                szVertShaderSource = m_szVertexShaderVer150;
        //                break;
        //        }
        //    }

        //    string szFragShaderSource = "";
        //    if (System.IO.File.Exists(a_szFragShaderFile))
        //    {
        //        System.IO.StreamReader oFragFile = new System.IO.StreamReader(a_szFragShaderFile);
        //        szFragShaderSource = oFragFile.ReadToEnd();
        //        oFragFile.Close();
        //    }
        //    else
        //    {
        //        logger.Error("Could not load fragment shader file: " + a_szFragShaderFile);
        //        // Set a default shader in the hopes that it will work. its better than nothing *shrug*
        //        switch (OpenTKUtilities.Instance.SupportedOpenGLVersion)
        //        {
        //            case OpenTKUtilities.GLVersion.OpenGL2X:
        //                szFragShaderSource = m_szPixelShaderVer120;
        //                break;
        //            default:
        //                szFragShaderSource = m_szPixelShaderVer150;
        //                break;
        //        }
        //    }

        //    int iShaderError = 1;

        //    int iGLVertexShader = GL.CreateShader(ShaderType.VertexShader);    // Get a shader handle from open GL
        //    GL.ShaderSource(iGLVertexShader, szVertShaderSource);                  // Let OpenGL know about the source code for the shandle provided.
        //    GL.CompileShader(iGLVertexShader);                                 // Tell OpenGL to compile the shaders gened above.

        //    GL.GetShader(iGLVertexShader, ShaderParameter.CompileStatus, out iShaderError);
        //    if (iShaderError != 1)
        //    {
        //        logger.Error("Error " + iShaderError.ToString() + " Compiling Vertex Shader: " + GL.GetShaderInfoLog(iGLVertexShader)); // Log Result!
        //        iShaderError = 1;
        //    }

        //    int iGLPixelShader = GL.CreateShader(ShaderType.FragmentShader);    // Get a shader handle from open GL
        //    GL.ShaderSource(iGLPixelShader, szFragShaderSource);                     // Let OpenGL know about the source code for the shandle provided.
        //    GL.CompileShader(iGLPixelShader);                                   // Tell OpenGL to compile the shaders gened above.

        //    GL.GetShader(iGLPixelShader, ShaderParameter.CompileStatus, out iShaderError);
        //    if (iShaderError != 1)
        //    {
        //        logger.Error("Error " + iShaderError.ToString() + " Compiling Fragment/Pixel Shader: " + GL.GetShaderInfoLog(iGLPixelShader)); // Log Result!
        //        iShaderError = 1;
        //    }

        //    m_iShaderProgramHandle = GL.CreateProgram();                        // Tell OpenGL to creat a handle for a complete shader program (composed of the above two shaders).
        //    GL.AttachShader(m_iShaderProgramHandle, iGLVertexShader);           // Attache our Vertex shader to the program.
        //    GL.AttachShader(m_iShaderProgramHandle, iGLPixelShader);            // Attache our Pixel (fragment) shader to our program.
        //    // Note the below 4 function calls bind our vertex components in C# to our OpenGL shader.
        //    GL.BindAttribLocation(m_iShaderProgramHandle, 0, "VertexPosition"); // Binds the vertex position Variable in the shader program to the index 0.
        //    GL.BindAttribLocation(m_iShaderProgramHandle, 1, "VertexColour");   // Binds the vertex color Variable in the shader program to the index 1.
        //    GL.BindAttribLocation(m_iShaderProgramHandle, 2, "UVCord");         // Binds the vertex UC coords Variable in the shader program to the index 2.
        //    if (OpenTKUtilities.Instance.SupportedOpenGLVersion != OpenTKUtilities.GLVersion.OpenGL2X)
        //    {
        //        GL.BindFragDataLocation(m_iShaderProgramHandle, 0, "FragColor");    // Binds the Pixel (fragment) color Variable to the index 3, only for GL3.0 or greater!!
        //    }
        //    GL.LinkProgram(m_iShaderProgramHandle);                             // Compiles the Shader into a complete program ready to be run on the GPU. (think linker stage in normal compiling).

        //    GL.GetProgram(m_iShaderProgramHandle, ProgramParameter.ValidateStatus, out iShaderError);
        //    if (iShaderError != 1 || iShaderError != 0)
        //    {
        //        logger.Error("Error " + iShaderError.ToString() + " Creating Shader Program: " + GL.GetShaderInfoLog(m_iShaderProgramHandle)); // Log Result!
        //        iShaderError = 1;
        //    }

        //    // The Following Bind our Projection, view (camera) and model Matricies in c# to the corosponding vars in the shader program
        //    // it is what allows us to update a matrix in c# and have the GPU do all the calculations for Transformations on next render.
        //    m_aiShaderMatrixLocations = new int[3];     // create memory.
        //    m_aiShaderMatrixLocations[0] = GL.GetUniformLocation(m_iShaderProgramHandle, "ProjectionMatrix");
        //    m_aiShaderMatrixLocations[1] = GL.GetUniformLocation(m_iShaderProgramHandle, "ViewMatrix");
        //    m_aiShaderMatrixLocations[2] = GL.GetUniformLocation(m_iShaderProgramHandle, "ModelMatrix");
        //    ErrorCode m_eGLError = GL.GetError();
        //    if (m_eGLError != ErrorCode.NoError)
        //    {
        //        logger.Info("OpenGL Bind Matricies to Shader Code: " + m_eGLError.ToString());
        //    }
        //    // This tells OpenGL to delete the shader objects.
        //    // Note that OpenGL wont delete them until all shader programs currently useing them are deleted also.
        //    // Deleteing them now lets OpenGL know that we don't want to use tem again in a different shader (if we do we will need to re compile them).
        //    // Allowing OpenGL to clean up after us. i.e. we do it now so we don't forget later ;)
        //    GL.DeleteShader(iGLVertexShader);
        //    GL.DeleteShader(iGLPixelShader);
        //}

        ///// <summary>
        ///// Creates the default shader for openGL 2.1 or higher
        ///// </summary>
        //void CreateDefaultVer120()
        //{
        //    int iShaderError = 1;

        //    int iGLVertexShader = GL.CreateShader(ShaderType.VertexShader);    // Get a shader handle from open GL
        //    GL.ShaderSource(iGLVertexShader, m_szVertexShaderVer120);                  // Let OpenGL know about the source code for the shandle provided.
        //    GL.CompileShader(iGLVertexShader);                                 // Tell OpenGL to compile the shaders gened above.

        //    GL.GetShader(iGLVertexShader, ShaderParameter.CompileStatus, out iShaderError);
        //    if (iShaderError != 1)
        //    {
        //        logger.Error("Error " + iShaderError.ToString() + " Compiling Vertex Shader: " + GL.GetShaderInfoLog(iGLVertexShader)); // Log Result!
        //        iShaderError = 1;
        //    }

        //    int iGLPixelShader = GL.CreateShader(ShaderType.FragmentShader);    // Get a shader handle from open GL
        //    GL.ShaderSource(iGLPixelShader, m_szPixelShaderVer120);                     // Let OpenGL know about the source code for the shandle provided.
        //    GL.CompileShader(iGLPixelShader);                                   // Tell OpenGL to compile the shaders gened above.

        //    GL.GetShader(iGLPixelShader, ShaderParameter.CompileStatus, out iShaderError);
        //    if (iShaderError != 1)
        //    {
        //        logger.Error("Error " + iShaderError.ToString() + " Compiling Fragment/Pixel Shader: " + GL.GetShaderInfoLog(iGLPixelShader)); // Log Result!
        //        iShaderError = 1;
        //    }

        //    m_iShaderProgramHandle = GL.CreateProgram();                        // Tell OpenGL to creat a handle for a complete shader program (composed of the above two shaders).
        //    GL.AttachShader(m_iShaderProgramHandle, iGLVertexShader);           // Attache our Vertex shader to the program.
        //    GL.AttachShader(m_iShaderProgramHandle, iGLPixelShader);            // Attache our Pixel (fragment) shader to our program.

        //    // Note the below 4 function calls bind our vertex components in C# to our OpenGL shader.
        //    GL.BindAttribLocation(m_iShaderProgramHandle, 0, "VertexPosition"); // Binds the vertex position Variable in the shader program to the index 0.
        //    GL.BindAttribLocation(m_iShaderProgramHandle, 1, "VertexColour");   // Binds the vertex color Variable in the shader program to the index 1.
        //    GL.BindAttribLocation(m_iShaderProgramHandle, 2, "UVCord");         // Binds the vertex UC coords Variable in the shader program to the index 2.
        //    GL.LinkProgram(m_iShaderProgramHandle);                             // Compiles the Shader into a complete program ready to be run on the GPU. (think linker stage in normal compiling).

        //    GL.GetProgram(m_iShaderProgramHandle, ProgramParameter.ValidateStatus, out iShaderError);
        //    if (iShaderError != 1)
        //    {
        //        logger.Error("Error " + iShaderError.ToString() + " Creating Shader Program: " + GL.GetShaderInfoLog(m_iShaderProgramHandle)); // Log Result!
        //        iShaderError = 1;
        //    }

        //    logger.Info("OpenGL Pre Bind Matricies to Shader Code: " + GL.GetError().ToString());
        //    // The Following Bind our Projection, view (camera) and model Matricies in c# to the corosponding vars in the shader program
        //    // it is what allows us to update a matrix in c# and have the GPU do all the calculations for Transformations on next render.
        //    m_aiShaderMatrixLocations = new int[3];     // create memory.
        //    m_aiShaderMatrixLocations[0] = GL.GetUniformLocation(m_iShaderProgramHandle, "ProjectionMatrix");
        //    m_aiShaderMatrixLocations[1] = GL.GetUniformLocation(m_iShaderProgramHandle, "ViewMatrix");
        //    m_aiShaderMatrixLocations[2] = GL.GetUniformLocation(m_iShaderProgramHandle, "ModelMatrix");
        //    m_eGLError = GL.GetError();
        //    if (m_eGLError != ErrorCode.NoError)
        //    {
        //        logger.Info("OpenGL Bind Matricies to Shader Code: " + m_eGLError.ToString());
        //    }
        //    // This tells OpenGL to delete the shader objects.
        //    // Note that OpenGL wont delete them until all shader programs currently useing them are deleted also.
        //    // Deleteing them now lets OpenGL know that we don't want to use tem again in a different shader (if we do we will need to re compile them).
        //    // Allowing OpenGL to clean up after us. i.e. we do it now so we don't forget later ;)
        //    GL.DeleteShader(iGLVertexShader);
        //    GL.DeleteShader(iGLPixelShader);
        //}

        ///// <summary>
        ///// Creates the default Shader for openGL 3.2 or higher.
        ///// </summary>
        //void CreateDefaultVer150()
        //{
        //    int iShaderError = 1;

        //    int iGLVertexShader = GL.CreateShader(ShaderType.VertexShader);    // Get a shader handle from open GL
        //    GL.ShaderSource(iGLVertexShader, m_szVertexShaderVer150);          // Let OpenGL know about the source code for the shandle provided.
        //    GL.CompileShader(iGLVertexShader);                                 // Tell OpenGL to compile the shaders gened above.

        //    GL.GetShader(iGLVertexShader, ShaderParameter.CompileStatus, out iShaderError);
        //    if (iShaderError != 1)
        //    {
        //        logger.Error("Error " + iShaderError.ToString() + " Compiling Vertex Shader: " + GL.GetShaderInfoLog(iGLVertexShader)); // Log Result!
        //        iShaderError = 1;
        //    }

        //    int iGLPixelShader = GL.CreateShader(ShaderType.FragmentShader);    // Get a shader handle from open GL
        //    GL.ShaderSource(iGLPixelShader, m_szPixelShaderVer150);                     // Let OpenGL know about the source code for the shandle provided.
        //    GL.CompileShader(iGLPixelShader);                                   // Tell OpenGL to compile the shaders gened above.

        //    GL.GetShader(iGLPixelShader, ShaderParameter.CompileStatus, out iShaderError);
        //    if (iShaderError != 1)
        //    {
        //        logger.Error("Error " + iShaderError.ToString() + " Compiling Fragment/Pixel Shader: " + GL.GetShaderInfoLog(iGLPixelShader)); // Log Result!
        //        iShaderError = 1;
        //    }

        //    m_iShaderProgramHandle = GL.CreateProgram();                        // Tell OpenGL to creat a handle for a complete shader program (composed of the above two shaders).
        //    GL.AttachShader(m_iShaderProgramHandle, iGLVertexShader);           // Attache our Vertex shader to the program.
        //    GL.AttachShader(m_iShaderProgramHandle, iGLPixelShader);            // Attache our Pixel (fragment) shader to our program.
        //    // Note the below 4 function calls bind our vertex components in C# to our OpenGL shader.
        //    GL.BindAttribLocation(m_iShaderProgramHandle, 0, "VertexPosition"); // Binds the vertex position Variable in the shader program to the index 0.
        //    GL.BindAttribLocation(m_iShaderProgramHandle, 1, "VertexColour");   // Binds the vertex color Variable in the shader program to the index 1.
        //    GL.BindAttribLocation(m_iShaderProgramHandle, 2, "UVCord");         // Binds the vertex UC coords Variable in the shader program to the index 2.
        //    GL.BindFragDataLocation(m_iShaderProgramHandle, 0, "FragColor");    // Binds the Pixel (fragment) color Variable to the index 3.
        //    GL.LinkProgram(m_iShaderProgramHandle);                             // Compiles the Shader into a complete program ready to be run on the GPU. (think linker stage in normal compiling).

        //    GL.GetProgram(m_iShaderProgramHandle, ProgramParameter.ValidateStatus, out iShaderError);
        //    if (iShaderError != 1)
        //    {
        //        logger.Error("Error " + iShaderError.ToString() + " Creating Shader Program: " + GL.GetShaderInfoLog(m_iShaderProgramHandle)); // Log Result!
        //        iShaderError = 1;
        //    }

        //    // The Following Bind our Projection, view (camera) and model Matricies in c# to the corosponding vars in the shader program
        //    // it is what allows us to update a matrix in c# and have the GPU do all the calculations for Transformations on next render.
        //    m_aiShaderMatrixLocations = new int[3];     // create memory.
        //    m_aiShaderMatrixLocations[0] = GL.GetUniformLocation(m_iShaderProgramHandle, "ProjectionMatrix");
        //    m_aiShaderMatrixLocations[1] = GL.GetUniformLocation(m_iShaderProgramHandle, "ViewMatrix");
        //    m_aiShaderMatrixLocations[2] = GL.GetUniformLocation(m_iShaderProgramHandle, "ModelMatrix");

        //    m_eGLError = GL.GetError();
        //    if (m_eGLError != ErrorCode.NoError)
        //    {
        //        logger.Info("OpenGL Bind Matricies to Shader Code: " + m_eGLError.ToString());
        //    }
        //    // This tells OpenGL to delete the shader objects.
        //    // Note that OpenGL wont delete them until all shader programs currently useing them are deleted also.
        //    // Deleteing them now lets OpenGL know that we don't want to use tem again in a different shader (if we do we will need to re compile them).
        //    // Allowing OpenGL to clean up after us. i.e. we do it now so we don't forget later ;)
        //    GL.DeleteShader(iGLVertexShader);
        //    GL.DeleteShader(iGLPixelShader);
        //}


        public void SetProjectionMatrix(ref Matrix4 a_m4Projection)
        {
            GL.UseProgram(m_iShaderProgramHandle);
            GL.UniformMatrix4(m_aiShaderMatrixLocations[0], false, ref a_m4Projection);
        }
示例#42
0
 public void SetViewMatrix(ref Matrix4 a_m4View)
 {
     GL.UseProgram(m_iShaderProgramHandle);
     GL.UniformMatrix4(m_aiShaderMatrixLocations[1], false, ref a_m4View);
 }
示例#43
0
 public void Scale(float x, float y, float z)
 {
     mMatrix = Matrix4CreateScale(x, y, z) * mMatrix;
 }
示例#44
0
 public override void applyPaintTransform(RenderObject child, Matrix4 transform)
 {
     D.assert(() => { throw new UIWidgetsError(this.GetType() + " does not implement applyPaintTransform."); });
 }
示例#45
0
        public Matrix4 ApplyGeometricTransformations(RenderingContext rc, ComposedShader shader, SceneGraphNode context)
        {
            RefreshDefaultUniforms(shader);
            //RefreshMaterialUniforms();

            if (shader.IsTessellator)
            {
                RefreshTessUniforms(shader);
            }


            Matrix4 view = Matrix4.LookAt(new Vector3(4, 3, 3), // Camera is at (4,3,3), in World Space
                                          new Vector3(0, 0, 0), // and looks at the origin
                                          new Vector3(0, 1, 0)  // Head is up (set to 0,-1,0 to look upside-down)
                                          );

            Matrix4 model; // applied transformation hierarchy

            SceneGraphNode transform_context = context == null ? this : context;

            List <Transform> transformationHierarchy = transform_context
                                                       .AscendantByType <Transform>()
                                                       .Select(t => (Transform)t)
                                                       .Where(t => t.Hidden == false)
                                                       .ToList();

            Matrix4 modelview = Matrix4.Identity;// * rc.matricies.worldview;

            // using Def_Use/Figure02.1Hut.x3d Cone and Cylinder
            Vector3 x3dScale = new Vector3(0.06f, 0.06f, 0.06f); // scaling down to conform with X3D standard (note this was done manually and might need tweaking)

            //x3dScale = Vector3.One;

            Quaternion modelrotation      = Quaternion.Identity;
            Matrix4    modelLocalRotation = Matrix4.Identity;


            //if (rc.cam.OrbitLocalOrientation != Vector2.Zero)
            //{
            //    // Center of Rotation based on center of bounding box
            //    Quaternion qLocal = QuaternionExtensions.EulerToQuat(0, -rc.cam.OrbitLocalOrientation.X, -rc.cam.OrbitLocalOrientation.Y);
            //    Quaternion qAdjust = QuaternionExtensions.EulerToQuat(MathHelpers.PIOver2, 0.0f, 0.0f);

            //    Matrix4 mat4CenterOfRotation = Matrix4.CreateTranslation(centerOfRotation);
            //    Matrix4 origin = Matrix4.CreateTranslation(new Vector3(0, 0, 0));

            //    modelLocalRotation = mat4CenterOfRotation * Matrix4.CreateFromQuaternion(qLocal) * Matrix4.CreateFromQuaternion(qAdjust);
            //}

            //const float bbscale = 0.0329999961f;

            Vector3 centerOffset = Vector3.Zero;

            foreach (Transform transform in transformationHierarchy)
            {
                modelview = SceneEntity.ApplyX3DTransform(centerOffset,
                                                          Vector3.Zero,
                                                          transform.Scale,
                                                          Vector3.Zero,
                                                          transform.Translation, // * x3dScale,
                                                          modelview);

                //modelview *= Matrix4.CreateTranslation(transform.Translation * x3dScale);

                //modelrotation = new Quaternion(transform.Rotation.X, transform.Rotation.Y, transform.Rotation.Z, transform.Rotation.W);
                //modelrotations *= Matrix4.CreateFromQuaternion(modelrotation);

                //modelrotations *= MathHelpers.CreateRotation(ref modelrotation);
            }

            //Vector3 center = modelview.ExtractTranslation();
            //Vector3 centerOffsetVector = center + (bbox.Maximum - bbox.Minimum);
            //Matrix4 centerOffset = Matrix4.CreateTranslation(centerOffsetVector);



            model = modelview;

            Matrix4 cameraTransl = Matrix4.CreateTranslation(rc.cam.Position);

            Quaternion q = rc.cam.Orientation;

            Matrix4 cameraRot;

            cameraRot = Matrix4.CreateFromQuaternion(q); // cameraRot = MathHelpers.CreateRotation(ref q);


            Matrix4 MVP = ((modelLocalRotation * model) * cameraTransl) * cameraRot; // position and orient the Shape relative to the world and camera



            //shader.SetFieldValue("size", new Vector3(bbox.Width, bbox.Height, bbox.Depth) * bbscale);
            shader.SetFieldValue("modelview", ref MVP);                              //GL.UniformMatrix4(uniformModelview, false, ref rc.matricies.modelview);
            shader.SetFieldValue("projection", ref rc.matricies.projection);
            shader.SetFieldValue("camscale", rc.cam.Scale.X);                        //GL.Uniform1(uniformCameraScale, rc.cam.Scale.X);
            shader.SetFieldValue("X3DScale", rc.matricies.Scale);                    //GL.Uniform3(uniformX3DScale, rc.matricies.Scale);
            shader.SetFieldValue("coloringEnabled", this.coloring ? 1 : 0);          //GL.Uniform1(uniforms.a_coloringEnabled, 0);
            shader.SetFieldValue("texturingEnabled", this.texturingEnabled ? 1 : 0); //GL.Uniform1(uniforms.a_texturingEnabled, this.texturingEnabled ? 1 : 0);
            shader.SetFieldValue("lightingEnabled", 1);

            if (shader.IsBuiltIn == false)
            {
                shader.ApplyFieldsAsUniforms(rc);
            }

            return(MVP);
        }
示例#46
0
 public void SetTop(ref Matrix4 matrix)
 {
     stack[stackIndex] = matrix;
     device.SetTransform(matrixType, ref stack[stackIndex]);
 }
示例#47
0
 public Matrix4 OpenTk()
 {
     return(Matrix4.Transpose(_openTk1));
 }
示例#48
0
 public void MultiplyTop(ref Matrix4 matrix)
 {
     stack[stackIndex] = matrix * stack[stackIndex];
     device.SetTransform(matrixType, ref stack[stackIndex]);
 }
示例#49
0
        public static void OnResize(int width, int height)
        {
            UI.Width  = width;
            UI.Height = height;

            UIProjectionMatrix = Matrix4.CreateTranslation(new Vector3(-UI.Width / 2, -UI.Height / 2, 0)) * Matrix4.CreateOrthographic(UI.Width, UI.Height, 0, 1000);
            Shaders.UpdateUIProjectionMatrix(UIProjectionMatrix);

            if (UIWindow == null)
            {
                return;
            }
            UIWindow.Size = new Point(UI.Width, UI.Height);
            UIWindow.OnResize();
        }
示例#50
0
 public unsafe override void MultiplyMatrix(ref Matrix4 matrix)
 {
     curStack.MultiplyTop(ref matrix);
 }
示例#51
0
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            if (this.DesignMode)
                return;

            if (area.LocationMiddle.Lat == 0 && area.LocationMiddle.Lng == 0)
                return;

            try
            {
                base.OnPaint(e);
            }
            catch
            {
                return;
            }

            double heightscale = (step/90.0)*1;

            float yawradians = (float) (Math.PI*(rpy.Z*1)/180.0f);

            //radians = 0;

            float mouseY = (float) step/10f;

            cameraX = center.Lng; // -Math.Sin(yawradians) * mouseY;     // multiplying by mouseY makes the
            cameraY = center.Lat; // -Math.Cos(yawradians) * mouseY;    // camera get closer/farther away with mouseY
            cameraZ = (center.Alt < srtm.getAltitude(center.Lat, center.Lng).alt)
                ? (srtm.getAltitude(center.Lat, center.Lng).alt + 1)*heightscale
                : center.Alt*heightscale; // (srtm.getAltitude(lookZ, lookX, 20) + 100) * heighscale;

            lookX = center.Lng + Math.Sin(yawradians)*mouseY;
            lookY = center.Lat + Math.Cos(yawradians)*mouseY;
            lookZ = cameraZ;

            // cameraZ += 0.04;

            GMapProvider type = GMap.NET.MapProviders.GoogleSatelliteMapProvider.Instance;
            PureProjection prj = type.Projection;

            int size = (int) (cameraZ*150000);

            // in front
            PointLatLngAlt leftf = center.newpos(rpy.Z, size);
            // behind
            PointLatLngAlt rightf = center.newpos(rpy.Z, 50);
            // left : 90 allows for 180 degree viewing angle
            PointLatLngAlt left = center.newpos(rpy.Z - 90, size);
            // right
            PointLatLngAlt right = center.newpos(rpy.Z + 90, size);

            double maxlat = Math.Max(left.Lat, Math.Max(right.Lat, Math.Max(leftf.Lat, rightf.Lat)));
            double minlat = Math.Min(left.Lat, Math.Min(right.Lat, Math.Min(leftf.Lat, rightf.Lat)));

            double maxlng = Math.Max(left.Lng, Math.Max(right.Lng, Math.Max(leftf.Lng, rightf.Lng)));
            double minlng = Math.Min(left.Lng, Math.Min(right.Lng, Math.Min(leftf.Lng, rightf.Lng)));

            // if (Math.Abs(area.Lat - maxlat) < 0.001)
            {
            }
            // else
            {
                area = RectLatLng.FromLTRB(minlng, maxlat, maxlng, minlat);
            }

            GPoint topLeftPx = prj.FromLatLngToPixel(area.LocationTopLeft, zoom);
            GPoint rightButtomPx = prj.FromLatLngToPixel(area.Bottom, area.Right, zoom);
            GPoint pxDelta = new GPoint(rightButtomPx.X - topLeftPx.X, rightButtomPx.Y - topLeftPx.Y);

            zoom = 21;
            pxDelta.X = 9999;

            int otherzoomlevel = 12;

            // zoom based on pixel density
            while (pxDelta.X > this.Width)
            {
                zoom--;

                // current area
                topLeftPx = prj.FromLatLngToPixel(area.LocationTopLeft, zoom);
                rightButtomPx = prj.FromLatLngToPixel(area.Bottom, area.Right, zoom);
                pxDelta = new GPoint(rightButtomPx.X - topLeftPx.X, rightButtomPx.Y - topLeftPx.Y);
            }

            otherzoomlevel = zoom - 4;

            //Console.WriteLine("zoom {0}", zoom);

            // update once per seconds - we only read from disk, so need to let cahce settle
            if (lastrefresh.AddSeconds(0.5) < DateTime.Now)
            {
                // get tiles - bg
                core.Provider = type;
                core.Position = LocationCenter;

                // get zoom 10
                core.Zoom = otherzoomlevel;
                core.OnMapSizeChanged(this.Width, this.Height);

                // get actual current zoom
                core.Zoom = zoom;
                core.OnMapSizeChanged(this.Width, this.Height);

                lastrefresh = DateTime.Now;
            }
            else
            {
                //return;
            }

            float screenscale = this.Width/(float) this.Height;

            if(!Context.IsCurrent)
                MakeCurrent();

            GL.MatrixMode(MatrixMode.Projection);

            OpenTK.Matrix4 projection = OpenTK.Matrix4.CreatePerspectiveFieldOfView((float)(120*MathHelper.deg2rad), screenscale, 0.00001f,
                (float) step*20000);
            GL.LoadMatrix(ref projection);

            Matrix4 modelview = Matrix4.LookAt((float) cameraX, (float) cameraY, (float) cameraZ, (float) lookX,
                (float) lookY, (float) lookZ, 0, 0, 1);
            GL.MatrixMode(MatrixMode.Modelview);

            // roll
            modelview = Matrix4.Mult(modelview, Matrix4.CreateRotationZ((float)(rpy.X*MathHelper.deg2rad)));
            // pitch
            modelview = Matrix4.Mult(modelview, Matrix4.CreateRotationX((float)((rpy.Y - 15)*-MathHelper.deg2rad)));

            GL.LoadMatrix(ref modelview);

            GL.ClearColor(Color.CornflowerBlue);

            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit | ClearBufferMask.AccumBufferBit);

            GL.LightModel(LightModelParameter.LightModelAmbient, new float[] {1f, 1f, 1f, 1f});

            //  GL.Disable(EnableCap.Fog);
            GL.Enable(EnableCap.Fog);
            //GL.Enable(EnableCap.Lighting);
            //GL.Enable(EnableCap.Light0);

            GL.Fog(FogParameter.FogColor, new float[] {100/255.0f, 149/255.0f, 237/255.0f, 1f});
            //GL.Fog(FogParameter.FogDensity,0.1f);
            GL.Fog(FogParameter.FogMode, (int) FogMode.Linear);
            GL.Fog(FogParameter.FogStart, (float) step*40);
            GL.Fog(FogParameter.FogEnd, (float) (step*50));

//            GL.Enable(EnableCap.DepthTest);
            GL.DepthFunc(DepthFunction.Always);

            /*
            GL.Begin(BeginMode.LineStrip);

            GL.Color3(Color.White);
            GL.Vertex3(0, 0, 0);

            //GL.Color3(Color.Red);
            GL.Vertex3(area.Bottom, 0, area.Left);

            //GL.Color3(Color.Yellow);
            GL.Vertex3(lookX, lookY, lookZ);

            //GL.Color3(Color.Green);
            GL.Vertex3(cameraX, cameraY, cameraZ);

            GL.End();
             */
            /*
            GL.PointSize(10);
            GL.Color4(Color.Yellow);
            GL.LineWidth(5);
           

            GL.Begin(PrimitiveType.LineStrip);
 
            //GL.Vertex3(new Vector3((float)center.Lng,(float)center.Lat,(float)(center.Alt * heightscale)));
            //GL.Vertex3(new Vector3(0, 0, 0));
            //GL.Vertex3(new Vector3((float)cameraX, (float)cameraY, (float)cameraZ));
            //GL.Color3(Color.Green);
            //GL.Vertex3(new Vector3((float)lookX, (float)lookY, (float)lookZ));

            GL.Vertex3(area.LocationTopLeft.Lng, area.LocationTopLeft.Lat, (float)cameraZ);
            GL.Vertex3(area.LocationTopLeft.Lng, area.LocationRightBottom.Lat, (float)cameraZ);
            GL.Vertex3(area.LocationRightBottom.Lng, area.LocationRightBottom.Lat, (float)cameraZ);
            GL.Vertex3(area.LocationRightBottom.Lng, area.LocationTopLeft.Lat, (float)cameraZ);
            GL.Vertex3(area.LocationTopLeft.Lng, area.LocationTopLeft.Lat, (float)cameraZ);

            GL.End();
            */
            GL.Finish();

            GL.PointSize((float) (step*1));
            GL.Color3(Color.Blue);
            GL.Begin(PrimitiveType.Points);
            GL.Vertex3(new Vector3((float) center.Lng, (float) center.Lat, (float) cameraZ));
            GL.End();


            //GL.ClampColor(ClampColorTarget.ClampReadColor, ClampColorMode.True);
            /*
            GL.Enable(EnableCap.Blend);
            GL.DepthMask(false);
            GL.BlendFunc(BlendingFactorSrc.Zero, BlendingFactorDest.Src1Color);
            GL.DepthMask(true);
            GL.Disable(EnableCap.Blend);
            */
            // textureid.Clear();

            // get level 10 tiles
            List<GPoint> tileArea1 = prj.GetAreaTileList(area, otherzoomlevel, 1);

            // get type list at new zoom level
            List<GPoint> tileArea2 = prj.GetAreaTileList(area, zoom, 2);

            List<GPoint> tileArea = new List<GPoint>();

            tileArea.AddRange(tileArea1);
            tileArea.AddRange(tileArea2);

            // get tiles & combine into one
            foreach (var p in tileArea)
            {
                int localzoom = zoom;

                core.tileDrawingListLock.AcquireReaderLock();
                core.Matrix.EnterReadLock();
                try
                {
                    if (tileArea1.Contains(p))
                        localzoom = otherzoomlevel;

                    topLeftPx = prj.FromLatLngToPixel(area.LocationTopLeft, localzoom);

                    GMap.NET.Internals.Tile t = core.Matrix.GetTileWithNoLock(localzoom, p);

                    if (t.NotEmpty)
                    {
                        foreach (GMapImage img in t.Overlays)
                        {
                            if (!textureid.ContainsKey(p))
                            {
                                generateTexture(p, (Bitmap) img.Img);
                            }
                        }
                    }
                    else
                    {
                    }
                }
                finally
                {
                    core.Matrix.LeaveReadLock();
                    core.tileDrawingListLock.ReleaseReaderLock();
                }

                //GMapImage tile = ((PureImageCache)Maps.MyImageCache.Instance).GetImageFromCache(type.DbId, p, zoom) as GMapImage;

                //if (tile != null && !textureid.ContainsKey(p))
                {
                    //  generateTexture(p, (Bitmap)tile.Img);
                }

                if (textureid.ContainsKey(p))
                {
                    int texture = textureid[p];

                    GL.Enable(EnableCap.Texture2D);
                    GL.BindTexture(TextureTarget.Texture2D, texture);
                }
                else
                {
                    //Console.WriteLine("Missing tile");
                    continue;
                }

                long x = p.X*prj.TileSize.Width - topLeftPx.X;
                long y = p.Y*prj.TileSize.Width - topLeftPx.Y;

                long xr = p.X*prj.TileSize.Width;
                long yr = p.Y*prj.TileSize.Width;

                long x2 = (p.X + 1)*prj.TileSize.Width;
                long y2 = (p.Y + 1)*prj.TileSize.Width;


                GL.LineWidth(0);
                GL.Color3(Color.White);

                // generate terrain
                GL.Begin(PrimitiveType.TriangleStrip);

                var latlng = prj.FromPixelToLatLng(xr, yr, localzoom);

                double heightl = srtm.getAltitude(latlng.Lat, latlng.Lng).alt;
                if (localzoom == 10)
                    heightl = 0;

                //xr - topLeftPx.X, yr - topLeftPx.Y
                GL.TexCoord2(0, 0);
                GL.Vertex3(latlng.Lng, latlng.Lat, heightl*heightscale);


                // next down
                latlng = prj.FromPixelToLatLng(xr, y2, localzoom);

                heightl = srtm.getAltitude(latlng.Lat, latlng.Lng).alt;
                if (localzoom == 10)
                    heightl = 0;

                GL.TexCoord2(0, 1);
                GL.Vertex3(latlng.Lng, latlng.Lat, heightl*heightscale);


                // next right
                latlng = prj.FromPixelToLatLng(x2, yr, localzoom);

                heightl = srtm.getAltitude(latlng.Lat, latlng.Lng).alt;
                if (localzoom == 10)
                    heightl = 0;

                GL.TexCoord2(1, 0);
                GL.Vertex3(latlng.Lng, latlng.Lat, heightl*heightscale);


                // next right down
                latlng = prj.FromPixelToLatLng(x2, y2, localzoom);

                heightl = srtm.getAltitude(latlng.Lat, latlng.Lng).alt;
                if (localzoom == 10)
                    heightl = 0;

                GL.TexCoord2(1, 1);
                GL.Vertex3(latlng.Lng, latlng.Lat, heightl*heightscale);

                GL.End();
            }

            GL.Flush();

            try
            {
                this.SwapBuffers();


                //Context.MakeCurrent(null);
            }
            catch
            {
            }

            //this.Invalidate();

            return;
        }
示例#52
0
        public static void InitUI(int width, int height)
        {
            if (Shaders.Init())
            {
                Elements = new Dictionary <string, UIElement>();

                // create the top level screen container
                UIWindow            = new UIContainer(new Point(0, 0), new Point(UI.Width, UI.Height), "TopLevel");
                UIWindow.RelativeTo = Corner.BottomLeft;
                Elements.Add("Screen", UIWindow);

                UIProjectionMatrix = Matrix4.CreateTranslation(new Vector3(-UI.Width / 2, -UI.Height / 2, 0)) * Matrix4.CreateOrthographic(UI.Width, UI.Height, 0, 1000);

                Visible = true;

                MainThreadID = System.Threading.Thread.CurrentThread.ManagedThreadId;

                OnResize(width, height);
            }
        }
示例#53
0
 private Matrix4 planetTransform(int position)
 {
     return(Matrix4.CreateScale(PlanetScale) * Matrix4.CreateTranslation(position * OrbitStep + OrbitOffset, 0, 0));
 }
示例#54
0
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            if (this.DesignMode)
            {
                return;
            }

            if (area.LocationMiddle.Lat == 0 && area.LocationMiddle.Lng == 0)
            {
                return;
            }

            _angle += 1f;

            // area.LocationTopLeft = new PointLatLng(area.LocationTopLeft.Lat + 0.0001,area.LocationTopLeft.Lng);

            //area.Size = new SizeLatLng(0.1, 0.1);

            try
            {
                base.OnPaint(e);
            }
            catch { return; }

            double heightscale = (step / 90.0) * 3;

            float radians = (float)(Math.PI * (rpy.Z * -1) / 180.0f);

            //radians = 0;

            float mouseY = (float)(0.1);

            cameraX = area.LocationMiddle.Lng;                                                                                                                                         // multiplying by mouseY makes the
            cameraZ = area.LocationMiddle.Lat;                                                                                                                                         // camera get closer/farther away with mouseY
            cameraY = (LocationCenter.Alt < srtm.getAltitude(cameraZ, cameraX, 20)) ? (srtm.getAltitude(cameraZ, cameraX, 20) + 0.2) * heightscale : LocationCenter.Alt * heightscale; // (srtm.getAltitude(lookZ, lookX, 20) + 100) * heighscale;


            lookX = area.LocationMiddle.Lng + Math.Sin(radians) * mouseY;;
            lookY = cameraY;
            lookZ = area.LocationMiddle.Lat + Math.Cos(radians) * mouseY;;


            MakeCurrent();


            GL.MatrixMode(MatrixMode.Projection);

            OpenTK.Matrix4 projection = OpenTK.Matrix4.CreatePerspectiveFieldOfView(60 * deg2rad, 1f, 0.00001f, 5000.0f);
            GL.LoadMatrix(ref projection);

            Matrix4 modelview = Matrix4.LookAt((float)cameraX, (float)cameraY, (float)cameraZ, (float)lookX, (float)lookY, (float)lookZ, 0, 1, 0);

            GL.MatrixMode(MatrixMode.Modelview);

            // roll
            modelview = Matrix4.Mult(modelview, Matrix4.CreateRotationZ(rpy.X * deg2rad));
            // pitch
            modelview = Matrix4.Mult(modelview, Matrix4.CreateRotationX(rpy.Y * -deg2rad));

            GL.LoadMatrix(ref modelview);

            GL.ClearColor(Color.LightBlue);

            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            GL.LightModel(LightModelParameter.LightModelAmbient, new float[] { 1f, 1f, 1f, 1f });

            GL.Enable(EnableCap.Texture2D);
            GL.BindTexture(TextureTarget.Texture2D, texture);

            /*
             * GL.Begin(BeginMode.LineStrip);
             *
             * GL.Color3(Color.White);
             * GL.Vertex3(0, 0, 0);
             *
             * GL.Vertex3(area.Bottom, 0, area.Left);
             *
             * GL.Vertex3(lookX, lookY, lookZ);
             *
             * //GL.Vertex3(cameraX, cameraY, cameraZ);
             *
             * GL.End();
             */
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

            sw.Start();

            //zoom = 14;

            getImage();

            sw.Stop();

            Console.WriteLine("img " + sw.ElapsedMilliseconds);

            sw.Start();

            double increment = step * 5;

            double cleanup  = area.Bottom % increment;
            double cleanup2 = area.Left % increment;



            for (double z = (area.Bottom - cleanup); z < area.Top - step; z += increment)
            {
                //Makes OpenGL draw a triangle at every three consecutive vertices
                GL.Begin(PrimitiveType.TriangleStrip);
                for (double x = (area.Left - cleanup2); x < area.Right - step; x += increment)
                {
                    double heightl = srtm.getAltitude(z, area.Right + area.Left - x, 20);

                    //  Console.WriteLine(x + " " + z);

                    GL.Color3(Color.White);


                    //  int heightl = 0;

                    double scale2 = (Math.Abs(x - area.Left) / area.WidthLng);    // / (float)_terrain.Width;

                    double scale3 = (Math.Abs(z - area.Bottom) / area.HeightLat); // / (float)_terrain.Height;

                    double imgx = 1 - scale2;
                    double imgy = 1 - scale3;
                    //GL.Color3(Color.Red);

                    //GL.Color3(_terrain.GetPixel(imgx, imgy));
                    GL.TexCoord2(imgx, imgy);
                    GL.Vertex3(x, heightl * heightscale, z); //  _terrain.GetPixel(x, z).R

                    try
                    {
                        heightl = srtm.getAltitude(z + increment, area.Right + area.Left - x, 20);

                        //scale2 = (Math.Abs(x - area.Left) / area.WidthLng) * (float)_terrain.Width;

                        scale3 = (Math.Abs(((z + increment) - area.Bottom)) / area.HeightLat);// / (float)_terrain.Height;

                        imgx = 1 - scale2;
                        imgy = 1 - scale3;
                        // GL.Color3(Color.Green);
                        //GL.Color3(_terrain.GetPixel(imgx, imgy));
                        GL.TexCoord2(imgx, imgy);
                        GL.Vertex3(x, heightl * heightscale, z + increment);

                        //  Console.WriteLine(x + " " + (z + step));
                    }
                    catch { break; }
                }
                GL.End();
            }

            GL.Enable(EnableCap.Blend);
            GL.DepthMask(false);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One);
            GL.DepthMask(true);
            GL.Disable(EnableCap.Blend);

            GL.Flush();


            sw.Stop();

            Console.WriteLine("GL  " + sw.ElapsedMilliseconds);

            try
            {
                this.SwapBuffers();


                Context.MakeCurrent(null);
            }
            catch { }

            //this.Invalidate();
        }
示例#55
0
        private void RenderShape(RenderingContext rc)
        {
            // Refactor tessellation
            var shader = CurrentShader;

            if (shader != null)
            {
                shader.Use();

                if (bbox != null)
                {
                    shader.SetFieldValue("bboxMaxWidth", bbox.Width);
                    shader.SetFieldValue("bboxMaxHeight", bbox.Height);
                    shader.SetFieldValue("bboxMaxDepth", bbox.Depth);

                    shader.SetFieldValue("bbox_x", bbox.Width);
                    shader.SetFieldValue("bbox_y", bbox.Height);
                    shader.SetFieldValue("bbox_z", bbox.Depth);
                }

                shader.SetFieldValue("coloringEnabled", coloring ? 1 : 0);

                if (typeof(ElevationGrid).IsInstanceOfType(geometry))
                {
                    shader.SetFieldValue("lightingEnabled", 0);
                    shader.SetFieldValue("texturingEnabled", 1);
                }

                Vector3 tmp = rc.matricies.Scale;
                if (typeof(Text).IsInstanceOfType(geometry))
                {
                    rc.PushMatricies();
                    rc.matricies.Scale *= 200f;
                }

                if (depthMask == false)
                {
                    //REFACTOR!!
                    Matrix4 mat4 = Matrix4.Identity;
                    //Quaternion qRotFix = QuaternionExtensions.EulerToQuat(rc.cam.calibOrient.X, rc.cam.calibOrient.Y, rc.cam.calibOrient.Z);
                    //mat4 *= Matrix4.CreateTranslation(rc.cam.calibTrans) * Matrix4.CreateFromQuaternion(qRotFix);
                    Quaternion qRotFix = QuaternionExtensions.EulerToQuat(0.15f, 3.479997f, 0f);
                    mat4 *= Matrix4.CreateTranslation(new Vector3(0f, 0f, -0.29f)) * Matrix4.CreateFromQuaternion(qRotFix);
                    // test weapon/gun rendering fixed in front of player
                    //TODO: port this to X3D

                    shader.SetFieldValue("modelview", ref mat4);
                    if (quadShader != null)
                    {
                        quadShader.SetFieldValue("modelview", ref mat4);
                    }
                    //GL.DepthMask(false);
                }

                shader.SetFieldValue("size", size);
                shader.SetFieldValue("scale", scale);

                if (loadedGeometry)
                {
                    if (shader.IsTessellator)
                    {
                        RenderTessellator(rc);
                    }
                    else
                    {
                        if (typeof(PointSet).IsInstanceOfType(geometry))
                        {
                            RenderPoints(rc);
                        }
                        else if (typeof(IndexedLineSet).IsInstanceOfType(geometry) || typeof(LineSet).IsInstanceOfType(geometry))
                        {
                            RenderLines(rc);
                        }
                        else
                        {
                            RenderTriangles(rc);
                            RenderQuads(rc);
                        }
                    }
                }


                if (depthMask == false)
                {
                    //GL.DepthMask(true);
                }

                if (typeof(Text).IsInstanceOfType(geometry))
                {
                    rc.PopMatricies();
                    rc.matricies.Scale = tmp;
                }
            }
        }
示例#56
0
        private void setupUi()
        {
            var formatter = new ThousandsFormatter();
            var colonies  = this.controller.Planets.Where(x => x.Owner != null).ToList();

            this.UpdateScene(
                ref this.colonyInfos,
                colonies.Select(
                    planet =>
            {
                var xOffset = planet.OrdinalPosition * OrbitStep + OrbitOffset;

                return(new SceneObject(new PolygonData(
                                           PopCountZ,
                                           new SpriteData(Matrix4.Identity, TextRenderUtil.Get.TextureId, Color.White),
                                           TextRenderUtil.Get.BufferText(
                                               LocalizationManifest.Get.CurrentLanguage["FormMain"]["Population"].Text() + ": " + formatter.Format(planet.Population),
                                               -0.5f,
                                               Matrix4.CreateScale(TextScale) * Matrix4.CreateTranslation(xOffset, -PlanetScale / 2 - PopCountTopMargin, 0)
                                               ).ToList()
                                           )));
            }
                    ).ToList()
                );


            const float yOffset = -PlanetScale / 2 - PopCountTopMargin - TextScale - ButtonTopMargin - ButtonSize / 2;

            //TODO(v0.6) buttons for only hostile colonies
            this.UpdateScene(
                ref this.bombButtons,
                colonies.Select(
                    colony =>
            {
                var xOffset = colony.OrdinalPosition * OrbitStep + OrbitOffset;

                //TODO(v0.6) Use scene object physical shape
                return(new SceneObject(new PolygonData(
                                           PopCountZ,
                                           new SpriteData(Matrix4.CreateScale(ButtonSize) * Matrix4.CreateTranslation(xOffset, yOffset, 0), GalaxyTextures.Get.BombButton.Id, Color.White),
                                           SpriteHelpers.UnitRectVertexData(GalaxyTextures.Get.BombButton)
                                           )));
            }).ToList()
                );
        }
示例#57
0
        internal void RenderToFrameBuffer(FrameBuffer frameBuffer, ref Matrix4 transform, bool useOrthoProjection)
        {
            if (frameBuffer == null)
            {
                throw new ArgumentNullException("frameBuffer");
            }
            if (!frameBuffer.Status)
            {
                throw new ArgumentException("Frame buffer is not renderable.", "frameBuffer");
            }
            UISystem.IsOffScreenRendering = true;
            GraphicsContext graphicsContext      = UISystem.GraphicsContext;
            int             num                  = frameBuffer.Width;
            int             num2                 = frameBuffer.Height;
            Matrix4         viewProjectionMatrix = UISystem.ViewProjectionMatrix;
            Matrix4         transform3D          = this.Transform3D;
            PivotType       pivotType            = this.PivotType;

            this.Transform3D = transform;
            this.PivotType   = PivotType.TopLeft;
            LinkedTree <Widget> parent     = this.linkedTree.Parent;
            LinkedTree <Widget> linkedTree = null;

            if (parent != null)
            {
                linkedTree = this.LinkedTree.NextSibling;
                this.linkedTree.RemoveChild();
            }
            graphicsContext.SetFrameBuffer(frameBuffer);
            graphicsContext.SetColorMask((ColorMask)15);
            UISystem.SetClipRegionFull();
            graphicsContext.SetViewport(0, 0, num, num2);
            graphicsContext.SetClearColor(0f, 0f, 0f, 1f);
            graphicsContext.Clear();
            if (useOrthoProjection)
            {
                float num3 = 100000f;
                float num4 = -100000f;
                UISystem.ViewProjectionMatrix = new Matrix4(2f / (float)num * UISystem.Scale, 0f, 0f, 0f, 0f, -2f / (float)num2 * UISystem.Scale, 0f, 0f, 0f, 0f, -2f / (num3 - num4), 0f, -1f, 1f, (num3 + num4) / (num3 - num4), 1f);
            }
            UISystem.Render(this);
            graphicsContext.Enable((EnableMode)4u, true);
            graphicsContext.SetBlendFuncRgb((BlendFuncMode)0, (BlendFuncFactor)0, (BlendFuncFactor)1);
            graphicsContext.SetBlendFuncAlpha((BlendFuncMode)0, (BlendFuncFactor)9, (BlendFuncFactor)0);
            UISystem.SetClipRegionFull();
            UISprite     uISprite = new UISprite(1);
            UISpriteUnit unit     = uISprite.GetUnit(0);

            unit.SetPosition(-1f, -1f);
            unit.Width  = (float)frameBuffer.Width + 2f;
            unit.Height = (float)frameBuffer.Height + 2f;
            unit.Color  = new UIColor(0f, 0f, 0f, 1f);
            uISprite.Render();
            graphicsContext.SetFrameBuffer(null);
            UISystem.SetClipRegionFull();
            graphicsContext.SetColorMask((ColorMask)7);
            UISystem.ViewProjectionMatrix = viewProjectionMatrix;
            if (linkedTree != null)
            {
                this.linkedTree.InsertChildBefore(linkedTree);
            }
            else if (parent != null)
            {
                parent.AddChildLast(this.linkedTree);
            }
            this.pivotType   = pivotType;
            this.Transform3D = transform3D;
            UISystem.IsOffScreenRendering = false;
        }
 public override void Render(GLContext context)
 {
     if (PrimaryEditor.RenderLines)
     {
         context.Textures.White.Bind();
         context.Rendering.RenderLineBox(Mins, Maxes, RotMatrix());
     }
     else
     {
         Location HalfSize = (Maxes - Mins) / 2;
         Matrix4  mat      = Matrix4.CreateScale((float)HalfSize.X, (float)HalfSize.Y, (float)HalfSize.Z) * RotMatrix() * Matrix4.CreateTranslation((Mins + HalfSize).ToOVector());
         GL.UniformMatrix4(2, false, ref mat);
         context.Rendering.SetMinimumLight(1.0f);
         MyVBO.Render(PrimaryEditor.RenderTextures);
     }
 }
示例#59
0
 public void RenderToFrameBuffer(FrameBuffer frameBuffer, Matrix4 transform)
 {
     this.RenderToFrameBuffer(frameBuffer, ref transform, true);
 }
示例#60
0
        public override void Render(RenderingContext rc)
        {
            base.Render(rc);

            rc.PushMatricies();

            //if (!loadedGeometry) return;

            // PREPARE shape for rendering

            NormalMatrix = new Matrix3(rc.matricies.modelview); // NormalMatrix = M4GetUpper3x3(ModelviewMatrix);

            var shader = CurrentShader;

            if (shader != null)
            {
                // CurrentShader = linkedShaders;


                shader.Use();

                if (shader.IsTessellator)
                {
                    if (shader.IsBuiltIn)
                    {
                        // its a built in system shader so we are using the the fixed parameter inbuilt tesselator
                        CurrentShader.SetFieldValue("TessLevelInner", this.tessLevelInner);
                        CurrentShader.SetFieldValue("TessLevelOuter", this.tessLevelOuter);
                    }
                }

                shader.SetFieldValue("lightingEnabled", 1);
                shader.SetFieldValue("headlightEnabled", 0);
                shader.SetFieldValue("calib1", rc.cam.calibTrans);
                shader.SetFieldValue("calib2", rc.cam.calibOrient);

                if (depthMask)
                {
                    Matrix4 MVP     = ApplyGeometricTransformations(rc, shader, this);
                    Vector3 lookat  = QuaternionExtensions.Rotate(rc.cam.Orientation, Vector3.UnitZ);
                    Vector3 forward = new Vector3(lookat.X, 0, lookat.Z).Normalized();
                    Vector3 up      = Vector3.UnitY;
                    Vector3 left    = up.Cross(forward);

                    Vector2 orient;
                    Vector3 position;

                    orient   = QuaternionExtensions.ExtractPitchYawRoll(rc.cam.Orientation.Inverted()).Xy; // pitch and yaw only
                    position = rc.cam.Position;

                    shader.SetFieldValue("headlightEnabled", NavigationInfo.HeadlightEnabled ? 1 : 0);
                    shader.SetFieldValue("sceneCameraPosition", position);
                    shader.SetFieldValue("model", ref MVP);
                    shader.SetFieldValue("orientation", orient);
                    shader.SetFieldValue("lookat", rc.cam.Direction);
                    shader.SetFieldValue("forward", forward);
                    shader.SetFieldValue("up", up);
                    shader.SetFieldValue("left", left);
                }
                else
                {
                    //REFACTOR!!

                    RefreshDefaultUniforms(shader);

                    if (shader.IsTessellator)
                    {
                        RefreshTessUniforms(shader);
                    }

                    //Matrix4 MVP = rc.cam.GetWorldOrientation() ;

                    //shader.SetFieldValue("modelview", ref MVP);

                    //shader.SetFieldValue("modelview", ref MVP); //GL.UniformMatrix4(uniformModelview, false, ref rc.matricies.modelview);
                    shader.SetFieldValue("projection", ref rc.matricies.projection);
                    shader.SetFieldValue("camscale", rc.cam.Scale.X);                        //GL.Uniform1(uniformCameraScale, rc.cam.Scale.X);
                    shader.SetFieldValue("X3DScale", rc.matricies.Scale);                    //GL.Uniform3(uniformX3DScale, rc.matricies.Scale);
                    shader.SetFieldValue("coloringEnabled", coloring ? 1 : 0);
                    shader.SetFieldValue("texturingEnabled", this.texturingEnabled ? 1 : 0); //GL.Uniform1(uniforms.a_texturingEnabled, this.texturingEnabled ? 1 : 0);
                    shader.SetFieldValue("normalmatrix", ref NormalMatrix);
                }

                ApplyAppearance(rc);

                // RENDER shape
                RenderShape(rc);
            }

            if (drawBoundingBox && bbox != null)
            {
                RenderBoundingBox(rc);
            }
        }