示例#1
0
        protected override void InitNode()
        {
            Body = GetComponentInParent <CelestialBody>();
            Body.TerrainNodes.Add(this);

            TerrainMaterial = MaterialHelper.CreateTemp(Body.ColorShader, "TerrainNode");

            //Manager.GetSkyNode().InitUniforms(TerrainMaterial);

            var faces = new Vector3d[] { new Vector3d(0, 0, 0), new Vector3d(90, 0, 0), new Vector3d(90, 90, 0), new Vector3d(90, 180, 0), new Vector3d(90, 270, 0), new Vector3d(0, 180, 180) };

            FaceToLocal = Matrix4x4d.Identity();

            // If this terrain is deformed into a sphere the face matrix is the rotation of the
            // terrain needed to make up the spherical planet. In this case there should be 6 terrains, each with a unique face number
            if (Face - 1 >= 0 && Face - 1 < 6)
            {
                FaceToLocal = Matrix4x4d.Rotate(faces[Face - 1]);
            }

            //LocalToWorld = Matrix4x4d.ToMatrix4x4d(transform.localToWorldMatrix) * FaceToLocal;
            LocalToWorld = FaceToLocal;

            Deformation = new DeformationSpherical(Body.Radius);

            TerrainQuadRoot = new TerrainQuad(this, null, 0, 0, -Body.Radius, -Body.Radius, 2.0 * Body.Radius, ZMin, ZMax);
        }
示例#2
0
        protected virtual void SetProjectionMatrix()
        {
            var h = (float)(GetHeight() - GroundHeight);

            CameraComponent.nearClipPlane = Mathf.Clamp(0.1f * h, 0.03f, 1000.0f);
            CameraComponent.farClipPlane  = Mathf.Clamp(1e6f * h, 1000.0f, 1e12f);

            CameraComponent.ResetProjectionMatrix();

            var projectionMatrix = CameraComponent.projectionMatrix;

            if (SystemInfo.graphicsDeviceVersion.IndexOf("Direct3D") > -1)
            {
                // NOTE : Default unity antialiasing breaks matrices?
                if (CameraHelper.IsDeferred(CameraComponent) || QualitySettings.antiAliasing == 0)
                {
                    // Invert Y for rendering to a render texture
                    for (byte i = 0; i < 4; i++)
                    {
                        projectionMatrix[1, i] = -projectionMatrix[1, i];
                    }
                }

                // Scale and bias depth range
                for (byte i = 0; i < 4; i++)
                {
                    projectionMatrix[2, i] = projectionMatrix[2, i] * 0.5f + projectionMatrix[3, i] * 0.5f;
                }
            }

            CameraToScreenMatrix = new Matrix4x4d(projectionMatrix);
            ScreenToCameraMatrix = CameraToScreenMatrix.Inverse();
        }
示例#3
0
        public override void UpdateNode()
        {
            UpdateKeywords(OceanMaterial);

            OceanMaterial.renderQueue = (int)RenderQueue + RenderQueueOffset;

            // Calculates the required data for the projected grid
            CameraToWorld = GodManager.Instance.View.CameraToWorldMatrix;

            var oceanFrame = CameraToWorld * Vector3d.zero; // Camera in local space

            var radius       = ParentBody.Size;
            var trueAltitude = Vector3d.Distance(GodManager.Instance.View.WorldCameraPosition, Origin) - radius;

            if ((radius > 0.0 && trueAltitude > ZMin) || (radius < 0.0 && new Vector2d(oceanFrame.y, oceanFrame.z).Magnitude() < -radius - ZMin))
            {
                OldLocalToOcean = Matrix4x4d.identity;
                Offset          = Vector4.zero;
                DrawOcean       = false;

                return;
            }

            DrawOcean = true;
        }
示例#4
0
 public DeformationBase()
 {
     uniforms       = new Uniforms();
     localToCamera  = Matrix4x4d.identity;
     localToScreen  = Matrix4x4d.identity;
     localToTangent = Matrix3x3d.identity;
 }
示例#5
0
        /*
         * Get a copy of the projection matrix and convert in to double precision
         * and apply the bias if using dx11 and flip Y if deferred rendering is used
         */
        protected virtual void SetProjectionMatrix()
        {
            float h = (float)(GetHeight() - m_groundHeight);

            camera.nearClipPlane = 0.1f * h;
            camera.farClipPlane  = 1e6f * h;

            camera.ResetProjectionMatrix();

            Matrix4x4 p   = camera.projectionMatrix;
            bool      d3d = SystemInfo.graphicsDeviceVersion.IndexOf("Direct3D") > -1;

            if (d3d)
            {
                if (camera.actualRenderingPath == RenderingPath.DeferredLighting)
                {
                    // Invert Y for rendering to a render texture
                    for (int i = 0; i < 4; i++)
                    {
                        p[1, i] = -p[1, i];
                    }
                }

                // Scale and bias depth range
                for (int i = 0; i < 4; i++)
                {
                    p[2, i] = p[2, i] * 0.5f + p[3, i] * 0.5f;
                }
            }

            m_cameraToScreenMatrix = new Matrix4x4d(p);
            m_screenToCameraMatrix = m_cameraToScreenMatrix.Inverse();
        }
示例#6
0
        public void UpdateNode()
        {
            LocalToWorld = /*Matrix4x4d.ToMatrix4x4d(transform.localToWorldMatrix) * */ FaceToLocal;

            Matrix4x4d localToCamera    = View.WorldToCamera * LocalToWorld;
            Matrix4x4d localToScreen    = View.CameraToScreen * localToCamera;
            Matrix4x4d invLocalToCamera = localToCamera.Inverse;

            DeformedCameraPos = invLocalToCamera * (new Vector3d(0));

            Frustum3d.SetPlanes(DeformedFrustumPlanes, localToScreen);
            LocalCameraPos = Deform.DeformedToLocal(DeformedCameraPos);

            Matrix4x4d m = Deform.LocalToDeformedDifferential(LocalCameraPos, true);

            DistFactor = (float)Math.Max((new Vector3d(m[0, 0], m[1, 0], m[2, 0])).Magnitude, (new Vector3d(m[0, 1], m[1, 1], m[2, 1])).Magnitude);

            Vector3d left  = DeformedFrustumPlanes[0].xyz.Normalized;
            Vector3d right = DeformedFrustumPlanes[1].xyz.Normalized;

            float fov   = (float)MathUtility.Safe_Acos(-Vector3d.Dot(left, right));
            float width = (float)Screen.width;

            SplitDist = m_splitFactor * width / 1024.0f * Mathf.Tan(40.0f * Mathf.Deg2Rad) / Mathf.Tan(fov / 2.0f);

            if (SplitDist < 1.1f || !MathUtility.IsFinite(SplitDist))
            {
                SplitDist = 1.1f;
            }

            // initializes data structures for horizon occlusion culling
            if (HorizonCulling && LocalCameraPos.z <= Root.ZMax)
            {
                Vector3d deformedDir = invLocalToCamera * (new Vector3d(0, 0, 1));
                Vector2d localDir    = (Deform.DeformedToLocal(deformedDir) - LocalCameraPos).xy.Normalized;

                LocalCameraDir = new Matrix2x2d(localDir.y, -localDir.x, -localDir.x, -localDir.y);

                for (int i = 0; i < HORIZON_SIZE; ++i)
                {
                    m_horizon[i] = float.NegativeInfinity;
                }
            }

            Root.Update();

            World.SkyNode.SetUniforms(m_terrainMaterial);
            World.SunNode.SetUniforms(m_terrainMaterial);
            World.SetUniforms(m_terrainMaterial);
            Deform.SetUniforms(this, m_terrainMaterial);

            if (World.OceanNode != null)
            {
                World.OceanNode.SetUniforms(m_terrainMaterial);
            }
            else
            {
                m_terrainMaterial.SetFloat("_Ocean_DrawBRDF", 0.0f);
            }
        }
示例#7
0
        /*
         * Sets the shader uniforms that are necessary to project on screen the
         * TerrainQuad of the given TerrainNode. This method can set the uniforms
         * that are common to all the quads of the given terrain.
         */
        public virtual void SetUniforms(TerrainNode node, Material mat)
        {
            if (mat == null || node == null)
            {
                return;
            }

            float d1 = node.GetSplitDist() + 1.0f;
            float d2 = 2.0f * node.GetSplitDist();

            mat.SetVector(m_uniforms.blending, new Vector2(d1, d2 - d1));

            m_localToCamera = node.GetView().GetWorldToCamera() * node.GetLocalToWorld();
            m_localToScreen = node.GetView().GetCameraToScreen() * m_localToCamera;

            Vector3d2 localCameraPos = node.GetLocalCameraPos();
            Vector3d2 worldCamera    = node.GetView().GetWorldCameraPos();

            Matrix4x4d A = LocalToDeformedDifferential(localCameraPos);
            Matrix4x4d B = DeformedToTangentFrame(worldCamera);

            Matrix4x4d ltot = B * node.GetLocalToWorld() * A;

            m_localToTangent = new Matrix3x3d(ltot.m[0, 0], ltot.m[0, 1], ltot.m[0, 3],
                                              ltot.m[1, 0], ltot.m[1, 1], ltot.m[1, 3],
                                              ltot.m[3, 0], ltot.m[3, 1], ltot.m[3, 3]);

            mat.SetMatrix(m_uniforms.localToScreen, m_localToScreen.ToMatrix4x4());
            mat.SetMatrix(m_uniforms.localToWorld, node.GetLocalToWorld().ToMatrix4x4());
        }
示例#8
0
 /// <summary>
 ///     OSG utiliza una representacion 'row-mayor', OpenGL 'column-mayor' y Clip
 ///     'column-mayor'.
 ///     http://steve.hollasch.net/cgindex/math/matrix/column-vec.html
 ///     http://www.openscenegraph.org/projects/osg/wiki/Support/Maths/MatrixTransformations
 /// </summary>
 /// <param name="mat"></param>
 /// <returns></returns>
 public static Matrixd ToMatrixd(this Matrix4x4d mat)
 {
     return(new Matrixd(mat.M00, mat.M10, mat.M20, mat.M30,
                        mat.M01, mat.M11, mat.M21, mat.M31,
                        mat.M02, mat.M12, mat.M22, mat.M32,
                        mat.M03, mat.M13, mat.M23, mat.M33));
 }
示例#9
0
 public Deformation()
 {
     m_uniforms       = new Uniforms();
     m_localToCamera  = new Matrix4x4d();
     m_localToScreen  = new Matrix4x4d();
     m_localToTangent = new Matrix3x3d();
 }
示例#10
0
    public void TRS()
    {
        for (int i = 0; i < count; i++)
        {
            float ax, ay, az;
            float bx, by, bz;
            float cx, cy, cz;

            ax = UnityEngine.Random.Range(-10F, 10F);
            ay = UnityEngine.Random.Range(-10F, 10F);
            az = UnityEngine.Random.Range(-10F, 10F);

            bx = UnityEngine.Random.Range(-10F, 10F);
            by = UnityEngine.Random.Range(-10F, 10F);
            bz = UnityEngine.Random.Range(-10F, 10F);

            cx = UnityEngine.Random.Range(-10F, 10F);
            cy = UnityEngine.Random.Range(-10F, 10F);
            cz = UnityEngine.Random.Range(-10F, 10F);

            Matrix4x4  value  = Matrix4x4.TRS(new Vector3(ax, ay, az), Quaternion.Euler(new Vector3(bx, by, bz)), new Vector3(cx, cy, cz));
            Matrix4x4d valued = Matrix4x4d.TRS(new Vector3d(ax, ay, az), Quaterniond.Euler(new Vector3d(bx, by, bz)), new Vector3d(cx, cy, cz));

            Assert.True(Approximate(value, valued));
        }
    }
