public override Color Calculate(Vector point, Vector normal)
		{
            // Use dotproduct for diffuse lighting. Add point functionality as this now is a directional light.
            // Ambient light
            var ambient = ColorAmbient.ToVector() * Strength;

            // Diffuse light
            var lightDir = Direction;
            lightDir.Normalize();
            normal.Normalize();
            var dfDot = lightDir.Dot(normal);
            MathHelper.Saturate(ref dfDot);
            var diffuse = ColorDiffuse.ToVector() * dfDot * Strength;

            // Specular highlight
            var Reflection = 2 * dfDot * normal - lightDir;
            Reflection.Normalize();
            var view = Camera.Position - point;
            view.Normalize();
            var spDot = Reflection.Dot(view);
            MathHelper.Saturate(ref spDot);
            var specular = ColorSpecular.ToVector() * spDot * Strength;

            // Compute self shadowing
            var shadow = 4.0f * lightDir.Dot(normal);
            MathHelper.Saturate(ref shadow);


            // Final result
            var colorVector = ambient + shadow * (diffuse + specular);
            //var colorVector = ambient + diffuse;

			return colorVector.ToColorWithClamp();
		}
		private static void RenderUnscaled(IBuffers buffer, int positionOffset, Image image, Vector translatedPosition, int bufferSize, UInt32 bufferZ)
		{
			var rOffset = buffer.FrameBuffer.RedPosition;
			var gOffset = buffer.FrameBuffer.GreenPosition;
			var bOffset = buffer.FrameBuffer.BluePosition;
			var aOffset = buffer.FrameBuffer.AlphaPosition;
			var imageContext = image.ImageContext as ImageContext;
			var spriteOffset = 0;

			for (var y = 0; y < image.Height; y++)
			{
				var offset = y * buffer.FrameBuffer.Stride;
				var depthBufferOffset = (buffer.Width * ((int)translatedPosition.Y + y)) + (int)translatedPosition.X;
				for (var x = 0; x < image.Width; x++)
				{
					var actualOffset = offset + positionOffset;

					if (actualOffset >= 0 && actualOffset < bufferSize &&
						bufferZ < buffer.DepthBuffer[depthBufferOffset])
					{
						buffer.FrameBuffer.Pixels[actualOffset] = imageContext.Pixels[spriteOffset];
						buffer.DepthBuffer[depthBufferOffset] = bufferZ;
					}
					offset ++;
					spriteOffset ++;
					depthBufferOffset++;
				}
			}
		}
Example #3
0
        public void Render(Viewport viewport, Sprite sprite, Matrix view, Matrix projection, Matrix world, float xScale, float yScale, float rotation)
        {
            var image = sprite.CurrentFrame;

            var position = new Vector(0, 0, 0);
            var transformedPosition = Vector.Transform(position, world, view);
            var translatedPosition = Vector.Translate(transformedPosition, projection, viewport.Width, viewport.Height);

            var z = ((transformedPosition.Z / viewport.View.DepthDivisor) + viewport.View.DepthZero);
            var depthBufferAdjustedZ = z;

            var bufferSize = BufferContainer.Stride * BufferContainer.Height;
            var bufferZ = (UInt32)((1.0f - depthBufferAdjustedZ) * (float)UInt32.MaxValue);
            if (depthBufferAdjustedZ < 0f || depthBufferAdjustedZ >= 1f)
            {
                return;
            }

            var xOriginOffset = (int)-((sprite.CurrentFrame.Width / 2f) * xScale);
            var yOriginOffset = (int)-((sprite.CurrentFrame.Height / 2f) * yScale);

            var actualX = ((int) translatedPosition.X) + xOriginOffset;
            var actualY = ((int) translatedPosition.Y) + yOriginOffset;

            var positionOffset = actualX + (actualY * BufferContainer.Stride);

            if (xScale != 1f || yScale != 1f)
            {
                RenderScaled(viewport, positionOffset, actualX, actualY, sprite.CurrentFrame, translatedPosition, bufferSize, bufferZ, xScale, yScale);
            }
            else
            {
                RenderUnscaled(viewport, positionOffset, actualX, actualY, sprite.CurrentFrame, translatedPosition, bufferSize, bufferZ);
            }
        }
