public void LookAt(Vector3 lookDir, Vector3 up) { lookDir.Normalize(); Matrix matView = Matrix.LookAtLH(Vector3.Zero, lookDir, up); Quaternion qtnView = Quaternion.RotationMatrix(matView); m_Orientation = Quaternion.Invert(qtnView); }
public void GlobalSetUp() { randomTriangles = new Vector3[TRIANGLE_COUNT * 3]; for (int i = 0; i < TRIANGLE_COUNT * 3; i++) { randomTriangles[i] = RNG.RandomVector3(); } origin = RNG.RandomVector3(); direction = RNG.RandomVector3(); direction.Normalize(); testRay = new Ray(origin, direction); randomRays = new Ray[RAY_COUNT]; for (int i = 0; i < RAY_COUNT; i++) { Vector3 thisOrigin = RNG.RandomVector3(); Vector3 thisDirection = RNG.RandomVector3(); thisDirection.Normalize(); randomRays[i] = new Ray(thisOrigin, thisDirection); } heightmap = new float[256 * 256]; for (int y = 0; y < 256; y++) { for (int x = 0; x < 256; x++) { heightmap[y * 256 + x] = (float)Math.Max(RNG.NextGaussian(25.0, 10.0), 0); } } }
public static Matrix4 Rotate (float angle, Vector3 r) { float a = RadiansOverPi (angle); float c = (float)Math.Cos (a); float s = (float)Math.Sin (a); float k = 1.0f - c; r.Normalize (); Vector3 u = r; Vector3 v = s * u; Vector3 w = k * u; Vector4 P = Vector4.Zero; Vector4 Q = Vector4.Zero; Vector4 R = Vector4.Zero; Vector4 S = Vector4.Zero; P.X = w.X * u.X + c; P.Y = w.X * u.Y + v.Z; P.Z = w.X * u.Z - v.Y; Q.X = w.X * u.Y - v.Z; Q.Y = w.Y * u.Y + c; Q.Z = w.Y * u.Z + v.X; R.X = w.X * u.Z + v.Y; R.Y = w.Y * u.Z - v.X; R.Z = w.Z * u.Z + c; S.W = 1.0f; return MakeResultMatrix (P, Q, R, S); }
/// <summary> /// 拡大縮小ベクトルと回転行列と位置ベクトルに分割します。 /// </summary> /// <param name="m">元の行列(戻り値は回転行列)</param> /// <param name="scaling">拡大縮小ベクトル</param> /// <returns>位置ベクトル</returns> public static Vector3 DecomposeMatrix(ref Matrix m, out Vector3 scaling) { Vector3 vx = new Vector3(m.M11, m.M12, m.M13); Vector3 vy = new Vector3(m.M21, m.M22, m.M23); Vector3 vz = new Vector3(m.M31, m.M32, m.M33); Vector3 vt = new Vector3(m.M41, m.M42, m.M43); float scax = vx.Length(); float scay = vy.Length(); float scaz = vz.Length(); scaling = new Vector3(scax, scay, scaz); vx.Normalize(); vy.Normalize(); vz.Normalize(); m.M11 = vx.X; m.M12 = vx.Y; m.M13 = vx.Z; m.M21 = vy.X; m.M22 = vy.Y; m.M23 = vy.Z; m.M31 = vz.X; m.M32 = vz.Y; m.M33 = vz.Z; m.M41 = 0; m.M42 = 0; m.M43 = 0; return vt; }
public PistonConstraint( int indexA, int indexB, SimulationObject[] simulationObject, Vector3 startAnchorPosition, Vector3 pistonAxis, double restoreCoefficient, double springCoefficient) { IndexA = indexA; IndexB = indexB; KeyIndex = GetHashCode(); RestoreCoefficient = restoreCoefficient; SpringCoefficient = springCoefficient; StartAnchorPoint = startAnchorPosition; PistonAxis = -1.0 * pistonAxis.Normalize (); SimulationObject objectA = simulationObject[IndexA]; SimulationObject objectB = simulationObject[IndexB]; Vector3 relativePos = objectA.RotationMatrix * (startAnchorPosition - objectA.StartPosition); AnchorPoint = relativePos + objectA.Position; StartErrorAxis1 = objectA.RotationMatrix.Transpose() * (AnchorPoint - objectA.Position); StartErrorAxis2 = objectB.RotationMatrix.Transpose() * (AnchorPoint - objectB.Position); RelativeOrientation = objectB.RotationStatus.Inverse() * objectA.RotationStatus; }
public void rotate(Vector3 axis, float angle) { axis.Normalize(); axis = axis * (float)Math.Sin(angle / 2.0f); float scalar = (float)Math.Cos(angle / 2.0f); rotate(new Quaternion(axis, scalar)); }
public override float GetDistanceToCenter( Vector3 particlePosition, Vector3 particleVelocity, out Vector3 alongAxis, out Vector3 aroundAxis, out Vector3 awayAxis) { // Along - following the main axis alongAxis = mainAxis; // Toward - tawards the main axis awayAxis = particlePosition - fieldPosition; awayAxis.Y = 0; // In case of cylinder the away vector should be flat (away from the axis rather than just a point) awayAxis.Normalize(); // Around - around the main axis, following the right hand rule aroundAxis = Vector3.Cross(alongAxis, awayAxis); particlePosition -= fieldPosition; inverseRotation.Rotate(ref particlePosition); particlePosition /= fieldSize; // Start of code for Cylinder if (Math.Abs(particlePosition.Y) >= halfHeight) return 1; particlePosition.Y = 0; particlePosition.X /= radius; particlePosition.Z /= radius; var maxDist = particlePosition.Length(); // End of code for Cylinder return maxDist; }
// レンダリング public void Render() { viewport.MakeCurrent(); GL.Enable(EnableCap.DepthTest); GL.Enable(EnableCap.CullFace); GL.FrontFace(FrontFaceDirection.Cw); GL.CullFace(CullFaceMode.Back); GL.Viewport(0, 0, viewport.Width, viewport.Height); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); GL.UseProgram(program); Vector3 eyePos = new Vector3(5.0f, 5.0f, 5.0f); Vector3 lookAt = new Vector3(0.0f, 0.0f, 0.0f); Vector3 eyeUp = new Vector3(0.0f, 1.0f, 0.0f); Matrix4 viewMatrix = Matrix4.LookAt(eyePos, lookAt, eyeUp); Matrix4 projectionMatrix = Matrix4.CreatePerspectiveFieldOfView((float)System.Math.PI / 4.0f, (float)viewport.Width / (float)viewport.Height, 0.1f, 10.0f); Matrix4 viewProjectionMatrix = viewMatrix * projectionMatrix; GL.UniformMatrix4(GL.GetUniformLocation(program, "viewProjection"), false, ref viewProjectionMatrix); Matrix4 worldMatrix = Matrix4.Identity; GL.UniformMatrix4(GL.GetUniformLocation(program, "world"), false, ref worldMatrix); Vector3 lightDir = new Vector3((float)Math.Cos((float)lightAngle), -1.0f, (float)Math.Sin((float)lightAngle)); lightDir.Normalize(); GL.Uniform3(GL.GetUniformLocation(program, "lightDir"), lightDir); lightAngle += 0.001f; cube.Render(); viewport.SwapBuffers(); }
/// <summary> /// Set of lines in 3D space. /// </summary> /// <param name="origin"></param> /// <param name="xAxis"></param> /// <param name="yAxis"></param> /// <param name="scale">Scaling the field extent.</param> /// <param name="field"></param> public LineBall(Plane plane, LineSet lines, RenderEffect effect = RenderEffect.DEFAULT, Colormap colormap = Colormap.Parula, bool flatten = false) { _thickness = lines.Thickness * plane.PointSize; _color = lines.Color; this._vertexSizeBytes = Marshal.SizeOf(typeof(Vector4)); this._numVertices = lines.NumPoints * 2 - lines.Lines.Length * 2; // Linelist means, all points are there twice, minus the endpoints. if (_numVertices == 0) return; this._topology = PrimitiveTopology.LineList; // Setting up the vertex buffer. if (!flatten) GenerateGeometry(plane, lines); else GenerateGeometryFlatXY(plane, lines); //this._technique = _lineEffect.GetTechniqueByName("Render"); UsedMap = colormap; _planeNormal = plane.ZAxis; _planeNormal.Normalize(); _effect = _lineEffect; SetRenderEffect(effect); this._vertexLayout = new InputLayout(_device, _technique.GetPassByIndex(0).Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("SCALAR", 0, Format.R32_Float, 12, 0) }); }
public void ComputeMatricies ( Matrix viewMatrix, Vector3 lightDir, int cascadeSize, float splitSize, float splitOffset, float splitFactor, float projDepth ) { var smSize = cascadeSize; var camMatrix = Matrix.Invert( viewMatrix ); var viewPos = camMatrix.TranslationVector; lightDir.Normalize(); for ( int i = 0; i<4; i++ ) { float offset = splitOffset * (float)Math.Pow( splitFactor, i ); float radius = splitSize * (float)Math.Pow( splitFactor, i ); Vector3 viewDir = camMatrix.Forward.Normalized(); Vector3 origin = viewPos + viewDir * offset; Matrix lightRot = Matrix.LookAtRH( Vector3.Zero, Vector3.Zero + lightDir, Vector3.UnitY ); Matrix lightRotI = Matrix.Invert( lightRot ); Vector3 lsOrigin = Vector3.TransformCoordinate( origin, lightRot ); float snapValue = 4.0f * radius / smSize; lsOrigin.X = (float)Math.Round(lsOrigin.X / snapValue) * snapValue; lsOrigin.Y = (float)Math.Round(lsOrigin.Y / snapValue) * snapValue; lsOrigin.Z = (float)Math.Round(lsOrigin.Z / snapValue) * snapValue; origin = Vector3.TransformCoordinate( lsOrigin, lightRotI );//*/ shadowViews[i] = Matrix.LookAtRH( origin, origin + lightDir, Vector3.UnitY ); shadowProjections[i] = Matrix.OrthoRH( radius*2, radius*2, -projDepth/2, projDepth/2); } }
/// <summary> Checks if this vector has 'good' values, i.e. components are not very little values. </summary> /// <param name="vector"> Vector to check. Must be a normalized vector. </param> public static void checkIntegrity(ref Vector3 vector) { float threshold = 0.000001f; bool mustRenormalize = false; if (Math.Abs(vector.X) < threshold) { vector.X = 0; mustRenormalize = true; } if (Math.Abs(vector.Y) < threshold) { vector.Y = 0; mustRenormalize = true; } if (Math.Abs(vector.Z) < threshold) { vector.Z = 0; mustRenormalize = true; } if( mustRenormalize ) vector.Normalize(); if (Math.Abs(vector.X) > 0.999999) vector.X = Math.Sign(vector.X); if (Math.Abs(vector.Y) > 0.999999) vector.Y = Math.Sign(vector.Y); if (Math.Abs(vector.Z) > 0.999999) vector.Z = Math.Sign(vector.Z); }
private static float AngleBetween(Vector3 v1, Vector3 v2) { v1.Normalize(); v2.Normalize(); float dot = Vector3.Dot(v1, v2); return (float)Math.Acos(dot); }
public Quad(int startX,int endX, int startZ, int endZ, Base.Content.Terrain.Terrain terrain, RenderManager renderer) { _bounds = new QuadBounds { MinX = startX / terrain.PointsPerMeter, MaxX = endX / terrain.PointsPerMeter, MinZ = startZ / terrain.PointsPerMeter, MaxZ = endZ / terrain.PointsPerMeter, MinY = terrain.Height[0], MaxY = terrain.Height[0] }; HorizontalCenter = new Vector2(Bounds.MinX + (Bounds.MaxX - Bounds.MinX) / 2, Bounds.MinZ + (Bounds.MaxZ - Bounds.MinZ) / 2); int verticesX = endX - startX + 1; int verticesZ = endZ - startZ + 1; var dataStream = new DataStream(32 * verticesX * verticesZ, true, true); for (int i = 0; i < verticesX; i++) { for (int j = 0; j < verticesZ; j++) { //Position int xindex = Math.Min(i + startX, terrain.PointsX - 1);//Clamp to arraybounds if neccessary int zindex = Math.Min(j + startZ, terrain.PointsZ - 1);//(Quadsize needs to be consistent for sharing IndexBuffers) float x = xindex / terrain.PointsPerMeter; float z = zindex / terrain.PointsPerMeter; float y = terrain.Height[xindex * terrain.PointsZ + zindex]; dataStream.Write(new Vector3(x, y, z)); //Normal float deltax = (terrain.Height[(xindex < terrain.PointsX - 1 ? xindex + 1 : xindex) * terrain.PointsZ + zindex] - terrain.Height[(xindex != 0 ? xindex - 1 : xindex) * terrain.PointsZ + zindex]); float deltaz = (terrain.Height[xindex * terrain.PointsZ + (zindex < terrain.PointsZ - 1 ? zindex + 1 : zindex)] - terrain.Height[xindex * terrain.PointsZ + (zindex != 0 ? zindex - 1 : zindex)]); if (xindex == 0 || xindex == terrain.PointsX - 1) deltax *= 2; if (zindex == 0 || zindex == terrain.PointsZ - 1) deltaz *= 2; var normal = new Vector3(-deltax, 2 / terrain.PointsPerMeter, deltaz); normal.Normalize(); dataStream.Write(normal); //TextureCoordinates dataStream.Write(new Vector2(x / terrain.PointsX, z / terrain.PointsZ)); //Boundingbox-Params if (y < _bounds.MinY) _bounds.MinY = y; if (y > _bounds.MaxY) _bounds.MaxY = y; } } dataStream.Position = 0; VBuffer = new Buffer(renderer.D3DDevice, dataStream, 32 * verticesX * verticesZ, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); VertexBuffer = new VertexBufferBinding(VBuffer, 32, 0); dataStream.Dispose(); }
/// <summary> /// Creates the instance of the camera at the given location. /// </summary> /// <param name="position">Position of the camera.</param> /// <param name="target">The target towards which the camera is pointing.</param> public Camera(Game game, Vector3 position, Vector3 target) : this(game) { m_position = position; m_direction = target - m_position; m_direction.Normalize(); View = CreateLookAt(); }
/// <summary> /// Modifies the orientation of the camera to get the camera to look in a particular direction. /// </summary> /// <param name="direction">The direction to have the camera look.</param> public void SetDirection(Vector3 direction) { if (direction == Vector3.Zero) return; Vector3 zvec = -direction.Normalize(); Vector3 xvec = Vector3.Up.Cross(zvec).Normalize(); Vector3 yvec = zvec.Cross(xvec).Normalize(); Orientation = Quaternion.FromAxis(xvec, yvec, zvec); }
public void LookTo(Vector3 direction) { if (direction == Vector3.Zero) return; direction.Normalize(); var angle = (float)Math.Atan2(-direction.X, direction.Z); Object.Transform = Matrix.RotationY(angle) * Matrix.Translation(Object.Transform.TranslationVector); }
/// <summary> /// Generates a random tangent and binormal for a given normal, /// usefull for creating plane vertices or orienting objects (lookat) where the rotation along the normal doesn't matter /// </summary> /// <param name="normal"></param> /// <param name="tangent"></param> /// <param name="binormal"></param> public static void GenerateTangentBinormal(Vector3 normal, out Vector3 tangent, out Vector3 binormal) { tangent = Math.Abs(normal.Y) < 0.01f ? new Vector3(normal.Z, normal.Y, -normal.X) : new Vector3(-normal.Y, normal.X, normal.Z); tangent.Normalize(); binormal = Vector3.Cross(normal, tangent); tangent = Vector3.Cross(binormal, normal); }
public Plane(Vector3 v1, Vector3 v2, Vector3 v3) { vec1 = v1; vec2 = v2; vec3 = v3; Normal = Vector3.Cross((v2 - v1), (v3 - v1)); Normal.Normalize(); D = (float)-Vector3.Dot(Normal, vec1); }
public Particle AddParticle(Vector3 Location, float Speed) { //create a random direction first. Vector3 RandomDirection = new Vector3((float) (PrehenderGame.rgen.NextDouble() - 0.5), (float) (PrehenderGame.rgen.NextDouble() - 0.5), (float) (PrehenderGame.rgen.NextDouble() - 0.5)); RandomDirection.Normalize(); return AddParticle(Location, RandomDirection * Speed); }
public Collider(Vector3 position, Vector3 direction, float forwardRange) { direction.Normalize(); this.forwardNormal = this.Forward = direction; this.Forward *= forwardRange; this.Direction2D = new Vector3(direction.X, 0, direction.Z); this.Direction2D.Normalize(); this.Position = position; this.forwardRange = forwardRange; }
/// <summary> /// Creates the instance of the camera. /// </summary> public Camera(Game game) { // Create the direction vector and normalize it since it will be used for movement m_direction = Vector3.Zero - m_position; m_direction.Normalize(); // Create default camera matrices Projection = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, game.Width / (float)game.Height, 0.01f, 1000); View = CreateLookAt(); }
void UpdateDirection() { Vector3 dir = new Vector3(0, 0.5f, -1.0f); dir.Normalize(); emitDirection = Vector3.TransformSimple(dir, parent.CurrentFacing); emitPosition = Vector3.TransformSimple(new Vector3(0, 380, -125), parent.CurrentFacing); Vector3 right = Vector3.TransformSimple(Vector3.UnitX, parent.CurrentFacing); emitNormal = Vector3.Cross(right, emitDirection); }
private static Matrix4 Matrix4_CreateBillboardRotation(Vector3 targetpos, Vector3 viewpos, Vector3 right) { Vector3 view = targetpos - viewpos; view.Normalize(); Vector3 up = Vector3.Cross(right, view); right.Normalize(); view = Vector3.Cross(up, right); up.Normalize(); return new Matrix4(right.X, right.Y, right.Z, 0.0f, up.X, up.Y, up.Z, 0.0f, view.X, view.Y, view.Z, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); }
public static Vector3 RandomXY() { Random random = new Random(Environment.TickCount); Vector3 vector3 = new Vector3(); vector3.X = (float)(random.NextDouble() - 0.5); vector3.Y = (float)(random.NextDouble() - 0.5); vector3.Z = 0.0f; vector3.Normalize(); return vector3; }
public static Vector3 vectorize(Point3 p1, Point3 p2) { Vector3 v = new Vector3(); v.X = p2.x - p1.x; v.Y = p2.y - p1.y; v.Z = p2.z - p1.z; v.Normalize(); return v; }
public PerspectiveCamera() { location = new Vector3(100, 100, 0); lookAt = new Vector3(0, 0, 0); eyeDirection = new Vector3(-1, -1, 0); eyeDirection.Normalize(); up = new Vector3(-1, 1, 0); up.Normalize(); right = new Vector3(0, 0, -1); Name = "Perspective Camera"; }
/// <summary> /// Shoot a projectile. /// </summary> public void fire(Vector2 dir) { Vector3 direction = new Vector3(dir.X, dir.Y, 0); direction.Normalize(); game.Add(new Projectile(game, game.assets.GetModel("shot", CreateEnemyProjectileModel), pos, direction * 10, this )); }
public Matrix4 GetViewMatrix() { Vector3 lookat = new Vector3(); lookat.X = (float)(Math.Sin((float)Orientation.X) * Math.Cos((float)Orientation.Y)); lookat.Y = (float)Math.Sin((float)Orientation.Y); lookat.Z = (float)(Math.Cos((float)Orientation.X) * Math.Cos((float)Orientation.Y)); lookat.Normalize(); return Matrix4.LookAt(Position, Position + lookat, Vector3.UnitY); }
public ShotTrail( SfxSystem sfxSystem, FXEvent fxEvent ) : base(sfxSystem, fxEvent) { sparkDir = Matrix.RotationQuaternion(fxEvent.Rotation).Forward + rand.GaussRadialDistribution(0, 0.1f); sparkDir.Normalize(); AddParticleStage("bulletSpark", 0, 0f, 0.1f, 10, false, EmitSpark ); AddLightStage( fxEvent.Origin + sparkDir * 0.1f , new Color4(125,110, 35,1), 0.5f, 100f, 3f ); //AddSoundStage( @"sound\weapon\bulletHit", fxEvent.Origin, 1, false ); }
private void UpdateView() { mForward = mTarget - Position; mForward.Normalize(); mViewNoTranspose = LeftHanded == false ? Matrix.LookAtRH(Position, mTarget, mUp) : Matrix.LookAtLH(Position, mTarget, mUp); Matrix.Invert(ref mViewNoTranspose, out mViewInverted); Matrix.Transpose(ref mViewNoTranspose, out mMatView); if (ViewChanged != null) ViewChanged(this, mMatView); mFrustum.Update(mViewNoTranspose, mProjNoTranspose); }