示例#11
0
    public static Matrix4x4d SetAxisAngle(Vector3d rotationAxis, double radians)
    {
        Matrix4x4d m = new Matrix4x4d();

        double s, c;
        double xx, yy, zz, xy, yz, zx, xs, ys, zs, one_c;

        s = Math.Sin(radians);
        c = Math.Cos(radians);

        xx    = rotationAxis.x * rotationAxis.x;
        yy    = rotationAxis.y * rotationAxis.y;
        zz    = rotationAxis.z * rotationAxis.z;
        xy    = rotationAxis.x * rotationAxis.y;
        yz    = rotationAxis.y * rotationAxis.z;
        zx    = rotationAxis.z * rotationAxis.x;
        xs    = rotationAxis.x * s;
        ys    = rotationAxis.y * s;
        zs    = rotationAxis.z * s;
        one_c = 1 - c;

        m[0, 0] = (one_c * xx) + c;
        m[0, 1] = (one_c * xy) - zs;
        m[0, 2] = (one_c * zx) + ys;

        m[1, 0] = (one_c * xy) + zs;
        m[1, 1] = (one_c * yy) + c;
        m[1, 2] = (one_c * yz) - xs;

        m[2, 0] = (one_c * zx) - ys;
        m[2, 1] = (one_c * yz) + xs;
        m[2, 2] = (one_c * zz) + c;

        return(m);
    }
        /// <summary>
        ///
        /// </summary>
        protected virtual void SetScreenUniforms(TerrainNode node, TerrainQuad quad, MaterialPropertyBlock matPropertyBlock)
        {
            double ox = quad.Ox;
            double oy = quad.Oy;
            double l  = quad.Length;

            Vector3d p0 = new Vector3d(ox, oy, 0.0);
            Vector3d p1 = new Vector3d(ox + l, oy, 0.0);
            Vector3d p2 = new Vector3d(ox, oy + l, 0.0);
            Vector3d p3 = new Vector3d(ox + l, oy + l, 0.0);

            Matrix4x4d corners = new Matrix4x4d(p0.x, p1.x, p2.x, p3.x,
                                                p0.y, p1.y, p2.y, p3.y,
                                                p0.z, p1.z, p2.z, p3.z,
                                                1.0, 1.0, 1.0, 1.0);

            matPropertyBlock.SetMatrix(m_uniforms.screenQuadCorners, MathConverter.ToMatrix4x4(m_localToScreen * corners));

            Matrix4x4d verticals = new Matrix4x4d(0.0, 0.0, 0.0, 0.0,
                                                  0.0, 0.0, 0.0, 0.0,
                                                  1.0, 1.0, 1.0, 1.0,
                                                  0.0, 0.0, 0.0, 0.0);

            matPropertyBlock.SetMatrix(m_uniforms.screenQuadVerticals, MathConverter.ToMatrix4x4(m_localToScreen * verticals));
        }
        void Start()
        {
            Matrix4x4d T, R;

            double spacing = 0.125;
            double radius  = spacing;
            double mass    = 1.0;

            System.Random rnd = new System.Random(0);

            Vector3 min    = new Vector3(-1, -1, -1);
            Vector3 max    = new Vector3(1, 1, 1);
            Box3d   bounds = new Box3d(min, max);

            ParticlesFromBounds source = new ParticlesFromBounds(spacing, bounds);

            T = Matrix4x4d.Translate(new Vector3d(0.0, 4.0, 0.0));
            R = Matrix4x4d.Rotate(new Vector3d(0.0, 0.0, 25.0));

            RidgidBody3d body = new RidgidBody3d(source, radius, mass, T * R);

            body.Dampning = 1.0;
            body.RandomizePositions(rnd, radius * 0.01);

            Solver = new Solver3d();
            Solver.AddBody(body);
            Solver.AddForce(new GravitationalForce3d());
            Solver.AddCollision(new PlanarCollision3d(Vector3.up, 0));
            Solver.SolverIterations    = 2;
            Solver.CollisionIterations = 2;
            Solver.SleepThreshold      = 1;

            CreateSpheres();
        }
        /// <summary>
        /// Sets the shader uniforms that are necessary to project on screen the
        /// TerrainQuad of the given TerrainNode. This method can set the uniforms
        /// that are common to all the quads of the given terrain.
        /// </summary>
        public virtual void SetUniforms(TerrainNode node, Material mat)
        {
            if (mat == null || node == null)
            {
                return;
            }

            float d1 = node.SplitDist + 1.0f;
            float d2 = 2.0f * node.SplitDist;

            mat.SetVector(m_uniforms.blending, new Vector2(d1, d2 - d1));

            m_localToCamera = node.View.WorldToCamera * node.LocalToWorld;
            m_localToScreen = node.View.CameraToScreen * m_localToCamera;

            Vector3d localCameraPos = node.LocalCameraPos;
            Vector3d worldCamera    = node.View.WorldCameraPos;

            Matrix4x4d A = LocalToDeformedDifferential(localCameraPos);
            Matrix4x4d B = DeformedToTangentFrame(worldCamera);

            Matrix4x4d ltot = B * node.LocalToWorld * A;

            m_localToTangent = new Matrix3x3d(ltot[0, 0], ltot[0, 1], ltot[0, 3],
                                              ltot[1, 0], ltot[1, 1], ltot[1, 3],
                                              ltot[3, 0], ltot[3, 1], ltot[3, 3]);

            mat.SetMatrix(m_uniforms.localToScreen, MathConverter.ToMatrix4x4(m_localToScreen));
            mat.SetMatrix(m_uniforms.localToWorld, MathConverter.ToMatrix4x4(node.LocalToWorld));
        }
示例#15
0
    private static Matrix4x4d LookRotationToMatrix(Vector3d viewVec, Vector3d upVec)
    {
        Vector3d   z = viewVec;
        Matrix4x4d m = new Matrix4x4d();

        double mag = Vector3d.Magnitude(z);

        if (mag < 0)
        {
            m = Matrix4x4d.identity;
        }
        z /= mag;

        Vector3d x = Vector3d.Cross(upVec, z);

        mag = Vector3d.Magnitude(x);
        if (mag < 0)
        {
            m = Matrix4x4d.identity;
        }
        x /= mag;

        Vector3d y = Vector3d.Cross(z, x);

        m[0, 0] = x.x; m[0, 1] = y.x; m[0, 2] = z.x;
        m[1, 0] = x.y; m[1, 1] = y.y; m[1, 2] = z.y;
        m[2, 0] = x.z; m[2, 1] = y.z; m[2, 2] = z.z;

        return(m);
    }
示例#16
0
 public Deformation()
 {
     m_uniforms = new Uniforms();
     m_localToCamera = new Matrix4x4d();
     m_localToScreen = new Matrix4x4d();
     m_localToTangent = new Matrix3x3d();
 }
示例#17
0
        private void CalculateMatrices(double ox, double oy, double length, double r)
        {
            var p0 = new Vector3d(ox, oy, r);
            var p1 = new Vector3d(ox + length, oy, r);
            var p2 = new Vector3d(ox, oy + length, r);
            var p3 = new Vector3d(ox + length, oy + length, r);

            Center = (p0 + p3) * 0.5;

            double l0 = 0.0, l1 = 0.0, l2 = 0.0, l3 = 0.0;

            var v0 = p0.Normalized(ref l0);
            var v1 = p1.Normalized(ref l1);
            var v2 = p2.Normalized(ref l2);
            var v3 = p3.Normalized(ref l3);

            Lengths = new Vector4d(l0, l1, l2, l3);

            DeformedCorners = new Matrix4x4d(v0.x * r, v1.x * r, v2.x * r, v3.x * r,
                                             v0.y * r, v1.y * r, v2.y * r, v3.y * r,
                                             v0.z * r, v1.z * r, v2.z * r, v3.z * r,
                                             1.0, 1.0, 1.0, 1.0);

            DeformedVerticals = new Matrix4x4d(v0.x, v1.x, v2.x, v3.x,
                                               v0.y, v1.y, v2.y, v3.y,
                                               v0.z, v1.z, v2.z, v3.z,
                                               0.0, 0.0, 0.0, 0.0);

            var uz = Center.Normalized();
            var ux = new Vector3d(0.0, 1.0, 0.0).Cross(uz).Normalized();
            var uy = uz.Cross(ux);

            TangentFrameToWorld = Owner.TangentFrameToWorld * new Matrix3x3d(ux.x, uy.x, uz.x, ux.y, uy.y, uz.y, ux.z, uy.z, uz.z);
        }
示例#18
0
        protected virtual void SetScreenUniforms(TerrainNode node, TerrainQuad quad, MaterialPropertyBlock matPropertyBlock)
        {
            double ox = quad.GetOX();
            double oy = quad.GetOY();
            double l  = quad.GetLength();

            Vector3d2 p0 = new Vector3d2(ox, oy, 0.0);
            Vector3d2 p1 = new Vector3d2(ox + l, oy, 0.0);
            Vector3d2 p2 = new Vector3d2(ox, oy + l, 0.0);
            Vector3d2 p3 = new Vector3d2(ox + l, oy + l, 0.0);

            Matrix4x4d corners = new Matrix4x4d(p0.x, p1.x, p2.x, p3.x,
                                                p0.y, p1.y, p2.y, p3.y,
                                                p0.z, p1.z, p2.z, p3.z,
                                                1.0, 1.0, 1.0, 1.0);

            matPropertyBlock.AddMatrix(m_uniforms.screenQuadCorners, (m_localToScreen * corners).ToMatrix4x4());

            Matrix4x4d verticals = new Matrix4x4d(0.0, 0.0, 0.0, 0.0,
                                                  0.0, 0.0, 0.0, 0.0,
                                                  1.0, 1.0, 1.0, 1.0,
                                                  0.0, 0.0, 0.0, 0.0);

            matPropertyBlock.AddMatrix(m_uniforms.screenQuadVerticals, (m_localToScreen * verticals).ToMatrix4x4());
        }
示例#19
0
 public DeformationBase()
 {
     uniforms       = new Uniforms();
     localToCamera  = new Matrix4x4d();
     localToScreen  = new Matrix4x4d();
     localToTangent = new Matrix3x3d();
 }
        public FluidBoundary3d(ParticleSource source, double radius, double density, Matrix4x4d RTS)
        {
            ParticleRadius = radius;
            Density        = density;

            CreateParticles(source, RTS);
            CreateBoundryPsi();
        }
        public RidgidBody3d(ParticleSource source, double radius, double mass, Matrix4x4d RTS)
            : base(source.NumParticles, radius, mass)
        {
            Stiffness = 1.0;

            CreateParticles(source, RTS);
            Constraints.Add(new ShapeMatchingConstraint3d(this, mass, Stiffness));
        }
示例#22
0
        public void GetRow()
        {
            Matrix4x4d m = Indexed4x4();

            Assert.AreEqual(new Vector4d(0, 4, 8, 12), m.GetRow(0));
            Assert.AreEqual(new Vector4d(1, 5, 9, 13), m.GetRow(1));
            Assert.AreEqual(new Vector4d(2, 6, 10, 14), m.GetRow(2));
            Assert.AreEqual(new Vector4d(3, 7, 11, 15), m.GetRow(3));
        }
示例#23
0
 private void RandomMatrix(ref Matrix4x4 matrix, ref Matrix4x4d matrixd)
 {
     for (int i = 0; i < 16; i++)
     {
         float temp = UnityEngine.Random.Range(-10F, 10F);
         matrix[i]  = temp;
         matrixd[i] = temp;
     }
 }