Example #4
0
		public void Transform(Matrix world, Matrix view)
		{
			TransformedVector = Vector.Transform(Vector, world);
			TransformedVector = Vector.Transform(TransformedVector, view);
			TransformedNormal = Vector.TransformNormal(Normal, world);
			TransformedNormal = Vector.TransformNormal(TransformedNormal, view);
		}
		public void Render(IViewport viewport, Sprite sprite, Matrix view, Matrix projection, Matrix world, float xScale, float yScale, float rotation)
		{
			var buffer = BufferManager.Instance.Current;

			var image = sprite.CurrentFrame;

			
			var position = new Vector(0, 0, 0);
			var transformedPosition = Vector.Transform(position, world, view);
			var translatedPosition = Vector.Translate(transformedPosition, projection, viewport.Width, viewport.Height);
			var depthBufferAdjustedZ = -transformedPosition.Z / viewport.Camera.DepthDivisor;
			var positionOffset = (((int)translatedPosition.X)) + (((int)translatedPosition.Y) * buffer.FrameBuffer.Stride);

			var bufferSize = buffer.FrameBuffer.Stride*buffer.Height;
			var bufferZ = (UInt32)(depthBufferAdjustedZ * (float)UInt32.MaxValue);
			if( depthBufferAdjustedZ < 0f || depthBufferAdjustedZ >= 1f)
			{
				return;
			}
			
			if( xScale != 1f || yScale != 1f )
			{
				RenderScaled(buffer, positionOffset, sprite.CurrentFrame, translatedPosition, bufferSize, bufferZ, xScale, yScale);
				
			} else
			{
				RenderUnscaled(buffer,positionOffset,sprite.CurrentFrame,translatedPosition,bufferSize,bufferZ);
			}
		}
Example #6
0
 public void ImplicitlySettingAVectorAsCoordinateShouldReturnSameValuesAsInVector()
 {
     var vector = new Vector(5f, 6f, 7f);
     Coordinate coordinate = vector;
     Assert.That(coordinate.X, Is.EqualTo(vector.X));
     Assert.That(coordinate.Y, Is.EqualTo(vector.Y));
     Assert.That(coordinate.Z, Is.EqualTo(vector.Z));
 }
Example #7
0
        public Vector(Vector v1)
			: this()
        {
            X = v1.X;
            Y = v1.Y;
            Z = v1.Z;
            W = v1.W;
        }
        public DirectionalLight()
		{
			Strength = 1f;
            Specular = true;
            Diffuse = true;
            Ambient = true;
            Direction = new Vector(0, 0, 1, 0);
		}
Example #9
0
		public void Transform(Matrix world, Matrix view)
		{
			TransformedNormal = Vector.TransformNormal(Normal, world);
			TransformedNormal = Vector.TransformNormal(TransformedNormal, view);
			TransformedPosition = Vector.Transform(Position, world, view);

			TransformedDebugNormal = TransformedPosition +(TransformedNormal); //*DebugNormalLength);
		}
Example #10
0
 public void TransformingWithOnlyTranslationShouldPositionSphereCorrectly()
 {
     var boundingSphere = new BoundingSphere(Vector.Zero, 1);
     var position = new Vector(10, 5, 3);
     var matrix = Matrix.CreateTranslation(position);
     var transformedBoundingSphere = boundingSphere.Transform(matrix);
     Assert.That(transformedBoundingSphere.Center, Is.EqualTo(position));
 }
Example #11
0
 public Vertex(float x, float y, float z)
     : this()
 {
     Vector = new Vector(x, y, z);
     TransformedVector = new Math.Vector(x, y, z);
     TranslatedVector = new Math.Vector(x, y, z);
     Normal = Vector.Zero;
     TranslatedScreenCoordinates = Vector.Zero;
 }
Example #12
0
 public void AddingACoordinateToAVectorShouldReturnAVectorWithCorrectResult()
 {
     var v1 = new Vector(2f, 4f, 6f);
     var c2 = new Coordinate { X = 1f, Y = 2f, Z = 3f };
     var vector = v1 + c2;
     Assert.That(vector.X, Is.EqualTo(3f));
     Assert.That(vector.Y, Is.EqualTo(6f));
     Assert.That(vector.Z, Is.EqualTo(9f));
 }
Example #13
0
File: Node.cs Project: Conn/Balder
		protected Node()
		{
			World = Matrix.Identity;

			PositionMatrix = Matrix.Identity;
			ScaleMatrix = Matrix.Identity;
			Scale = new Vector(1f,1f,1f);
			Position = Vector.Zero;
		}
Example #14
0
 public void AddingAVectorToACoordinateShouldReturnAVectorWithCorrectResult()
 {
     var c1 = new Coordinate { X = 2f, Y = 4f, Z = 6f };
     var v2 = new Vector(1f, 2f, 3f);
     var vector = c1 + v2;
     Assert.That(vector.X, Is.EqualTo(3f));
     Assert.That(vector.Y, Is.EqualTo(6f));
     Assert.That(vector.Z, Is.EqualTo(9f));
 }
Example #15
0
 public void Transform(Matrix world, Matrix view)
 {
     //var matrix = world*view;
     var matrix = view;
     TransformedVector = Vector.Transform(Vector, matrix);
     //TransformedVector = Vector.Transform(TransformedVector, view);
     TransformedNormal = Vector.TransformNormal(Normal, matrix);
     //TransformedNormal = Vector.TransformNormal(TransformedNormal, view);
 }
Example #16
0
 public static Vector Transform(Vector position, Matrix matrix)
 {
     Vector vector = Vector.Zero;
     float num3 = (((position.X * matrix[0, 0]) + (position.Y * matrix[1, 0])) + (position.Z * matrix[2, 0])) + matrix[3, 0];
     float num2 = (((position.X * matrix[0, 1]) + (position.Y * matrix[1, 1])) + (position.Z * matrix[2, 1])) + matrix[3, 1];
     float num = (((position.X * matrix[0, 2]) + (position.Y * matrix[1, 2])) + (position.Z * matrix[2, 2])) + matrix[3, 2];
     vector.X = num3;
     vector.Y = num2;
     vector.Z = num;
     return vector;
 }
Example #17
0
 public void TransormingWith90DegreesRotationAroundYAndTranslationShouldPositionSphereCorrectly()
 {
     var boundingSphere = new BoundingSphere(Vector.Zero, 1);
     var position = new Vector(10, 5, 3);
     var translationMatrix = Matrix.CreateTranslation(position);
     var rotationMatrix = Matrix.CreateRotationY(90f);
     var matrix = translationMatrix * rotationMatrix;
     var transformedBoundingSphere = boundingSphere.Transform(matrix);
     var expectedPosition = position*rotationMatrix;
     Assert.That(transformedBoundingSphere.Center, Is.EqualTo(expectedPosition));
 }
Example #18
0
        public Color Calculate(Viewport viewport, Vector vector, Vector normal)
        {
            var color = viewport.Scene.AmbientColor;

            foreach( ILight light in viewport.Scene.Lights )
            {
                var lightColor = light.Calculate(viewport, vector, normal);
                color = color.Additive(lightColor);
            }

            return color;
        }
Example #19
0
        public void UnprojectingCenterOfViewportWithIdentityViewShouldGenerateAVectorAtCenter()
        {
            var viewport = new Viewport { Width = 640, Height = 480 };

            var aspect = (float) viewport.Height/(float) viewport.Width;
            var projection = Matrix.CreatePerspectiveFieldOfView(40f, aspect, 1, 4000f);
            var view = Matrix.Identity;
            var world = Matrix.Identity;
            var position = new Vector((float)viewport.Width/2, (float)viewport.Height/2,0);
            var result = viewport.Unproject(position, projection, view, world);
            Assert.That(result,Is.EqualTo(new Vector(0,0,-1)));
        }
Example #20
0
		public void GettingDistanceFromPlaneShouldReturnCorrectDistance()
		{
			var plane = new Plane();
			var vector1 = new Vector(-100, -100, 100);
			var vector2 = new Vector(100, -100, 100);
			var vector3 = new Vector(0, -100, 0);
			plane.SetVectors(vector1,vector2,vector3);

			var vectorToTest = new Vector(0, -200, 0);

			var length = plane.GetDistanceFromVector(vectorToTest);
			Assert.That(length,Is.EqualTo(-100f));
		}