示例#24
0
        public void GetColumn()
        {
            Matrix4x4d m = Indexed4x4();

            Assert.AreEqual(new Vector4d(0, 1, 2, 3), m.GetColumn(0));
            Assert.AreEqual(new Vector4d(4, 5, 6, 7), m.GetColumn(1));
            Assert.AreEqual(new Vector4d(8, 9, 10, 11), m.GetColumn(2));
            Assert.AreEqual(new Vector4d(12, 13, 14, 15), m.GetColumn(3));
        }
示例#25
0
        public void TryInverse()
        {
            Matrix4x4d m       = Random4x4(0);
            Matrix4x4d inverse = Matrix4x4d.Identity;

            m.TryInverse(ref inverse);

            Assert.IsTrue((inverse * Random4x4(0)).EqualsWithError(Matrix4x4d.Identity, 1e-6f));
        }
示例#26
0
 private void CreateParticles(ParticleSource source, Matrix4x4d RTS)
 {
     for (int i = 0; i < NumParticles; i++)
     {
         Vector4d pos = RTS * source.Positions[i].xyz1;
         Positions[i] = new Vector3((float)pos.x, (float)pos.y, (float)pos.z);
         Predicted[i] = Positions[i];
     }
 }
示例#27
0
	public static Matrix4x4d operator -(Matrix4x4d m1, Matrix4x4d m2) 
   	{
		Matrix4x4d kSum = new Matrix4x4d();
		for (int iRow = 0; iRow < 4; iRow++) {
			for (int iCol = 0; iCol < 4; iCol++) {
		    	kSum.m[iRow,iCol] = m1.m[iRow,iCol] - m2.m[iRow,iCol];
			}
		}
		return kSum;
   	}
示例#28
0
        public void CreatedFromArray()
        {
            double[] d = new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

            Matrix4x4d m = new Matrix4x4d(d);

            for (int i = 0; i < SIZE; i++)
            {
                Assert.AreEqual(i, m[i]);
            }
        }
示例#29
0
        public void CreatedFromSingleValue()
        {
            float v = 1.1234f;

            Matrix4x4d m = new Matrix4x4d(v);

            for (int i = 0; i < SIZE; i++)
            {
                Assert.AreEqual(v, m[i]);
            }
        }
示例#30
0
        public static Matrix4x4d ToMatrix4x4d(this Matrix4x4 m)
        {
            Matrix4x4d mat = new Matrix4x4d();

            mat.m00 = m.m00; mat.m01 = m.m01; mat.m02 = m.m02; mat.m03 = m.m03;
            mat.m10 = m.m10; mat.m11 = m.m11; mat.m12 = m.m12; mat.m13 = m.m13;
            mat.m20 = m.m20; mat.m21 = m.m21; mat.m22 = m.m22; mat.m23 = m.m23;
            mat.m30 = m.m30; mat.m31 = m.m31; mat.m32 = m.m32; mat.m33 = m.m33;

            return(mat);
        }
示例#31
0
        Matrix4x4d Indexed4x4()
        {
            Matrix4x4d m = new Matrix4x4d();

            for (int i = 0; i < SIZE; i++)
            {
                m[i] = i;
            }

            return(m);
        }
示例#32
0
        public static Matrix4x4 ToMatrix4x4(this Matrix4x4d m)
        {
            Matrix4x4 mat = new Matrix4x4();

            mat.m00 = (float)m.m00; mat.m01 = (float)m.m01; mat.m02 = (float)m.m02; mat.m03 = (float)m.m03;
            mat.m10 = (float)m.m10; mat.m11 = (float)m.m11; mat.m12 = (float)m.m12; mat.m13 = (float)m.m13;
            mat.m20 = (float)m.m20; mat.m21 = (float)m.m21; mat.m22 = (float)m.m22; mat.m23 = (float)m.m23;
            mat.m30 = (float)m.m30; mat.m31 = (float)m.m31; mat.m32 = (float)m.m32; mat.m33 = (float)m.m33;

            return(mat);
        }
示例#33
0
	public static Matrix4x4d operator *(Matrix4x4d m1, Matrix4x4d m2) 
   	{
		Matrix4x4d kProd = new Matrix4x4d();
		for (int iRow = 0; iRow < 4; iRow++) {
			for (int iCol = 0; iCol < 4; iCol++) {
				
		    	kProd.m[iRow,iCol] = m1.m[iRow,0] * m2.m[0,iCol] + 
									 m1.m[iRow,1] * m2.m[1,iCol] + 
									 m1.m[iRow,2] * m2.m[2,iCol] +
									 m1.m[iRow,3] * m2.m[3,iCol];	
			}
		}
		return kProd;
   	}
示例#34
0
	static public Vector4d[] GetFrustumPlanes(Matrix4x4d mat)
	{
		//extract frustum planes from a projection matrix
	    Vector4d[] frustumPlanes = new Vector4d[6];
		
	    // Extract the LEFT plane
		frustumPlanes[0] = new Vector4d();
	    frustumPlanes[0].x = mat.m[3,0] + mat.m[0,0];
	    frustumPlanes[0].y = mat.m[3,1] + mat.m[0,1];
	    frustumPlanes[0].z = mat.m[3,2] + mat.m[0,2];
	    frustumPlanes[0].w = mat.m[3,3] + mat.m[0,3];
	    // Extract the RIGHT plane
		frustumPlanes[1] = new Vector4d();
	    frustumPlanes[1].x = mat.m[3,0] - mat.m[0,0];
	    frustumPlanes[1].y = mat.m[3,1] - mat.m[0,1];
	    frustumPlanes[1].z = mat.m[3,2] - mat.m[0,2];
	    frustumPlanes[1].w = mat.m[3,3] - mat.m[0,3];
	    // Extract the BOTTOM plane
		frustumPlanes[2] = new Vector4d();
	    frustumPlanes[2].x = mat.m[3,0] + mat.m[1,0];
	    frustumPlanes[2].y = mat.m[3,1] + mat.m[1,1];
	    frustumPlanes[2].z = mat.m[3,2] + mat.m[1,2];
	    frustumPlanes[2].w = mat.m[3,3] + mat.m[1,3];
	    // Extract the TOP plane
		frustumPlanes[3] = new Vector4d();
	    frustumPlanes[3].x = mat.m[3,0] - mat.m[1,0];
	    frustumPlanes[3].y = mat.m[3,1] - mat.m[1,1];
	    frustumPlanes[3].z = mat.m[3,2] - mat.m[1,2];
	    frustumPlanes[3].w = mat.m[3,3] - mat.m[1,3];
	    // Extract the NEAR plane
		frustumPlanes[4] = new Vector4d();
	    frustumPlanes[4].x = mat.m[3,0] + mat.m[2,0];
	    frustumPlanes[4].y = mat.m[3,1] + mat.m[2,1];
	    frustumPlanes[4].z = mat.m[3,2] + mat.m[2,2];
	    frustumPlanes[4].w = mat.m[3,3] + mat.m[2,3];
	    // Extract the FAR plane
		frustumPlanes[5] = new Vector4d();
	    frustumPlanes[5].x = mat.m[3,0] - mat.m[2,0];
	    frustumPlanes[5].y = mat.m[3,1] - mat.m[2,1];
	    frustumPlanes[5].z = mat.m[3,2] - mat.m[2,2];
	    frustumPlanes[5].w = mat.m[3,3] - mat.m[2,3];
		
		return frustumPlanes;
	}
示例#35
0
        public void updateStuff()
        {
            //Calculates the required data for the projected grid

            // compute ltoo = localToOcean transform, where ocean frame = tangent space at
            // camera projection on sphere radius in local space

            //			m_core.chosenCamera.ResetProjectionMatrix();
            //			m_core.chosenCamera.ResetWorldToCameraMatrix();

            //			Matrix4x4 ctol1 = m_core.chosenCamera.cameraToWorldMatrix;
            Matrix4x4 ctol1 = m_manager.m_skyNode.farCamera.cameraToWorldMatrix;

            //position relative to kerbin
            //			Vector3d tmp = (m_core.chosenCamera.transform.position) - m_manager.parentCelestialBody.transform.position;
            Vector3d tmp = (m_manager.m_skyNode.farCamera.transform.position) - m_manager.parentCelestialBody.transform.position;
            //			print ("TMP");
            //			print (tmp);
            //			print (tmp.magnitude);

            Vector3d2 cl = new Vector3d2 ();
            //			cl.x = tmp.x;
            //			cl.y = tmp.y;
            //			cl.z = tmp.z;

            //			Matrix4x4d cameraToWorld = new Matrix4x4d (ctol1.m00, ctol1.m01, ctol1.m02, tmp.x,
            //			                                           ctol1.m10, ctol1.m11, ctol1.m12, tmp.y,
            //			                                           ctol1.m20, ctol1.m21, ctol1.m22, tmp.z,
            //			                                           ctol1.m30, ctol1.m31, ctol1.m32, ctol1.m33);

            Matrix4x4d cameraToWorld = new Matrix4x4d (ctol1.m00, ctol1.m01, ctol1.m02, ctol1.m03,
                                                       ctol1.m10, ctol1.m11, ctol1.m12, ctol1.m13,
                                                       ctol1.m20, ctol1.m21, ctol1.m22, ctol1.m23,
                                                       ctol1.m30, ctol1.m31, ctol1.m32, ctol1.m33);

            //			Matrix4x4d cameraToWorld = new Matrix4x4d (0,0.906534175092856,  0.422132431102747,    6365631.33384793,
            //			                                           -0.997188818006091 ,  0.0316302600890084,   -0.0679263416526804,  -906.151431945729,
            //			                                           0.0749297086849734,0.420945740013386,-0.903985742542972,-12059.3565785169,
            //			                                           0,0,0,1);

            //Vector3d planetPos = m_manager.parentCelestialBody.transform.position;

            Matrix4x4d worldToLocal = new Matrix4x4d (m_manager.parentCelestialBody.transform.worldToLocalMatrix);

            Vector4 translation = m_manager.parentCelestialBody.transform.worldToLocalMatrix.inverse.GetColumn (3);

            Matrix4x4d worldToLocal2 = new Matrix4x4d (1, 0, 0, -translation.x,
                                                      0, 1, 0, -translation.y,
                                                      0, 0, 1, -translation.z,
                                                      0, 0, 0, 1);

            //			print ("translation");
            //			print (translation);

            //Matrix4x4d camToLocal = cameraToWorld.Inverse ();// * worldToLocal.Inverse();

            Matrix4x4d camToLocal = worldToLocal2 * cameraToWorld;
            //			Matrix4x4d camToLocal = ModifiedWorldToCameraMatrix ();

            //			Matrix4x4d camToLocal = cameraToWorld ;

            //			print ("WORLD TO LOCAL");
            //			print (worldToLocal);

            //			print ("CAM T		O LOCAL");
            //			print (camToLocal);

            //cl = camToLocal * Vector3d2.Zero ();
            /*Vector3d2*/ cl = camToLocal * Vector3d2.Zero ();

            //			print ("CL");
            //			print (cl);
            //			print (cl.Magnitude ());

            // camera in local space relative to planet's origin

            double radius = m_manager.GetRadius ();

            m_drawOcean = true;
            Vector3d2 ux, uy, uz, oo;

            uz = cl.Normalized() ; // unit z vector of ocean frame, in local space

            if (m_oldlocalToOcean != Matrix4x4d.Identity())
            {
                ux = (new Vector3d2(m_oldlocalToOcean.m[1,0], m_oldlocalToOcean.m[1,1], m_oldlocalToOcean.m[1,2])).Cross(uz).Normalized();
            }

            else
            {
                ux = Vector3d2.UnitZ().Cross(uz).Normalized();
            }

            uy = uz.Cross(ux); // unit y vector

            //			h = cl.Magnitude() - radius;
            //			print ("h=");
            //			print (h);
            //			h = cl.Magnitude();
            //			Vector3d tmp2=m_core.chosenCamera.transform.position-m_manager.parentCelestialBody.transform.position;

            oo = uz * (radius); // origin of ocean frame, in local space
            //			oo = uz;
            //			oo.x = oo.x;
            //			oo.y = oo.y;
            //			oo.z = oo.z;

            //local to ocean transform
            //computed from oo and ux, uy, uz should be correct
            Matrix4x4d localToOcean = new Matrix4x4d(
                ux.x, ux.y, ux.z, -ux.Dot(oo),
                uy.x, uy.y, uy.z, -uy.Dot(oo),
                uz.x, uz.y, uz.z, -uz.Dot(oo),
                0.0,  0.0,  0.0,  1.0);

            Matrix4x4d cameraToOcean = localToOcean * camToLocal;
            //			cameraToOcean = cameraToOcean.Inverse ();
            //			Matrix4x4d cameraToOcean = OceanToWorld.Inverse() * cameraToWorld;
            Vector3d2 delta=new Vector3d2(0,0,0);

            if (m_oldlocalToOcean != Matrix4x4d.Identity())
            {
                /*Vector3d2 */delta = localToOcean * (m_oldlocalToOcean.Inverse() * Vector3d2.Zero());
                m_offset += delta;
            }

            m_oldlocalToOcean = localToOcean;

            Matrix4x4d ctos = ModifiedProjectionMatrix (m_manager.m_skyNode.farCamera);
            Matrix4x4d stoc = ctos.Inverse();
            //			Matrix4x4d stoc = new Matrix4x4d (1.23614492203479, 0, 0, 0,
            //				0, 0.577350279552042, 0, 0,
            //					0, 0, 0, -1,
            //			                                 0, 0, -0.000249974703487648, 0.000249974763086261);
            //			print ("STOC");
            //			print (stoc);
            //			Matrix4x4d stoc = Matrix4x4d.Identity();

            //			Matrix4x4 p = camera.projectionMatrix;
            //
            //			m_cameraToScreenMatrix = new Matrix4x4d(p);
            //			m_screenToCameraMatrix = m_cameraToScreenMatrix.Inverse();

            //			Matrix4x4d stoc = new Matrix4x4d(3.57253843540205,0,0,0,
            //			                             0,3.577350279552042,0,0,
            //			                             0,0,0,-2,
            //			                             0,0,-0.00178426976276966,0.00178426997547119);

            Vector3d2 oc = cameraToOcean * Vector3d2.Zero();

            //			h = tmp2.magnitude - radius;
            h = oc.z;
            //			print ("oc.z");
            //			print (h);
            //			print ("h=");
            //			print (h);

            //			print ("tmp2.magnitude - radius");
            //			print (tmp2.magnitude - radius);

            Vector4d stoc_w = (stoc * Vector4d.UnitW()).XYZ0();
            Vector4d stoc_x = (stoc * Vector4d.UnitX()).XYZ0();
            Vector4d stoc_y = (stoc * Vector4d.UnitY()).XYZ0();

            Vector3d2 A0 = (cameraToOcean * stoc_w).XYZ();
            Vector3d2 dA = (cameraToOcean * stoc_x).XYZ();
            Vector3d2 B =  (cameraToOcean * stoc_y).XYZ();

            Vector3d2 horizon1, horizon2;

            Vector3d2 offset = new Vector3d2(-m_offset.x, -m_offset.y, h);

            //			print ("offset");
            //			print (offset);

            double h1 = h * (h + 2.0 * radius);
            double h2 = (h + radius) * (h + radius);
            double alpha = B.Dot(B) * h1 - B.z * B.z * h2;

            double beta0 = (A0.Dot(B) * h1 - B.z * A0.z * h2) / alpha;
            double beta1 = (dA.Dot(B) * h1 - B.z * dA.z * h2) / alpha;

            double gamma0 = (A0.Dot(A0) * h1 - A0.z * A0.z * h2) / alpha;
            double gamma1 = (A0.Dot(dA) * h1 - A0.z * dA.z * h2) / alpha;
            double gamma2 = (dA.Dot(dA) * h1 - dA.z * dA.z * h2) / alpha;

            horizon1 = new Vector3d2(-beta0, -beta1, 0.0);
            horizon2 = new Vector3d2(beta0 * beta0 - gamma0, 2.0 * (beta0 * beta1 - gamma1), beta1 * beta1 - gamma2);

            Vector3d2 sunDir = new Vector3d2 (m_manager.getDirectionToSun ().normalized);
            Vector3d2 oceanSunDir = localToOcean.ToMatrix3x3d() * sunDir;

            m_oceanMaterial.SetVector("_Ocean_SunDir", oceanSunDir.ToVector3());

            m_oceanMaterial.SetVector("_Ocean_Horizon1", horizon1.ToVector3());
            m_oceanMaterial.SetVector("_Ocean_Horizon2", horizon2.ToVector3());

            m_oceanMaterial.SetMatrix("_Ocean_CameraToOcean", cameraToOcean.ToMatrix4x4());
            m_oceanMaterial.SetMatrix("_Ocean_OceanToCamera", cameraToOcean.Inverse().ToMatrix4x4());

            m_oceanMaterial.SetMatrix ("_Globals_CameraToScreen", ctos.ToMatrix4x4 ());
            m_oceanMaterial.SetMatrix ("_Globals_ScreenToCamera", stoc.ToMatrix4x4 ());

            m_oceanMaterial.SetVector("_Ocean_CameraPos", offset.ToVector3());

            m_oceanMaterial.SetVector("_Ocean_Color", m_oceanUpwellingColor * 0.1f);
            m_oceanMaterial.SetVector("_Ocean_ScreenGridSize", new Vector2((float)m_resolution / (float)Screen.width, (float)m_resolution / (float)Screen.height));
            m_oceanMaterial.SetFloat("_Ocean_Radius", (float)radius);

            m_oceanMaterial.SetFloat("scale", 1);

            m_manager.GetSkyNode().SetOceanUniforms(m_oceanMaterial);
        }
示例#36
0
	public Matrix4x4d Transpose()
	{
	    Matrix4x4d kTranspose = new Matrix4x4d();
	    for (int iRow = 0; iRow < 4; iRow++) {
	        for (int iCol = 0; iCol < 4; iCol++) {
	            kTranspose.m[iRow,iCol] = m[iCol,iRow];
	        }
	    }
	    return kTranspose;
	}
示例#37
0
	public static Matrix4x4d operator *(Matrix4x4d m, double s)
	{
		Matrix4x4d kProd = new Matrix4x4d();
		for (int iRow = 0; iRow < 4; iRow++) {
			for (int iCol = 0; iCol < 4; iCol++) {
		    	kProd.m[iRow,iCol] = m.m[iRow,iCol] * s;
			}
		}
		return kProd;
	}
示例#38
0
        /*
        * Computes the world to camera matrix using double precision
        * and applies it to the camera.
        */
        protected virtual void SetWorldToCameraMatrix()
        {
            Vector3d2 po = new Vector3d2(m_position.x0, m_position.y0, 0.0);
            Vector3d2 px = new Vector3d2(1.0, 0.0, 0.0);
            Vector3d2 py = new Vector3d2(0.0, 1.0, 0.0);
            Vector3d2 pz = new Vector3d2(0.0, 0.0, 1.0);

            double ct = Math.Cos(m_position.theta);
            double st = Math.Sin(m_position.theta);
            double cp = Math.Cos(m_position.phi);
            double sp = Math.Sin(m_position.phi);

            Vector3d2 cx = px * cp + py * sp;
            Vector3d2 cy = (px*-1.0) * sp*ct + py * cp*ct + pz * st;
            Vector3d2 cz = px * sp*st - py * cp*st + pz * ct;

            m_worldPos = po + cz * m_position.distance;

            if (m_worldPos.z < m_groundHeight + 10.0) {
                m_worldPos.z = m_groundHeight + 10.0;
            }

            Matrix4x4d view = new Matrix4x4d(	cx.x, cx.y, cx.z, 0.0,
                                                cy.x, cy.y, cy.z, 0.0,
                                                cz.x, cz.y, cz.z, 0.0,
                                                0.0, 0.0, 0.0, 1.0);

            m_worldToCameraMatrix = view * Matrix4x4d.Translate(m_worldPos * -1.0);

            m_worldToCameraMatrix.m[0,0] *= -1.0;
            m_worldToCameraMatrix.m[0,1] *= -1.0;
            m_worldToCameraMatrix.m[0,2] *= -1.0;
            m_worldToCameraMatrix.m[0,3] *= -1.0;

            m_cameraToWorldMatrix = m_worldToCameraMatrix.Inverse();

            camera.worldToCameraMatrix = m_worldToCameraMatrix.ToMatrix4x4();
            camera.transform.position = m_worldPos.ToVector3();
        }
示例#39
0
        // Use this for initialization
        protected virtual void Start()
        {
            m_worldToCameraMatrix = Matrix4x4d.Identity();
            m_cameraToWorldMatrix = Matrix4x4d.Identity();
            m_cameraToScreenMatrix = Matrix4x4d.Identity();
            m_screenToCameraMatrix = Matrix4x4d.Identity();
            m_worldCameraPos = new Vector3d2();
            m_cameraDir = new Vector3d2();
            m_worldPos = new Vector3d2();

            Constrain();
        }
示例#40
0
        public void SetUniforms(Material mat)
        {
            //Sets uniforms that this or other gameobjects may need
            if(mat == null) return;
            //mat.SetFloat ("atmosphereGlobalScale", atmosphereGlobalScale);

            mat.SetFloat ("_Alpha_Cutoff", alphaCutoff);
            mat.SetFloat ("_Alpha_Global", alphaGlobal);

            mat.SetFloat("scale",atmosphereGlobalScale);
            mat.SetFloat("Rg", Rg*atmosphereGlobalScale);
            mat.SetFloat("Rt", Rt*atmosphereGlobalScale);
            mat.SetFloat("RL", RL*atmosphereGlobalScale);

            //			if (debugSettings [5])
            if(!MapView.MapIsEnabled)
            {
                mat.SetFloat ("_Globals_ApparentDistance", apparentDistance);
            }
            else
            {
                mat.SetFloat("_Globals_ApparentDistance", (float)(parentCelestialBody.Radius/100.2f));
            }

            //			if (debugSettings[1])
            if(!MapView.MapIsEnabled)
            {

                mat.SetMatrix ("_Globals_WorldToCamera", farCamera.worldToCameraMatrix);
                mat.SetMatrix ("_Globals_CameraToWorld", farCamera.worldToCameraMatrix.inverse);
            }

            else
            {
                mat.SetMatrix ("_Globals_WorldToCamera", scaledSpaceCamera.worldToCameraMatrix);
                mat.SetMatrix ("_Globals_CameraToWorld", scaledSpaceCamera.worldToCameraMatrix.inverse);
            }

            mat.SetVector("betaR", m_betaR / 1000.0f);
            mat.SetFloat("mieG", Mathf.Clamp(m_mieG, 0.0f, 0.99f));
            mat.SetTexture("_Sky_Transmittance", m_transmit);
            mat.SetTexture("_Sky_Inscatter", m_inscatter);
            mat.SetTexture("_Sky_Irradiance", m_irradiance);
            //			mat.SetTexture("_Sky_Map", m_skyMap);
            mat.SetFloat("_Sun_Intensity", sun_intensity);
            mat.SetVector("_Sun_WorldSunDir", m_manager.getDirectionToSun().normalized);
            //			mat.SetVector("_Sun_WorldSunDir", m_manager.getDirectionToSun());

            //			//copied from m_manager's set uniforms

            Matrix4x4 p;
            //			if (debugSettings [2])
            if(!MapView.MapIsEnabled)
            {
                p = farCamera.projectionMatrix;
            }
            else
            {
                p = scaledSpaceCamera.projectionMatrix;
            }

            m_cameraToScreenMatrix = new Matrix4x4d (p);
            mat.SetMatrix ("_Globals_CameraToScreen", m_cameraToScreenMatrix.ToMatrix4x4 ());
            mat.SetMatrix ("_Globals_ScreenToCamera", m_cameraToScreenMatrix.Inverse ().ToMatrix4x4 ());

            //			if (debugSettings [3])
            {
                mat.SetVector ("_Globals_WorldCameraPos", farCamera.transform.position);
            }
            //			else
            //			{
            //				Vector3 newpos= ScaledSpace.ScaledToLocalSpace(scaledSpaceCamera.transform.position);
            //				//				m_skyMaterial.SetVector ("_Globals_WorldCameraPos", scaledSpaceCamera.transform.position);
            //				mat.SetVector ("_Globals_WorldCameraPos", newpos);
            //			}

            //			if (debugSettings [4])
            if(!MapView.MapIsEnabled)
            {
                mat.SetVector ("_Globals_Origin", parentCelestialBody.transform.position);
            }
            else
            {

                Transform celestialTransform = ScaledSpace.Instance.scaledSpaceTransforms.Single(t => t.name == parentCelestialBody.name);
                Vector3 idek =celestialTransform.position;
                mat.SetVector ("_Globals_Origin", idek);

            }

            mat.SetFloat ("_Exposure", m_HDRExposure);
        }