Example #21
0
 public FrustumIntersection IsPointInFrustum(Vector vector)
 {
     for( var planeIndex=0; planeIndex<_planes.Length; planeIndex++ )
     {
         var plane = _planes[planeIndex];
         var distance = plane.GetDistanceFromVector(vector);
         if ( distance < 0)
         {
             return FrustumIntersection.Outside;
         }
     }
     return FrustumIntersection.Inside;
 }
		private static void RenderScaled(IBuffers buffer, int positionOffset, Image image, Vector translatedPosition, int bufferSize, UInt32 bufferZ, float xScale, float yScale)
		{
			var rOffset = buffer.FrameBuffer.RedPosition;
			var gOffset = buffer.FrameBuffer.GreenPosition;
			var bOffset = buffer.FrameBuffer.BluePosition;
			var aOffset = buffer.FrameBuffer.AlphaPosition;
			var imageContext = image.ImageContext as ImageContext;

			var actualWidth = (int) (((float) image.Width)*xScale);
			var actualHeight = (int) (((float) image.Height)*yScale);

			if( actualWidth <= 0 || actualHeight <=0 )
			{
				return;
			}

			var spriteOffset = 0;

			XScalingInterpolator.SetPoint(0,0f,image.Width);
			XScalingInterpolator.Interpolate(actualWidth);

			YScalingInterpolator.SetPoint(0,0f,image.Height);
			YScalingInterpolator.Interpolate(actualHeight);
			

			for (var y = 0; y < actualHeight; y++)
			{
				var offset = y*buffer.FrameBuffer.Stride;
				var depthBufferOffset = (buffer.Width*((int) translatedPosition.Y + y)) + (int) translatedPosition.X;

				var spriteY = (int)YScalingInterpolator.Points[0].InterpolatedValues[y];

				for (var x = 0; x < actualWidth; x++)
				{
					var actualOffset = offset + positionOffset;
					
					var spriteX = (int)XScalingInterpolator.Points[0].InterpolatedValues[x];
					spriteOffset = (int)((spriteY*image.Width) + spriteX);

					if (actualOffset >= 0 && actualOffset < bufferSize &&
					    bufferZ < buffer.DepthBuffer[depthBufferOffset])
					{
						buffer.FrameBuffer.Pixels[actualOffset] = imageContext.Pixels[spriteOffset];
						buffer.DepthBuffer[depthBufferOffset] = bufferZ;
					}
					offset ++;
					
					depthBufferOffset++;
				}
			}
		}
Example #23
0
		public static Vector Unproject(this IViewport viewport, Vector source, Matrix projection, Matrix view, Matrix world)
		{
			var matrix = Matrix.Invert((world * view) * projection);
			source.X = (((source.X - viewport.XPosition) / ((float)viewport.Width)) * 2f) - 1f;
			source.Y = -((((source.Y - viewport.YPosition) / ((float)viewport.Height)) * 2f) - 1f);
			source.Z = (source.Z - MinDepth) / (MaxDepth - MinDepth);
			var vector = Vector.Transform(source, matrix);
			var a = (((source.X * matrix[0,3]) + (source.Y * matrix[1,3])) + (source.Z * matrix[2,3])) + matrix[3,3];
			if (!WithinEpsilon(a, 1f))
			{
				vector = (Vector)(vector / a);
			}
			return vector;
		}
Example #24
0
		public Color CalculateColorForVector(IViewport viewport, Vector vector, Vector normal)
		{
			var color = AmbientColor.ToVector();

			foreach( var node in _environmentalNodes )
			{
				if( node is Light )
				{
					var light = node as Light;
					var currentLightResult = light.Calculate(viewport, vector, normal);
					var currentLightResultAsVector = currentLightResult.ToVector();
					color += currentLightResultAsVector;
				}
			}
			return color.ToColorWithClamp();
		}
Example #25
0
        public Camera(Viewport viewport)
        {
            Position = new Vector(0f, -30f, 50f);
            Target = new Vector(0f, 0f, 0f);
            Up = new Vector(0f, -1f, 0f);
            Near = DefaultNear;
            Far = DefaultFar;
            Roll = 0;
            FieldOfView = DefaultFieldOfView;
            ProjectionMatrix = null;
            UpdateDepthDivisor();

            Frustum = new Frustum();

            Viewport = viewport;
        }
Example #26
0
        public void UnprojectingCenterOfViewportWithViewRotated90DegreesAroundYAxisShouldGenerateAVectorRotated90DegreesInOpositeDirection()
        {
            var viewport = new Viewport { Width = 640, Height = 480 };
            var aspect = (float)viewport.Height / (float)viewport.Width;
            var projection = Matrix.CreatePerspectiveFieldOfView(40f, aspect, 1, 4000f);
            var view = Matrix.CreateRotationY(90);
            var world = Matrix.Identity;
            var position = new Vector((float)viewport.Width / 2, (float)viewport.Height / 2, 0);
            var result = viewport.Unproject(position, projection, view, world);

            var negativeView = Matrix.CreateRotationY(-90);
            var expected = new Vector(0, 0, -1);
            var rotatedExpected = expected*negativeView;

            Assert.That(result, Is.EqualTo(rotatedExpected));
        }