示例#41
0
        /*
        * Get a copy of the projection matrix and convert in to double precision
        * and apply the bias if using dx11 and flip Y if deferred rendering is used
        */
        protected virtual void SetProjectionMatrix()
        {
            float h = (float)(GetHeight() - m_groundHeight);
            camera.nearClipPlane = 0.1f * h;
            camera.farClipPlane = 1e6f * h;

            camera.ResetProjectionMatrix();

            Matrix4x4 p = camera.projectionMatrix;
            bool d3d = SystemInfo.graphicsDeviceVersion.IndexOf("Direct3D") > -1;

            if(d3d)
            {
                if(camera.actualRenderingPath == RenderingPath.DeferredLighting)
                {
                    // Invert Y for rendering to a render texture
                    for (int i = 0; i < 4; i++) {
                        p[1,i] = -p[1,i];
                    }
                }

                // Scale and bias depth range
                for (int i = 0; i < 4; i++) {
                    p[2,i] = p[2,i]*0.5f + p[3,i]*0.5f;
                }
            }

            m_cameraToScreenMatrix = new Matrix4x4d(p);
            m_screenToCameraMatrix = m_cameraToScreenMatrix.Inverse();
        }
示例#42
0
        /**
        * Sets the shader uniforms that are necessary to project on screen the
        * TerrainQuad of the given TerrainNode. This method can set the uniforms
        * that are common to all the quads of the given terrain.
        */
        public virtual void SetUniforms(TerrainNode node, Material mat)
        {
            if(mat == null || node == null) return;

            float d1 = node.GetSplitDist() + 1.0f;
            float d2 = 2.0f * node.GetSplitDist();
            mat.SetVector(m_uniforms.blending, new Vector2(d1, d2 - d1));

            m_localToCamera = node.GetView().GetWorldToCamera() * node.GetLocalToWorld();
            m_localToScreen = node.GetView().GetCameraToScreen() * m_localToCamera;

            Vector3d2 localCameraPos = node.GetLocalCameraPos();
            Vector3d2 worldCamera = node.GetView().GetWorldCameraPos();

            Matrix4x4d A = LocalToDeformedDifferential(localCameraPos);
            Matrix4x4d B = DeformedToTangentFrame(worldCamera);

            Matrix4x4d ltot = B * node.GetLocalToWorld() * A;

            m_localToTangent = new Matrix3x3d(	ltot.m[0,0], ltot.m[0,1], ltot.m[0,3],
                                              ltot.m[1,0], ltot.m[1,1], ltot.m[1,3],
                                              ltot.m[3,0], ltot.m[3,1], ltot.m[3,3]);

            mat.SetMatrix(m_uniforms.localToScreen, m_localToScreen.ToMatrix4x4());
            mat.SetMatrix(m_uniforms.localToWorld, node.GetLocalToWorld().ToMatrix4x4());
        }
示例#43
0
        protected virtual void SetScreenUniforms(TerrainNode node, TerrainQuad quad, MaterialPropertyBlock matPropertyBlock)
        {
            double ox = quad.GetOX();
            double oy = quad.GetOY();
            double l = quad.GetLength();

            Vector3d2 p0 = new Vector3d2(ox, oy, 0.0);
            Vector3d2 p1 = new Vector3d2(ox + l, oy, 0.0);
            Vector3d2 p2 = new Vector3d2(ox, oy + l, 0.0);
            Vector3d2 p3 = new Vector3d2(ox + l, oy + l, 0.0);

            Matrix4x4d corners = new Matrix4x4d(p0.x, p1.x, p2.x, p3.x,
                                                p0.y, p1.y, p2.y, p3.y,
                                                p0.z, p1.z, p2.z, p3.z,
                                                1.0, 1.0, 1.0, 1.0);

            matPropertyBlock.AddMatrix(m_uniforms.screenQuadCorners, (m_localToScreen * corners).ToMatrix4x4());

            Matrix4x4d verticals = new Matrix4x4d(	0.0, 0.0, 0.0, 0.0,
                                                  0.0, 0.0, 0.0, 0.0,
                                                  1.0, 1.0, 1.0, 1.0,
                                                  0.0, 0.0, 0.0, 0.0);

            matPropertyBlock.AddMatrix(m_uniforms.screenQuadVerticals, (m_localToScreen * verticals).ToMatrix4x4());
        }
示例#44
0
        void UpdatePostProcessMaterial(Material mat)
        {
            //mat.SetFloat ("atmosphereGlobalScale", atmosphereGlobalScale);
            //			mat.SetFloat ("Rg", Rg*atmosphereGlobalScale*postProcessingScale);
            //			mat.SetFloat("Rt", Rt*atmosphereGlobalScale*postProcessingScale);
            //			mat.SetFloat("Rl", RL*atmosphereGlobalScale*postProcessingScale);

            totalscale = 1;
            totalscale2 = 1;
            for (int j = 0; j < 5; j++) {
            totalscale = totalscale * additionalScales[j];
            }

            for (int j = 6; j < 10; j++) {
            totalscale2 = totalscale2 * additionalScales[j];
            }

            mat.SetFloat("Rg", Rg * atmosphereGlobalScale * totalscale);
            mat.SetFloat("Rt", Rt * atmosphereGlobalScale * totalscale);
            mat.SetFloat("Rl", RL * atmosphereGlobalScale * totalscale);

            //mat.SetFloat("_inscatteringCoeff", inscatteringCoeff);
            mat.SetFloat("_extinctionCoeff", extinctionCoeff);
            mat.SetFloat("_global_alpha", postProcessingAlpha);
            mat.SetFloat("_Exposure", postProcessExposure);
            mat.SetFloat("_global_depth", postProcessDepth);
            mat.SetFloat("_global_depth2", totalscale2);

            mat.SetFloat("terrain_reflectance", terrainReflectance);
            mat.SetFloat("_irradianceFactor", irradianceFactor);

            mat.SetFloat("_Scale", postProcessingScale);
            //			mat.SetFloat("_Scale", 1);

            mat.SetFloat("_Ocean_Sigma", oceanSigma);
            mat.SetFloat("_Ocean_Threshold", _Ocean_Threshold);

            //			mat.SetMatrix ("_Globals_CameraToWorld", cams [0].worldToCameraMatrix.inverse);
            if (debugSettings[1]) {
            mat.SetMatrix("_Globals_CameraToWorld", farCamera.worldToCameraMatrix.inverse);
            } else {
            mat.SetMatrix("_Globals_CameraToWorld", scaledSpaceCamera.worldToCameraMatrix.inverse);
            }

            if (debugSettings[2]) {
            mat.SetVector("_CameraForwardDirection", farCamera.transform.forward);
            } else {
            mat.SetVector("_CameraForwardDirection", scaledSpaceCamera.transform.forward);
            }

            if (debugSettings[3]) {
            mat.SetVector("_Globals_Origin", /*Vector3.zero-*/ parentCelestialBody.transform.position);
            } else

            {

            //				celestialTransform = ScaledSpace.Instance.scaledSpaceTransforms.Single(t => t.name == parentCelestialBody.name);
            celestialTransform = ParentPlanetTransform;
            idek = celestialTransform.position;
            mat.SetVector("_Globals_Origin", /*Vector3.zero-*/ idek);
            }

            //mat.SetVector("betaR", m_betaR / (Rg / m_radius));
            //			mat.SetVector("betaR", m_betaR / (postProcessDepth));
            mat.SetVector("betaR", new Vector4(2.9e-3f, 0.675e-2f, 1.655e-2f, 0.0f));
            mat.SetFloat("mieG", 0.4f);
            mat.SetVector("SUN_DIR", m_manager.GetSunNodeDirection());
            mat.SetFloat("SUN_INTENSITY", sunIntensity);

            Matrix4x4 ctol1 = farCamera.cameraToWorldMatrix;
            Vector3d tmp = (farCamera.transform.position) - m_manager.parentCelestialBody.transform.position;

            Matrix4x4d viewMat = new Matrix4x4d(ctol1.m00, ctol1.m01, ctol1.m02, tmp.x,
                                            ctol1.m10, ctol1.m11, ctol1.m12, tmp.y,
                                            ctol1.m20, ctol1.m21, ctol1.m22, tmp.z,
                                            ctol1.m30, ctol1.m31, ctol1.m32, ctol1.m33);

            //			print ("viewmat");
            //			print (viewMat.ToMatrix4x4());

            //			Matrix4x4 viewMat = farCamera.worldToCameraMatrix;
            viewMat = viewMat.Inverse();
            Matrix4x4 projMat = GL.GetGPUProjectionMatrix(farCamera.projectionMatrix, false);

            //			projMat.m23 = projMat.m23 * 0.5f;

            //			print ("projmat");
            //			print (projMat);

            Matrix4x4 viewProjMat = (projMat * viewMat.ToMatrix4x4());
            mat.SetMatrix("_ViewProjInv", viewProjMat.inverse);

            //			mat.SetMatrix("_ViewToWorld", viewMat.ToMatrix4x4());
            //
            //			var lpoints = RecalculateFrustrumPoints(farCamera);
            //			mat.SetVector("_FrustrumPoints", new Vector4(
            //				lpoints[4].x,lpoints[5].x,lpoints[5].y,lpoints[6].y));
            //
            //			mat.SetFloat("_CameraFar", farCamera.farClipPlane);
        }
示例#45
0
        public void SetUniforms(Material mat)
        {
            //Sets uniforms that this or other gameobjects may need
            if (mat == null) return;

            mat.SetFloat("_Extinction_Cutoff", ExtinctionCutoff);
            if (!MapView.MapIsEnabled) {
            mat.SetFloat("_Alpha_Global", alphaGlobal);
            mat.SetFloat("_Extinction_Tint", extinctionTint);
            mat.SetFloat("extinctionMultiplier", extinctionMultiplier);
            } else {
            mat.SetFloat("_Alpha_Global", mapAlphaGlobal);
            mat.SetFloat("_Extinction_Tint", mapExtinctionTint);
            mat.SetFloat("extinctionMultiplier", mapExtinctionMultiplier);
            }

            mat.SetFloat("scale", atmosphereGlobalScale);
            mat.SetFloat("Rg", Rg * atmosphereGlobalScale);
            mat.SetFloat("Rt", Rt * atmosphereGlobalScale);
            mat.SetFloat("RL", RL * atmosphereGlobalScale);

            //						if (debugSettings [5])
            if (!MapView.MapIsEnabled) {
            mat.SetFloat("_Globals_ApparentDistance", 1f);
            } else {
            mat.SetFloat("_Globals_ApparentDistance", (float)((parentCelestialBody.Radius / 100.2f) / MapViewScale));
            //				mat.SetFloat ("_Globals_ApparentDistance", MapViewScale);
            }

            //						if (debugSettings[1])
            if (!MapView.MapIsEnabled) {

            mat.SetMatrix("_Globals_WorldToCamera", farCamera.worldToCameraMatrix);
            mat.SetMatrix("_Globals_CameraToWorld", farCamera.worldToCameraMatrix.inverse);
            } else {
            mat.SetMatrix("_Globals_WorldToCamera", scaledSpaceCamera.worldToCameraMatrix);
            mat.SetMatrix("_Globals_CameraToWorld", scaledSpaceCamera.worldToCameraMatrix.inverse);
            }

            mat.SetVector("betaR", m_betaR / 1000.0f);
            mat.SetFloat("mieG", Mathf.Clamp(m_mieG, 0.0f, 0.99f));
            mat.SetTexture("_Sky_Transmittance", m_transmit);
            mat.SetTexture("_Sky_Inscatter", m_inscatter);
            mat.SetTexture("_Sky_Irradiance", m_irradiance);
            mat.SetFloat("_Sun_Intensity", 100f);
            mat.SetVector("_Sun_WorldSunDir", m_manager.getDirectionToSun().normalized);
            //			mat.SetVector("_Sun_WorldSunDir", m_manager.getDirectionToSun());

            //			//copied from m_manager's set uniforms

            //Matrix4x4 p;
            //						if (debugSettings [2])
            if (!MapView.MapIsEnabled) {
            p = farCamera.projectionMatrix;
            } else {
            p = scaledSpaceCamera.projectionMatrix;
            }

            m_cameraToScreenMatrix = new Matrix4x4d(p);
            mat.SetMatrix("_Globals_CameraToScreen", m_cameraToScreenMatrix.ToMatrix4x4());
            mat.SetMatrix("_Globals_ScreenToCamera", m_cameraToScreenMatrix.Inverse().ToMatrix4x4());

            //						if (debugSettings [3])
            if (!MapView.MapIsEnabled) {
            mat.SetVector("_Globals_WorldCameraPos", farCamera.transform.position);
            } else {
            mat.SetVector("_Globals_WorldCameraPos", scaledSpaceCamera.transform.position);
            }
            //			else
            //			{
            //				Vector3 newpos= ScaledSpace.ScaledToLocalSpace(scaledSpaceCamera.transform.position);
            //				//				m_skyMaterial.SetVector ("_Globals_WorldCameraPos", scaledSpaceCamera.transform.position);
            //				mat.SetVector ("_Globals_WorldCameraPos", newpos);
            //			}
            //
            //						if (debugSettings [4])
            if (!MapView.MapIsEnabled) {
            mat.SetVector("_Globals_Origin", parentCelestialBody.transform.position);

            } else {

            //				celestialTransform = ScaledSpace.Instance.scaledSpaceTransforms.Single(t => t.name == parentCelestialBody.name);
            celestialTransform = ParentPlanetTransform;
            //				idek =celestialTransform.position;
            idek = celestialTransform.position - scaledSpaceCamera.transform.position;
            mat.SetVector("_Globals_Origin", idek);

            }

            if (!MapView.MapIsEnabled) {
            mat.SetFloat("_Exposure", m_HDRExposure);
            } else {
            mat.SetFloat("_Exposure", mapExposure);
            }

            //			int childCnt = 0;
            //			Transform scaledSunTransform=ScaledSpace.Instance.scaledSpaceTransforms.Single(t => t.name == "Sun");
            //			foreach (Transform child in scaledSunTransform)
            //			{
            //				print(childCnt);
            //				print(child.gameObject.name);
            //				childCnt++;
            //				MeshRenderer temp;
            //				temp = child.gameObject.GetComponent<MeshRenderer>();
            ////				temp.enabled=false;
            //				print(temp.enabled);
            //			}
        }
示例#46
0
	public Matrix4x4d(Matrix4x4d m)
	{
		System.Array.Copy(m.m, this.m, 16);
	}
示例#47
0
        // Use this for initialization
        public virtual void Start()
        {
            //			base.Start();
            m_cameraToWorldMatrix = Matrix4x4d.Identity();

            m_oceanMaterial=new Material(ShaderTool.GetMatFromShader2("CompiledOceanWhiteCaps.shader"));

            m_manager.GetSkyNode().InitUniforms(m_oceanMaterial);

            m_oldlocalToOcean = Matrix4x4d.Identity();
            m_oldworldToOcean = Matrix4x4d.Identity();
            m_offset = Vector3d2.Zero();

            //Create the projected grid. The resolution is the size in pixels
            //of each square in the grid. If the squares are small the size of
            //the mesh will exceed the max verts for a mesh in Unity. In this case
            //split the mesh up into smaller meshes.

            m_resolution = Mathf.Max(1, m_resolution);
            //The number of squares in the grid on the x and y axis
            int NX = Screen.width / m_resolution;
            int NY = Screen.height / m_resolution;
            numGrids = 1;

            const int MAX_VERTS = 65000;
            //The number of meshes need to make a grid of this resolution
            if(NX*NY > MAX_VERTS)
            {
                numGrids += (NX*NY) / MAX_VERTS;
            }

            m_screenGrids = new Mesh[numGrids];
            waterGameObjects = new GameObject[numGrids];
            waterMeshRenderers = new MeshRenderer[numGrids];
            waterMeshFilters = new MeshFilter[numGrids];

            //Make the meshes. The end product will be a grid of verts that cover
            //the screen on the x and y axis with the z depth at 0. This grid is then
            //projected as the ocean by the shader
            for(int i = 0; i < numGrids; i++)
            {
                NY = Screen.height / numGrids / m_resolution;

                m_screenGrids[i] = MakePlane(NX, NY, (float)i / (float)numGrids, 1.0f / (float)numGrids);
                m_screenGrids[i].bounds = new Bounds(Vector3.zero, new Vector3(1e8f, 1e8f, 1e8f));

                waterGameObjects[i] = new GameObject();
                waterGameObjects[i].transform.parent=m_manager.parentCelestialBody.transform;
                waterMeshFilters[i] = waterGameObjects[i].AddComponent<MeshFilter>();
                waterMeshFilters[i].mesh.Clear ();
                waterMeshFilters[i].mesh = m_screenGrids[i];
                //
                waterGameObjects[i].layer = 15;
            //				celestialTransform = ScaledSpace.Instance.scaledSpaceTransforms.Single(t => t.name == parentCelestialBody.name);
            //				//			tester.transform.parent = parentCelestialBody.transform;
            //				tester.transform.parent = celestialTransform;

                waterMeshRenderers[i] = waterGameObjects[i].AddComponent<MeshRenderer>();

                //			InitUniforms (m_skyMaterialScaled);
                //			SetUniforms(m_skyMaterialScaled);

                waterMeshRenderers[i].sharedMaterial = m_oceanMaterial;
                waterMeshRenderers[i].material =m_oceanMaterial;

                waterMeshRenderers[i].castShadows = false;
                waterMeshRenderers[i].receiveShadows = false;

                waterMeshRenderers[i].enabled=true;

                //waterMeshRenderers[i].isVisible=true;

            }
        }
示例#48
0
		public Matrix4x4d ModifiedProjectionMatrix (Camera inCam)
		{
			/*
//			float h = (float)(GetHeight() - m_groundHeight);
//			camera.nearClipPlane = 0.1f * h;
//			camera.farClipPlane = 1e6f * h;
			
//			inCam.ResetProjectionMatrix();
			
			Matrix4x4 p = inCam.projectionMatrix;
//			bool d3d = SystemInfo.graphicsDeviceVersion.IndexOf("Direct3D") > -1;
			
//			if(d3d) 
//			{
//				if(inCam.actualRenderingPath == RenderingPath.DeferredLighting)
//				{
//					// Invert Y for rendering to a render texture
//					for (int i = 0; i < 4; i++) {
//						p[1,i] = -p[1,i];
//					}
//				}
//				
//				// Scale and bias depth range
//				for (int i = 0; i < 4; i++) {
//					p[2,i] = p[2,i]*0.5f + p[3,i]*0.5f;
//				}
//			}
			
			Matrix4x4d m_cameraToScreenMatrix = new Matrix4x4d(p);
			inCam.projectionMatrix = m_cameraToScreenMatrix.ToMatrix4x4(); */
			
			Matrix4x4 p;
			//			if (debugSettings [2])
			//			if(!MapView.MapIsEnabled)
			//			{
			//			float tmpNearclip = inCam.nearClipPlane;
			//			float tmpFarclip = inCam.farClipPlane;
			//			
			//			inCam.nearClipPlane = m_manager.m_skyNode.oceanNearPlane;
			//			inCam.farClipPlane = m_manager.m_skyNode.oceanFarPlane;
			
			//			float h = (float)(GetHeight() - m_groundHeight);
			//			m_manager.GetCore ().chosenCamera.nearClipPlane = 0.1f * (alt - m_radius);
			//			m_manager.GetCore ().chosenCamera.farClipPlane = 1e6f * (alt - m_radius);
			
			p = inCam.projectionMatrix;
			
			{
				//				if(camera.actualRenderingPath == RenderingPath.DeferredLighting)
				//				{
				//					// Invert Y for rendering to a render texture
				//										for (int i = 0; i < 4; i++) {
				//											p[1,i] = -p[1,i];
				//										}
				//				}

				//if OpenGL isn't detected
				// Scale and bias depth range
				if (!m_core.opengl)
					for (int i = 0; i < 4; i++) {
						p [2, i] = p [2, i] * 0.5f + p [3, i] * 0.5f;
					}
			}
			
			//			p = scaledSpaceCamera.projectionMatrix;
			
			//			inCam.nearClipPlane=tmpNearclip;
			//			inCam.farClipPlane=tmpFarclip;
			
			//			p = scaledSpaceCamera.projectionMatrix;
			//			}
			//			else
			//			{
			//				p = scaledSpaceCamera.projectionMatrix;
			//			}
			
			
			Matrix4x4d m_cameraToScreenMatrix = new Matrix4x4d (p);
			
			
			return m_cameraToScreenMatrix;
		}