Example #27
0
        private void CalculateCameraPosition()
        {
            var rotationX = Matrix.CreateRotationX((float)_xSlider.Value);
            var rotationY = Matrix.CreateRotationY((float)_ySlider.Value);

            var combined = rotationX*rotationY;
            var forward = Vector.Forward;
            var zoomedForward = forward*(float) _zoomSlider.Value;
            var position = zoomedForward*combined;

            var target = new Vector((float)_game.Camera.Target.X,
                                    (float)_game.Camera.Target.Y,
                                    (float)_game.Camera.Target.Z);
            var actualPosition = target - position;

            _game.Camera.Position.X = actualPosition.X;
            _game.Camera.Position.Y = actualPosition.Y;
            _game.Camera.Position.Z = actualPosition.Z;
        }
Example #28
0
		public static void CalculateVertexNormals(IGeometryContext context)
		{
			var vertexCount = new Dictionary<int, int>();
			var vertexNormal = new Dictionary<int, Vector>();

			var vertices = context.GetVertices();
			var faces = context.GetFaces();

			Func<int, Vector, int> addNormal =
				delegate(int vertex, Vector normal)
					{
						if (!vertexNormal.ContainsKey(vertex))
						{
							vertexNormal[vertex] = normal;
							vertexCount[vertex] = 1;
						}
						else
						{
							vertexNormal[vertex] += normal;
							vertexCount[vertex]++;
						}
						return 0;
					};

			foreach (var face in faces)
			{
				addNormal(face.A, face.Normal);
				addNormal(face.B, face.Normal);
				addNormal(face.C, face.Normal);
			}

			foreach (var vertex in vertexNormal.Keys)
			{
				var addedNormals = vertexNormal[vertex];
				var count = vertexCount[vertex];

				var normal = new Vector(addedNormals.X / count,
				                        addedNormals.Y / count,
				                        addedNormals.Z / count);
				vertices[vertex].Normal = normal;
			}
		}
Example #29
0
        public override Color Calculate(Viewport viewport, Vector point, Vector normal)
        {
            var actualAmbient = Ambient;
            var actualDiffuse = Diffuse;
            var actualSpecular = Specular;

            // Use dotproduct for diffuse lighting. Add point functionality as this now is a directional light.
            // Ambient light
            var ambient = actualAmbient  * Strength;

            // Diffuse light
            var lightDir = Position-point;
            lightDir.Normalize();
            normal.Normalize();
            var dfDot = lightDir.Dot(normal);
            dfDot = MathHelper.Saturate(dfDot);
            var diffuse = actualDiffuse * dfDot * Strength;

            // Specular highlight
            var reflection = 2f * dfDot * normal - lightDir;
            reflection.Normalize();
            var view = viewport.View.Position - point;
            view.Normalize();
            var spDot = reflection.Dot(view);
            spDot = MathHelper.Saturate(spDot);
            var specular = actualSpecular * spDot * Strength;

            // Compute self shadowing
            var shadow = 4.0f * lightDir.Dot(normal);
            shadow = MathHelper.Saturate(shadow);

            // Compute range for the light
            var attenuation = ((lightDir / Range).Dot(lightDir / Range));
            attenuation = MathHelper.Saturate(attenuation);
            attenuation = 1f - attenuation;

            // Final result
            var colorVector = ambient + shadow * (diffuse + specular) * attenuation;
            //var colorVector = ambient + diffuse;

            return colorVector;
        }
Example #30
0
		public override void Render(IViewport viewport, Matrix view, Matrix projection)
		{
			/* From DirectX sample
				w = width passed to D3DXMatrixPerspectiveLH
				h = height passed to D3DXMatrixPerspectiveLH
				n = z near passed to D3DXMatrixPerspectiveLH
				f = z far passed to D3DXMatrixPerspectiveLH
				d = distance of sprite from camera along Z
				qw = width of sprite quad
				qh = height of sprite quad
				vw = viewport height
				vh = viewport width
				scale = n / d
				(i.e. near/distance, such that at d = n, scale = 1.0)
				renderedWidth = vw * qw * scale / w 
				renderedHeight = vh * qh * scale / h
			 */

			var position = new Vector(0, 0, 0);
			var actualPosition = new Vector(World.data[12], World.data[13], World.data[14]);
			var transformedPosition = Vector.Transform(position, World, view);
			var translatedPosition = Vector.Translate(transformedPosition, projection, viewport.Width, viewport.Height);

			var distanceVector = viewport.Camera.Position - actualPosition;
			var distance = distanceVector.Length;
			var n = 100.0f;
			distance = MathHelper.Abs(distance);

			var scale = 0.0f + ((2 * n) / distance);
			if (scale <= 0)
			{
				scale = 0;
			}

			var xscale = scale;
			var yscale = scale;

			_spriteContext.Render(viewport,this,view,projection,World,xscale,yscale,0f);
		}