示例#49
0
        protected override void SetWorldToCameraMatrix()
        {
            double co = Math.Cos(m_position.x0); // x0 = longitude
            double so = Math.Sin(m_position.x0);
            double ca = Math.Cos(m_position.y0); // y0 = latitude
            double sa = Math.Sin(m_position.y0);

            Vector3d2 po = new Vector3d2(co*ca, so*ca, sa) * m_radius;
            Vector3d2 px = new Vector3d2(-so, co, 0.0);
            Vector3d2 py = new Vector3d2(-co*sa, -so*sa, ca);
            Vector3d2 pz = new Vector3d2(co*ca, so*ca, sa);

            double ct = Math.Cos(m_position.theta);
            double st = Math.Sin(m_position.theta);
            double cp = Math.Cos(m_position.phi);
            double sp = Math.Sin(m_position.phi);

            Vector3d2 cx = px * cp + py * sp;
            Vector3d2 cy = (px*-1.0) * sp*ct + py * cp*ct + pz * st;
            Vector3d2 cz = px * sp*st - py * cp*st + pz * ct;

            m_worldPos = po + cz * m_position.distance;

            if (m_worldPos.Magnitude() < m_radius + 10.0 + m_groundHeight) {
                m_worldPos = m_worldPos.Normalized(m_radius + 10.0 + m_groundHeight);
            }

            Matrix4x4d view = new Matrix4x4d(	cx.x, cx.y, cx.z, 0.0,
                       							cy.x, cy.y, cy.z, 0.0,
                       							cz.x, cz.y, cz.z, 0.0,
                       							0.0, 0.0, 0.0, 1.0);

            m_worldToCameraMatrix = view * Matrix4x4d.Translate(m_worldPos * -1.0);

            //Flip first row to match Unitys winding order.
            m_worldToCameraMatrix.m[0,0] *= -1.0;
            m_worldToCameraMatrix.m[0,1] *= -1.0;
            m_worldToCameraMatrix.m[0,2] *= -1.0;
            m_worldToCameraMatrix.m[0,3] *= -1.0;

            m_cameraToWorldMatrix = m_worldToCameraMatrix.Inverse();

            camera.worldToCameraMatrix = m_worldToCameraMatrix.ToMatrix4x4();
            camera.transform.position = m_worldPos.ToVector3();
        }
示例#50
0
	//Static Function
	
	static public Matrix4x4d ToMatrix4x4d(Matrix4x4 matf)
	{
		Matrix4x4d mat = new Matrix4x4d();
		
		mat.m[0,0] = matf.m00; mat.m[0,1] = matf.m01; mat.m[0,2] = matf.m02; mat.m[0,3] = matf.m03;
		mat.m[1,0] = matf.m10; mat.m[1,1] = matf.m11; mat.m[1,2] = matf.m12; mat.m[1,3] = matf.m13;
		mat.m[2,0] = matf.m20; mat.m[2,1] = matf.m21; mat.m[2,2] = matf.m22; mat.m[2,3] = matf.m23;
		mat.m[3,0] = matf.m30; mat.m[3,1] = matf.m31; mat.m[3,2] = matf.m32; mat.m[3,3] = matf.m33;
		
		return mat;
	}
示例#51
0
		// Use this for initialization
		public virtual void Start ()
		{
			m_cameraToWorldMatrix = Matrix4x4d.Identity ();
			
			//using different materials for both the far and near cameras because they have different projection matrixes
			//the projection matrix in the shader has to match that of the camera or the projection will be wrong and the ocean will
			//appear to "shift around"
			m_oceanMaterialNear = new Material (ShaderTool.GetMatFromShader2 ("CompiledOceanWhiteCaps.shader"));
			m_oceanMaterialFar = new Material (ShaderTool.GetMatFromShader2 ("CompiledOceanWhiteCaps.shader"));
			
			m_manager.GetSkyNode ().InitUniforms (m_oceanMaterialNear);
			m_manager.GetSkyNode ().InitUniforms (m_oceanMaterialFar);
			
			m_oldlocalToOcean = Matrix4x4d.Identity ();
			m_oldworldToOcean = Matrix4x4d.Identity ();
			m_offset = Vector3d2.Zero ();
			
			//Create the projected grid. The resolution is the size in pixels
			//of each square in the grid. If the squares are small the size of
			//the mesh will exceed the max verts for a mesh in Unity. In this case
			//split the mesh up into smaller meshes.
			
			m_resolution = Mathf.Max (1, m_resolution);
			//The number of squares in the grid on the x and y axis
			int NX = Screen.width / m_resolution;
			int NY = Screen.height / m_resolution;
			numGrids = 1;
			
			//			const int MAX_VERTS = 65000;
			//The number of meshes need to make a grid of this resolution
			if (NX * NY > MAX_VERTS) {
				numGrids += (NX * NY) / MAX_VERTS;
			}
			
			m_screenGrids = new Mesh[numGrids];

//			waterGameObjectsNear = new GameObject[numGrids];
//			waterMeshRenderersNear = new MeshRenderer[numGrids];
//			waterMeshFiltersNear = new MeshFilter[numGrids];
//
//			waterGameObjectsFar = new GameObject[numGrids];
//			waterMeshRenderersFar = new MeshRenderer[numGrids];
//			waterMeshFiltersFar = new MeshFilter[numGrids];

			//Make the meshes. The end product will be a grid of verts that cover
			//the screen on the x and y axis with the z depth at 0. This grid is then
			//projected as the ocean by the shader
			for (int i = 0; i < numGrids; i++) {
				NY = Screen.height / numGrids / m_resolution;
				
				m_screenGrids [i] = MakePlane (NX, NY, (float)i / (float)numGrids, 1.0f / (float)numGrids);
				m_screenGrids [i].bounds = new Bounds (Vector3.zero, new Vector3 (1e8f, 1e8f, 1e8f));
				

				//bad idea, the meshes still render arbitrarily to the near and far camera and end up drawing over everything
				//to get around this I use drawmesh further down
				//seems to have better performance also

//								waterGameObjectsNear[i] = new GameObject();
//								waterGameObjectsNear[i].transform.parent=m_manager.parentCelestialBody.transform;
//								waterMeshFiltersNear[i] = waterGameObjectsNear[i].AddComponent<MeshFilter>();
//								waterMeshFiltersNear[i].mesh.Clear ();
//								waterMeshFiltersNear[i].mesh = m_screenGrids[i];
//								waterGameObjectsNear[i].layer = 15;
//
//								waterMeshRenderersNear[i] = waterGameObjectsNear[i].AddComponent<MeshRenderer>();
//
//								waterMeshRenderersNear[i].sharedMaterial = m_oceanMaterialNear;
//								waterMeshRenderersNear[i].material =m_oceanMaterialNear;
//								
//								waterMeshRenderersNear[i].castShadows = false;
//								waterMeshRenderersNear[i].receiveShadows = false;
//				
//								waterMeshRenderersNear[i].enabled=true;
//
//
//				waterGameObjectsFar[i] = new GameObject();
//				waterGameObjectsFar[i].transform.parent=m_manager.parentCelestialBody.transform;
//				waterMeshFiltersFar[i] = waterGameObjectsFar[i].AddComponent<MeshFilter>();
//				waterMeshFiltersFar[i].mesh.Clear ();
//				waterMeshFiltersFar[i].mesh = m_screenGrids[i];
//				waterGameObjectsFar[i].layer = 15;
//				
//				waterMeshRenderersFar[i] = waterGameObjectsFar[i].AddComponent<MeshRenderer>();
//				
//				waterMeshRenderersFar[i].sharedMaterial = m_oceanMaterialFar;
//				waterMeshRenderersFar[i].material =m_oceanMaterialFar;
//				
//				waterMeshRenderersFar[i].castShadows = false;
//				waterMeshRenderersFar[i].receiveShadows = false;
//				
//				waterMeshRenderersFar[i].enabled=true;
				
			}

//			PQS pqs = m_manager.parentCelestialBody.pqsController;
//
//			if (pqs.ChildSpheres[0])
//				UnityEngine.Object.Destroy (pqs.ChildSpheres [0]);

//			if (ocean)
//			{
//				UnityEngine.Object.Destroy (ocean);
//			}



			
			//				Debug.Log("PQS.childspheres count"+pqs.ChildSpheres.Length);
			
//			PQS pqs = m_manager.parentCelestialBody.pqsController;
//			if (pqs.ChildSpheres [0]) {
//				ocean = pqs.ChildSpheres [0];
//				//					ocean.surfaceMaterial = new Material (ShaderTool.GetMatFromShader2 ("EmptyShader.shader"));
//				
//				///Thanks to rbray89 for this snippet that disables the stock ocean in a clean way
//				GameObject container = ocean.gameObject;
//				
//				FakeOceanPQS fakeOcean1 = new GameObject ().AddComponent<FakeOceanPQS> ();
//				
//				fakeOcean1.CloneFrom (ocean);
//				Destroy (ocean);
//				
//				FakeOceanPQS fakeOcean = container.AddComponent<FakeOceanPQS> ();
//				fakeOcean.CloneFrom (fakeOcean1);
//				
//				Destroy (fakeOcean1);
//				
//				FieldInfo field = typeof(PQS).GetFields (BindingFlags.Instance | BindingFlags.NonPublic).First (
//					f => f.FieldType == typeof(PQS[]));
//				field.SetValue (pqs, new PQS[] {fakeOcean });
//				
//				PQSMod_CelestialBodyTransform cbt = pqs.GetComponentsInChildren<PQSMod_CelestialBodyTransform> () [0];
//				cbt.secondaryFades = new PQSMod_CelestialBodyTransform.AltitudeFade[] { };
//			}


//			fakeOceanMesh = isosphere.Create (m_manager.GetRadius());
//
//
//			fakeOcean = new GameObject ();
//			fakeOceanMF = fakeOcean.AddComponent<MeshFilter>();
//			fakeOceanMF.mesh = fakeOceanMesh;
//			fakeOcean.layer = 15;
//
//
//			fakeOcean.transform.parent = m_manager.parentCelestialBody.transform;
//			
//			fakeOceanMR = fakeOcean.AddComponent<MeshRenderer>();
//
//			newMat = new Material (ShaderTool.GetMatFromShader2 ("BlackShader.shader"));
//			fakeOceanMR.sharedMaterial = newMat;
//			fakeOceanMR.material =newMat;
//
//			fakeOceanMR.castShadows = false;
//			fakeOceanMR.receiveShadows = false;

		}
示例#52
0
        protected override void SetScreenUniforms(TerrainNode node, TerrainQuad quad, MaterialPropertyBlock matPropertyBlock)
        {
            double ox = quad.GetOX();
            double oy = quad.GetOY();
            double l = quad.GetLength();

            Vector3d2 p0 = new Vector3d2(ox, oy, R);
            Vector3d2 p1 = new Vector3d2(ox + l, oy, R);
            Vector3d2 p2 = new Vector3d2(ox, oy + l, R);
            Vector3d2 p3 = new Vector3d2(ox + l, oy + l, R);
            Vector3d2 pc = (p0 + p3) * 0.5;

            double l0 = 0.0, l1 = 0.0, l2 = 0.0, l3 = 0.0;
            Vector3d2 v0 = p0.Normalized(ref l0);
            Vector3d2 v1 = p1.Normalized(ref l1);
            Vector3d2 v2 = p2.Normalized(ref l2);
            Vector3d2 v3 = p3.Normalized(ref l3);

            Matrix4x4d deformedCorners = new Matrix4x4d(v0.x * R, v1.x * R, v2.x * R, v3.x * R,
                                                        v0.y * R, v1.y * R, v2.y * R, v3.y * R,
                                                        v0.z * R, v1.z * R, v2.z * R, v3.z * R,
                                                        1.0, 1.0, 1.0, 1.0);

            matPropertyBlock.AddMatrix(m_uniforms.screenQuadCorners, (m_localToScreen * deformedCorners).ToMatrix4x4());

            Matrix4x4d deformedVerticals = new Matrix4x4d(	v0.x, v1.x, v2.x, v3.x,
                                                          v0.y, v1.y, v2.y, v3.y,
                                                          v0.z, v1.z, v2.z, v3.z,
                                                          0.0, 0.0, 0.0, 0.0);

            matPropertyBlock.AddMatrix(m_uniforms.screenQuadVerticals, (m_localToScreen * deformedVerticals).ToMatrix4x4());
            matPropertyBlock.AddVector(m_uniforms.screenQuadCornerNorms, new Vector4((float)l0, (float)l1, (float)l2, (float)l3));

            Vector3d2 uz = pc.Normalized();
            Vector3d2 ux = (new Vector3d2(0,1,0)).Cross(uz).Normalized();
            Vector3d2 uy = uz.Cross(ux);

            Matrix4x4d ltow = node.GetLocalToWorld();

            Matrix3x3d tangentFrameToWorld = new Matrix3x3d(ltow.m[0,0], ltow.m[0,1], ltow.m[0,2],
                                                            ltow.m[1,0], ltow.m[1,1], ltow.m[1,2],
                                                            ltow.m[2,0], ltow.m[2,1], ltow.m[2,2]);

            Matrix3x3d m = new Matrix3x3d(	ux.x, uy.x, uz.x,
                                          ux.y, uy.y, uz.y,
                                          ux.z, uy.z, uz.z);

            matPropertyBlock.AddMatrix(m_uniforms.tangentFrameToWorld, (tangentFrameToWorld * m).ToMatrix4x4());
        }
示例#53
0
		public void updateStuff (Material oceanMaterial, Camera inCamera)
		{
			//Calculates the required data for the projected grid
			
			// compute ltoo = localToOcean transform, where ocean frame = tangent space at
			// camera projection on sphere radius in local space
			
			Matrix4x4 ctol1 = inCamera.cameraToWorldMatrix;
			
			//position relative to kerbin
//			Vector3d tmp = (inCamera.transform.position) - m_manager.parentCelestialBody.transform.position;
			
			
			Matrix4x4d cameraToWorld = new Matrix4x4d (ctol1.m00, ctol1.m01, ctol1.m02, ctol1.m03,
			                                          ctol1.m10, ctol1.m11, ctol1.m12, ctol1.m13,
			                                          ctol1.m20, ctol1.m21, ctol1.m22, ctol1.m23,
			                                          ctol1.m30, ctol1.m31, ctol1.m32, ctol1.m33);
			
			
			//Looking back, I have no idea how I figured this crap out
			Vector4 translation = m_manager.parentCelestialBody.transform.worldToLocalMatrix.inverse.GetColumn (3);
			
			Matrix4x4d worldToLocal = new Matrix4x4d (1, 0, 0, -translation.x,
			                                         0, 1, 0, -translation.y,
			                                         0, 0, 1, -translation.z,
			                                         0, 0, 0, 1);

			Matrix4x4d camToLocal = worldToLocal * cameraToWorld;


			// camera in local space relative to planet's origin
			Vector3d2 cl = new Vector3d2 ();
			cl = camToLocal * Vector3d2.Zero ();
			
//			double radius = m_manager.GetRadius ();
			double radius = m_manager.GetRadius ()+m_oceanLevel;

//			Vector3d2 ux, uy, uz, oo;
			
			uz = cl.Normalized (); // unit z vector of ocean frame, in local space
			
			if (m_oldlocalToOcean != Matrix4x4d.Identity ()) {
				ux = (new Vector3d2 (m_oldlocalToOcean.m [1, 0], m_oldlocalToOcean.m [1, 1], m_oldlocalToOcean.m [1, 2])).Cross (uz).Normalized ();
			} else {
				ux = Vector3d2.UnitZ ().Cross (uz).Normalized ();
			}

			uy = uz.Cross (ux); // unit y vector
			
			oo = uz * (radius); // origin of ocean frame, in local space
			
			
			//local to ocean transform
			//computed from oo and ux, uy, uz should be correct
			Matrix4x4d localToOcean = new Matrix4x4d (
				ux.x, ux.y, ux.z, -ux.Dot (oo),
				uy.x, uy.y, uy.z, -uy.Dot (oo),
				uz.x, uz.y, uz.z, -uz.Dot (oo),
				0.0, 0.0, 0.0, 1.0);


			Matrix4x4d cameraToOcean = localToOcean * camToLocal;


			//Couldn't figure out how to change the wind's direction in all that math so I tried to do the easy thing
			//And Rotated the ocean and the sun
			//This didn't work

			//deleted rotation code here



			
			Vector3d2 delta = new Vector3d2 (0, 0, 0);
			
			if (m_oldlocalToOcean != Matrix4x4d.Identity ()) {
				delta = localToOcean * (m_oldlocalToOcean.Inverse () * Vector3d2.Zero ());
				m_offset += delta;
			}
			
			m_oldlocalToOcean = localToOcean;
			
			Matrix4x4d ctos = ModifiedProjectionMatrix (inCamera);
			Matrix4x4d stoc = ctos.Inverse ();
			
			Vector3d2 oc = cameraToOcean * Vector3d2.Zero ();
			
			h = oc.z;
			
			Vector4d stoc_w = (stoc * Vector4d.UnitW ()).XYZ0 ();
			Vector4d stoc_x = (stoc * Vector4d.UnitX ()).XYZ0 ();
			Vector4d stoc_y = (stoc * Vector4d.UnitY ()).XYZ0 ();
			
			Vector3d2 A0 = (cameraToOcean * stoc_w).XYZ ();
			Vector3d2 dA = (cameraToOcean * stoc_x).XYZ ();
			Vector3d2 B = (cameraToOcean * stoc_y).XYZ ();
			
			Vector3d2 horizon1, horizon2;
			
//			Vector3d2 offset = new Vector3d2 (-m_offset.x, -m_offset.y, h);
			offset = new Vector3d2 (-m_offset.x, -m_offset.y, h);
//			Vector3d2 offset = new Vector3d2 (0f, 0f, h);
			
			double h1 = h * (h + 2.0 * radius);
			double h2 = (h + radius) * (h + radius);
			double alpha = B.Dot (B) * h1 - B.z * B.z * h2;
			
			double beta0 = (A0.Dot (B) * h1 - B.z * A0.z * h2) / alpha;
			double beta1 = (dA.Dot (B) * h1 - B.z * dA.z * h2) / alpha;
			
			double gamma0 = (A0.Dot (A0) * h1 - A0.z * A0.z * h2) / alpha;
			double gamma1 = (A0.Dot (dA) * h1 - A0.z * dA.z * h2) / alpha;
			double gamma2 = (dA.Dot (dA) * h1 - dA.z * dA.z * h2) / alpha;
			
			horizon1 = new Vector3d2 (-beta0, -beta1, 0.0);
			horizon2 = new Vector3d2 (beta0 * beta0 - gamma0, 2.0 * (beta0 * beta1 - gamma1), beta1 * beta1 - gamma2);
			
			Vector3d2 sunDir = new Vector3d2 (m_manager.getDirectionToSun ().normalized);
			Vector3d2 oceanSunDir = localToOcean.ToMatrix3x3d () * sunDir;
			
			oceanMaterial.SetVector ("_Ocean_SunDir", oceanSunDir.ToVector3 ());
			
			oceanMaterial.SetVector ("_Ocean_Horizon1", horizon1.ToVector3 ());
			oceanMaterial.SetVector ("_Ocean_Horizon2", horizon2.ToVector3 ());
			
			oceanMaterial.SetMatrix ("_Ocean_CameraToOcean", cameraToOcean.ToMatrix4x4 ());
			oceanMaterial.SetMatrix ("_Ocean_OceanToCamera", cameraToOcean.Inverse ().ToMatrix4x4 ());
			
			oceanMaterial.SetMatrix ("_Globals_CameraToScreen", ctos.ToMatrix4x4 ());
			oceanMaterial.SetMatrix ("_Globals_ScreenToCamera", stoc.ToMatrix4x4 ());
			
			oceanMaterial.SetVector ("_Ocean_CameraPos", offset.ToVector3 ());
			
			oceanMaterial.SetVector ("_Ocean_Color", new Color(m_oceanUpwellingColor.x,m_oceanUpwellingColor.y,m_oceanUpwellingColor.z) /*  *0.1f   */);
			oceanMaterial.SetVector ("_Ocean_ScreenGridSize", new Vector2 ((float)m_resolution / (float)Screen.width, (float)m_resolution / (float)Screen.height));
			oceanMaterial.SetFloat ("_Ocean_Radius", (float)radius);
			
			//			oceanMaterial.SetFloat("scale", 1);
			oceanMaterial.SetFloat ("scale", oceanScale);

			oceanMaterial.SetFloat ("_OceanAlpha", oceanAlpha);
			oceanMaterial.SetFloat ("alphaRadius", alphaRadius);


			oceanMaterial.SetFloat ("sunReflectionMultiplier", sunReflectionMultiplier);
			oceanMaterial.SetFloat ("skyReflectionMultiplier", skyReflectionMultiplier);
			oceanMaterial.SetFloat ("seaRefractionMultiplier", seaRefractionMultiplier);


			m_manager.GetSkyNode ().SetOceanUniforms (oceanMaterial);
			
		}
示例#54
0
        public Matrix4x4d ModifiedWorldToCameraMatrix()
        {
            //			Vector3d po = new Vector3d(m_position.x0, m_position.y0, 0.0);
            Vector3d px = new Vector3d(1.0, 0.0, 0.0);                        //
            Vector3d py = new Vector3d(0.0, 1.0, 0.0);                        //
            Vector3d pz = new Vector3d(0.0, 0.0, 1.0);

            //			double ct = Math.Cos(m_position.theta);                        //
            //			double st = Math.Sin(m_position.theta);                        //
            //			double cp = Math.Cos(m_position.phi);                        //
            //			double sp = Math.Sin(m_position.phi);                        //

            double ct = Math.Cos(theta);                        //
            double st = Math.Sin(theta);                        //
            double cp = Math.Cos(phi);                        //
            double sp = Math.Sin(phi);                        //

            Vector3d cx = px * cp + py * sp;
            Vector3d cy = (px*-1.0) * sp*ct + py * cp*ct + pz * st;
            Vector3d cz = px * sp*st - py * cp*st + pz * ct;

            //			m_worldPos = po + cz * m_position.distance;
            //			Vector3 m_worldPos = m_manager.parentCelestialBody.transform.position -m_core.chosenCamera.transform.position ;
            Vector3 m_worldPos = m_manager.parentCelestialBody.transform.position -m_manager.m_skyNode.farCamera.transform.position ;

            //			if (m_worldPos.z < m_groundHeight + 10.0) {
            //				m_worldPos.z = m_groundHeight + 10.0;
            //			}

            Matrix4x4d view = new Matrix4x4d(	cx.x, cx.y, cx.z, 0.0,
                                             cy.x, cy.y, cy.z, 0.0,
                                             cz.x, cz.y, cz.z, 0.0,
                                             0.0, 0.0, 0.0, 1.0);

            Matrix4x4d m_worldToCameraMatrix = view * Matrix4x4d.Translate(m_worldPos * -1.0f);
            if (m_core.debugSettings[0])
            m_worldToCameraMatrix.m[0,0] *= -1.0;
            else
            m_worldToCameraMatrix.m[0,0] *= 1.0;

            if (m_core.debugSettings[1])
            m_worldToCameraMatrix.m[0,1] *= -1.0;
            else
            m_worldToCameraMatrix.m[0,1] *= 1.0;

            if (m_core.debugSettings[2])
            m_worldToCameraMatrix.m[0,2] *= -1.0;
            else
            m_worldToCameraMatrix.m[0,2] *= 1.0;

            if (m_core.debugSettings[3])
            m_worldToCameraMatrix.m[0,3] *= -1.0;
            else
            m_worldToCameraMatrix.m[0,3] *= 1.0;

            return m_worldToCameraMatrix;

            //			m_cameraToWorldMatrix = m_worldToCameraMatrix.Inverse();

            //			camera.worldToCameraMatrix = m_worldToCameraMatrix.ToMatrix4x4();
            //			camera.transform.position = m_worldPos.ToVector3();
        }