public void UpdateTransforms(ModelNode pNode, Matrix4 transf) { string nodename = pNode.Name; Matrix4 nodeTransf = Matrix4.Identity; double time; SingleAnimationNode pNodeAnim = FindNodeAnim(nodename, pNode.Mode, out time); if (pNodeAnim != null) { BEPUutilities.Vector3 vec = pNodeAnim.lerpPos(time); BEPUutilities.Quaternion quat = pNodeAnim.lerpRotate(time); OpenTK.Quaternion oquat = new OpenTK.Quaternion(quat.X, quat.Y, quat.Z, quat.W); Matrix4 trans; Matrix4.CreateTranslation(vec.X, vec.Y, vec.Z, out trans); trans.Transpose(); Matrix4 rot; Matrix4.CreateFromQuaternion(ref oquat, out rot); rot.Transpose(); Matrix4.Mult(ref trans, ref rot, out nodeTransf); } Matrix4 global; Matrix4.Mult(ref transf, ref nodeTransf, out global); for (int i = 0; i < pNode.Bones.Count; i++) { //Matrix4 modded; //Matrix4.Mult(ref globalInverse, ref global, out modded); Matrix4.Mult(ref global, ref pNode.Bones[i].Offset, out pNode.Bones[i].Transform); } for (int i = 0; i < pNode.Children.Count; i++) { UpdateTransforms(pNode.Children[i], global); } }
/// <summary> /// Constructs a new demo. /// </summary> /// <param name="game">Game owning this demo.</param> public BroadPhaseRemovalTestDemo(DemosGame game) : base(game) { Entity toAdd; //BoundingBox box = new BoundingBox(new Vector3(-5, 1, 1), new Vector3(5, 7, 7)); BEPUutilities.BoundingBox box = new BEPUutilities.BoundingBox(new BEPUutilities.Vector3(-500, -500, -500), new BEPUutilities.Vector3(500, 500, 500)); DynamicHierarchy dh = new DynamicHierarchy(); Random rand = new Random(0); RawList <Entity> entities = new RawList <Entity>(); for (int k = 0; k < 1000; k++) { BEPUutilities.Vector3 position = new BEPUutilities.Vector3((Fix64)rand.NextDouble() * (box.Max.X - box.Min.X) + box.Min.X, (Fix64)rand.NextDouble() * (box.Max.Y - box.Min.Y) + box.Min.Y, (Fix64)rand.NextDouble() * (box.Max.Z - box.Min.Z) + box.Min.Z); toAdd = new Box(position, 1, 1, 1, 1); entities.Add(toAdd); } testResults = new double[2]; int runCount = 10; for (int k = 0; k < runCount; k++) { for (int i = 0; i < entities.Count; i++) { dh.Add(entities[i].CollisionInformation); } long start = Stopwatch.GetTimestamp(); for (int i = 0; i < entities.Count; i++) { //dh.RemoveFast(entities[i].CollisionInformation); } long end = Stopwatch.GetTimestamp(); testResults[0] += (end - start) / (double)Stopwatch.Frequency; for (int i = 0; i < entities.Count; i++) { dh.Add(entities[i].CollisionInformation); } start = Stopwatch.GetTimestamp(); for (int i = 0; i < entities.Count; i++) { //dh.RemoveBrute(entities[i].CollisionInformation); } end = Stopwatch.GetTimestamp(); testResults[1] += (end - start) / (double)Stopwatch.Frequency; } testResults[0] /= runCount; testResults[1] /= runCount; }
public ref BEPUutilities.Vector3 CopyTo(ref BEPUutilities.Vector3 toVec) { toVec.X = x; toVec.Y = y; toVec.Z = z; return(ref toVec); }
public void Update(GameTime gameTime) { if (currentControlScheme == ControlScheme.A) { ControlSchemeA(); } if (currentControlScheme == ControlScheme.B) { ControlSchemeB(); } RayCastResult result; Vector3 pos = ParentObject.Transform.AbsoluteTransform.Translation; pos += new Vector3(0, -2, 0); BEPUutilities.Vector3 chopperPos = new BEPUutilities.Vector3(pos.X, pos.Y, pos.Z); BEPUutilities.Ray r = new BEPUutilities.Ray(chopperPos, BEPUutilities.Vector3.Down); if (SystemCore.PhysicsSimulation.RayCast(r, out result)) { if (result.HitObject.Tag is Chopper) { } else { //float distance = result.HitData.T; //if (distance < 5) // Ascend(lateralForce/2); //else // Descend(lateralForce/2); } } }
//Public public SpaceMngr() { fieldOfView = MathHelper.ToRadians(90f); nearPlaneDist = .0001f; farPlaneDist = 10000f; camTarget = Vector3.Zero; camPosition = new Vector3(0f, 0f, -100f); //3D position of the player's perspective view for monogame. center = new Vector2(AR.assetMngr.gDevice.Viewport.Width / 2, AR.assetMngr.gDevice.Viewport.Height / 2); aspectRatio = (float)AR.assetMngr.gDevice.Viewport.Width / (float)AR.assetMngr.gDevice.Viewport.Height; scale = (float)Math.Pow(1, aspectRatio); Console.WriteLine(aspectRatio); camPerception = Matrix.CreatePerspectiveFieldOfView(fieldOfView, AR.assetMngr.gDevice.Viewport.AspectRatio, nearPlaneDist, farPlaneDist); view = Matrix.CreateLookAt(camPosition, camTarget, Vector3.Up); area = Matrix.CreateWorld(camTarget, Vector3.Forward, Vector3.Up); spacetest = new Space(); BEPUutilities.Vector3 camPos = new BEPUutilities.Vector3(0f, 0f, -100f); camera = new Camera(camPos, 0.1f); }
void Events_ContactCreated(EntityCollidable sender, Collidable other, CollidablePairHandler pair, ContactData contact) { if (TheRegion.GlobalTickTimeLocal - lastSoundTime < soundmaxrate) { return; } lastSoundTime = TheRegion.GlobalTickTimeLocal; if (other is FullChunkObject) { ((ConvexFCOPairHandler)pair).ContactInfo(/*contact.Id*/ 0, out ContactInformation info); float vellen = (float)(Math.Abs(info.RelativeVelocity.X) + Math.Abs(info.RelativeVelocity.Y) + Math.Abs(info.RelativeVelocity.Z)); float mod = vellen / 5; if (mod > 2) { mod = 2; } Location block = new Location(contact.Position - contact.Normal * 0.01f); BlockInternal bi = TheRegion.GetBlockInternal(block); MaterialSound sound = ((Material)bi.BlockMaterial).Sound(); if (sound != MaterialSound.NONE) { new DefaultSoundPacketIn() { TheClient = TheClient }.PlayDefaultBlockSound(block, sound, mod, 0.5f * mod); } MaterialSound sound2 = Mat.Sound(); if (sound2 != MaterialSound.NONE) { new DefaultSoundPacketIn() { TheClient = TheClient }.PlayDefaultBlockSound(block, sound2, mod, 0.5f * mod); } } else if (other is EntityCollidable) { BEPUphysics.Entities.Entity e = ((EntityCollidable)other).Entity; BEPUutilities.Vector3 velocity = BEPUutilities.Vector3.Zero; if (e != null) { velocity = e.LinearVelocity; } BEPUutilities.Vector3 relvel = Body.LinearVelocity - velocity; float vellen = (float)(Math.Abs(relvel.X) + Math.Abs(relvel.Y) + Math.Abs(relvel.Z)); float mod = vellen / 5; if (mod > 2) { mod = 2; } MaterialSound sound = Mat.Sound(); if (sound != MaterialSound.NONE) { new DefaultSoundPacketIn() { TheClient = TheClient }.PlayDefaultBlockSound(new Location(contact.Position), sound, mod, 0.5f * mod); } } }
private void DrawMarchingCubes() { float xScale = (float)12 / DIM_SIZE; float yScale = (float)17 / DIM_SIZE; float zScale = (float)25 / DIM_SIZE; Vector3 scale = new Vector3(xScale, yScale, zScale); var gdata = particleManager.GetParticlesGData(DIM_SIZE, DIM_SIZE, DIM_SIZE, TRANSLATION, scale); //var gdata = getRandomGdata(dimSize); MarchingCubes.Poligonizator.Init(DIM_SIZE - 1, gdata, this.GraphicsDevice); var primitive = MarchingCubes.Poligonizator.Process(this.GraphicsDevice, ISO_LEVEL); Matrix view = BepuToXnaMatrix(Camera.ViewMatrix); Matrix projection = BepuToXnaMatrix(Camera.ProjectionMatrix); //Matrix world = Matrix.CreateTranslation(0, 0, 0); Matrix world = Matrix.CreateTranslation(TRANSLATION.X, TRANSLATION.Y, TRANSLATION.Z); world = Matrix.CreateScale(scale.X, scale.Y, scale.Z) * world; //Matrix.Multiply(world, 0.07f); _vertexCount = primitive.VertexCount; if (primitive.VertexCount > 0) { primitive.InitializePrimitive(this.GraphicsDevice); primitive.Draw(world, view, projection, Color.Blue); } }
public void UpdateCollider(Transform transform, Mesh mesh) { if (mesh != null) { Mesh _mesh = mesh; if (MeshHandler != null) { Physics.Remove(MeshHandler); MeshHandler = null; } BEPUutilities.Vector3[] points = new BEPUutilities.Vector3[_mesh._vertices.Length]; for (int i = 0; i < _mesh._vertices.Length; i++) { if (i < _mesh._vertices.Length) { points[i] = new BEPUutilities.Vector3(_mesh._vertices[i].X, _mesh._vertices[i].Y, _mesh._vertices[i].Z); } } MeshHandler = new StaticMesh(points, _mesh._indices, new BEPUutilities.AffineTransform(new BEPUutilities.Vector3(transform.Position.X, transform.Position.Y, transform.Position.Z))); Physics.Add(MeshHandler); _mesh = null; } }
/// <summary> /// Constructs a new demo. /// </summary> /// <param name="game">Game owning this demo.</param> public RayCastTestDemo(DemosGame game) : base(game) { Space.Add(new Box(new Vector3(0, -0.5f, 0), 50, 1, 50)); //Put whatever you'd like to ray cast here. var capsule = new Capsule(new Vector3(0, 1.2f, 0), 1, 0.6f); capsule.AngularVelocity = new Vector3(1, 1, 1); Space.Add(capsule); var cylinder = new Cylinder(new Vector3(0, 5, 0), 2, .5f); cylinder.AngularVelocity = new Vector3(1, -1, 1); Space.Add(cylinder); var points = new List<Vector3>(); var random = new Random(0); for (int k = 0; k < 40; k++) { points.Add(new Vector3(1 * (float)random.NextDouble(), 3 * (float)random.NextDouble(), 2 * (float)random.NextDouble())); } var convexHull = new ConvexHull(new Vector3(0, 10, 0), points); convexHull.AngularVelocity = new Vector3(-1, 1, 1); Space.Add(convexHull); game.Camera.Position = new Vector3(-10, 5, 10); game.Camera.Yaw((float)Math.PI / -4f); game.Camera.Pitch(-(float)Math.PI / 9f); //Starter ray. origin = new Vector3(10, 5, 0); direction = new Vector3(-3, -1, 0); }
/// <summary> /// Creates a new EntityModel. /// </summary> /// <param name="entity">Entity to attach the graphical representation to.</param> /// <param name="model">Graphical representation to use for the entity.</param> /// <param name="transform">Base transformation to apply to the model before moving to the entity.</param> /// <param name="game">Game to which this component will belong.</param> public ProjectileModel(Entity entity, Model model, BEPUutilities.Matrix transform, Game game, ParticleSystem explosionParticles, ParticleSystem explosionSmokeParticles, ParticleSystem projectileTrailParticles) : base(game) { this.entity = entity; this.model = model; this.Transform = transform; startPosition = new BEPUutilities.Vector3(entity.Position.X, entity.Position.Y, entity.Position.Z); this.explosionParticles = explosionParticles; this.explosionSmokeParticles = explosionSmokeParticles; //this.trailEmitter = new ParticleEmitter(projectileTrailParticles,trailParticlesPerSecond, MathConverter.Convert(entity.Position)); //Collect any bone transformations in the model itself. //The default cube model doesn't have any, but this allows the EntityModel to work with more complicated shapes. boneTransforms = new Matrix[model.Bones.Count]; foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.EnableDefaultLighting(); } } }
/// <summary> /// Gets the forward vector of this controller. /// </summary> /// <returns></returns> public Location ForwardVector() { OpenTK.Quaternion loquat = Position.ExtractRotation(true); BEPUutilities.Quaternion lquat = new BEPUutilities.Quaternion(loquat.X, loquat.Y, loquat.Z, loquat.W); BEPUutilities.Vector3 lforw = -BEPUutilities.Quaternion.Transform(BEPUutilities.Vector3.UnitZ, lquat); return(new Location(lforw)); }
public override void Update() { //Update propertis if (entity.Mass != Mass) { entity.Mass = Mass; } if (entity.LinearDamping != Drag) { entity.LinearDamping = Drag; } if (Mass > 0) { //Dynamic Parent.Transform.localPosition = Physics.VectorB2T(entity.Position); Parent.Transform.localRotation = Physics.QuaternionB2T(entity.Orientation); entity.Gravity = Physics.VectorT2B(Physics.Gravity); } else { //Kinematic BEPUutilities.Vector3 transformPosition = Physics.VectorT2B(Parent.Transform.Position); BEPUutilities.Quaternion transformOrientation = Physics.QuaternionT2B(Parent.Transform.Rotation); if (transformPosition != entity.Position) { entity.Position = transformPosition; } if (transformOrientation != entity.Orientation) { entity.Orientation = transformOrientation; } } base.Update(); }
/// <summary> /// Fired when the entity ticks. /// </summary> public void Tick() { Game game = Engine3D.Source as Game; Matrix4 m = Engine3D.MainView.PrimaryMatrix.Inverted(); m.Transpose(); float x = 2.0f * Engine3D.Client.MouseX / Engine3D.Window.Width - 1.0f; float y = 1.0f - 2.0f * Engine3D.Client.MouseY / Engine3D.Window.Height; Vector4 vIn = new Vector4(x, y, 1, 1); Vector4 vOut = Vector4.Transform(m, vIn); float mul = 1.0f / vOut.W; BEPUutilities.Vector3 dir = new BEPUutilities.Vector3(vOut.X * mul, vOut.Y * mul, vOut.Z * mul); if (game.Terrain.Body.RayCast(new BEPUutilities.Ray(Engine3D.MainCamera.Position.ToBVector(), dir), 100.0, out BEPUutilities.RayHit hit)) { BEPUutilities.Vector3 loc = hit.Location; Target = GridVertex.FromXY(loc.X, loc.Y); Vector2 pos = Target.ToCartesianCoords2D(); Entity.SetPosition(new Location(pos.X, pos.Y, game.Terrain.HeightMap[Target.U, Target.V] + 0.5)); BasicUnitAction action = game.UnitController.SelectedAction; if (action != null) { action.Update(); Rend.Color = action.AffectedVertices.Contains(Target) ? Color4F.Red : Color4F.Blue; } Rend.IsVisible = true; } else { Rend.IsVisible = false; } }
public BEPUphysics.ISpaceObject CreateCollision(JMapObjectData block) { BEPUphysics.ISpaceObject collision = null; if (block.colliderTypes == 0) { BEPUphysics.EntityStateManagement.MotionState ms = new BEPUphysics.EntityStateManagement.MotionState(); ms.Position = new BEPUutilities.Vector3(block.mapPos.x, block.mapPos.y, block.mapPos.z); ms.Orientation = new BEPUutilities.Quaternion(block.mapRot.x, block.mapRot.y, block.mapRot.z, block.mapRot.w); collision = new Box(ms, block.mapScale.x, 1f, block.mapScale.y); } else { var vertices = new BEPUutilities.Vector3[block.meshColliderVertices.Length]; int[] indices = new int[block.meshColliderIndices.Length]; for (int i = 0; i < vertices.Length; ++i) { vertices[i] = new BEPUutilities.Vector3(block.meshColliderVertices[i].x, block.meshColliderVertices[i].y, block.meshColliderVertices[i].z); } for (int i = 0; i < indices.Length; ++i) { indices[i] = block.meshColliderIndices[i]; } var Position = new BEPUutilities.Vector3(block.mapPos.x, block.mapPos.y, block.mapPos.z); var Orientation = new BEPUutilities.Quaternion(block.mapRot.x, block.mapRot.y, block.mapRot.z, block.mapRot.w); var staticMesh = new BEPUphysics.BroadPhaseEntries.StaticMesh(vertices, indices, new BEPUutilities.AffineTransform(new BEPUutilities.Vector3(0.1f, 0.1f, 0.1f), Orientation, Position)); //staticMesh.Sidedness = BEPUutilities.TriangleSidedness.DoubleSided; collision = staticMesh; } space.Add(collision); return(collision); }
public void Render3D(Location pos, float rot, Location size) { BEPUutilities.Matrix rot1 = BEPUutilities.Matrix.CreateFromAxisAngle(BEPUutilities.Vector3.UnitZ, rot) * BEPUutilities.Matrix.CreateFromAxisAngle(BEPUutilities.Vector3.UnitX, (float)(Math.PI * 0.25)); if (RenderedBlock != null) { TheClient.isVox = false; TheClient.SetVox(); TheClient.Rendering.SetMinimumLight(0.9f, TheClient.MainWorldView); RenderedBlock.WorldTransform = BEPUutilities.Matrix.CreateScale(size.ToBVector() * 0.70f) * rot1 * BEPUutilities.Matrix.CreateTranslation(pos.ToBVector()); RenderedBlock.Render(); TheClient.Rendering.SetMinimumLight(0f, TheClient.MainWorldView); } else if (RenderedModel != null) { TheClient.isVox = true; TheClient.SetEnts(); TheClient.Rendering.SetMinimumLight(0.9f, TheClient.MainWorldView); BEPUutilities.RigidTransform rt = BEPUutilities.RigidTransform.Identity; RenderedModel.Shape.GetBoundingBox(ref rt, out BEPUutilities.BoundingBox bb); BEPUutilities.Vector3 scale = BEPUutilities.Vector3.Max(bb.Max, -bb.Min); float len = (float)scale.Length(); RenderedModel.WorldTransform = BEPUutilities.Matrix.CreateScale(size.ToBVector() * len) * rot1 * BEPUutilities.Matrix.CreateTranslation(pos.ToBVector()); RenderedModel.RenderSimpler(); TheClient.Rendering.SetMinimumLight(0f, TheClient.MainWorldView); } }
public void Propel(int ownerActorId) { mOwnerActorId = ownerActorId; DynamicCollisionComponent collisionComponent = Owner.GetComponent <DynamicCollisionComponent>(ActorComponent.ComponentType.Physics); BEPUutilities.Vector3 forward = collisionComponent.Entity.OrientationMatrix.Forward * mSpeed; collisionComponent.Entity.ApplyLinearImpulse(ref forward); }
public static Vector3 Convert(BEPUutilities.Vector3 bepuVector) { Vector3 toReturn; toReturn.X = bepuVector.X; toReturn.Y = bepuVector.Y; toReturn.Z = bepuVector.Z; return(toReturn); }
public BEPUutilities.Vector3 Forward(Matrix4 matrix) { BEPUutilities.Vector3 vector = new BEPUutilities.Vector3(); vector.X = matrix.M31; vector.Y = matrix.M32; vector.Z = matrix.M33; return(vector); }
public static BEPUutilities.Vector3[] Convert(Vector3[] xnaVectors) { var bepuVectors = new BEPUutilities.Vector3[xnaVectors.Length]; for (int i = 0; i < xnaVectors.Length; i++) { Convert(ref xnaVectors[i], out bepuVectors[i]); } return bepuVectors; }
private bool asteroidClose(Vector3 pos) { foreach (Vector3 v in _locations) { if (Vector3.Distance(v, pos) < 15) return true; } return false; }
internal void Teleport(Microsoft.Xna.Framework.Vector3 vector3) { BEPUutilities.Vector3 v = vector3.ToBepuVector(); foreach (Entity e in vehicle.InvolvedEntities) { e.Position = v; } }
/// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); //GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default; // Copy any parent transforms. Matrix[] transforms = new Matrix[ship.Bones.Count]; ship.CopyAbsoluteBoneTransformsTo(transforms); // Draw the model. A model can have multiple meshes, so loop. cameraPositionBepu = physCapsule.Position + 5 * BEPUutilities.Vector3.Normalize(physCapsule.OrientationMatrix.Backward); if (BEPUutilities.Vector3.Normalize(physCapsule.OrientationMatrix.Backward) == BEPUutilities.Vector3.Up) { var modelRight = -0.01f * physCapsule.OrientationMatrix.Right; physCapsule.ApplyAngularImpulse(ref modelRight); } cameraPositionBepu = cameraPositionBepu + 1.5f * BEPUutilities.Vector3.Normalize(physCapsule.OrientationMatrix.Up); foreach (ModelMesh mesh in ship.Meshes) { // This is where the mesh orientation is set, as well // as our camera and projection. foreach (BasicEffect effect in mesh.Effects) { effect.Alpha = 1f; effect.LightingEnabled = false; effect.World = Matrix.CreateScale(0.001f) * MathConverter.Convert(physCapsule.WorldTransform);//MathConverter.Convert(BEPUutilities.Matrix.Multiply(modelRotationBepu, physCapsule.WorldTransform));// MathConverter.Convert(physCapsule.WorldTransform); effect.View = Matrix.CreateLookAt(MathConverter.Convert(cameraPositionBepu), MathConverter.Convert(physCapsule.Position), MathConverter.Convert(physCapsule.OrientationMatrix.Up)); effect.Projection = Matrix.CreatePerspectiveFieldOfView( MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f); } // Draw the mesh, using the effects set above. mesh.Draw(); } base.Draw(gameTime); // Draw info about current speed spriteBatch.Begin(); spriteBatch.DrawString(dfont, "Current speed:" + speed + " m/s", Vector2.Zero, Color.White); spriteBatch.DrawString(dfont, "Land at <6 m/s! ", new Vector2(0, 15), Color.White); if (goalReached) { spriteBatch.DrawString(dfont, "Goal reached!", new Vector2(350, 150), Color.Gold); if (goalReachedTooFast) { spriteBatch.DrawString(dfont, "Too fast - crash landing!", new Vector2(320, 165), Color.Red); } else { spriteBatch.DrawString(dfont, "Mission complete!", new Vector2(340, 165), Color.Red); } } spriteBatch.End(); }
public override void Enter(SteeringBlender steering, Actor owner, IAgentStateManager agent) { ZombieSkillSet zss = owner.GetBehaviorThatImplementsType <ZombieSkillSet>(); //zss.RangedSkill.CurrentOperation = WeaponFunctions.Neutral; BipedControllerComponent bcc = owner.GetComponent <BipedControllerComponent>(ActorComponent.ComponentType.Control); zss.RangedSkill.UpdateInputState(false, bcc); zss.MeleeSkill.UpdateInputState(false, bcc); int opponentId = agent.GetProperty <int>(AgentPropertyName.ActiveOpponent); Actor opponent = GameResources.ActorManager.GetActorById(opponentId); BipedControllerComponent opponentBcc = opponent.GetComponent <BipedControllerComponent>(ActorComponent.ComponentType.Control); BepuVec3 towardOpponent = opponentBcc.Controller.Body.Position - bcc.Controller.Body.Position; towardOpponent.Y = 0.0f; towardOpponent.Normalize(); const float MOVE_SECS_MAX = 2.5f; const float MOVE_SECS_MIN = 0.5f; float moveRand = SlagMath.Get0To1UpperFloat(GameResources.ActorManager.Random); switch (mMovementType) { case MovementType.Lateral: BepuVec3 right = BepuVec3.Cross(towardOpponent, BepuVec3.Up); // Make the random symmetrical about 0.5f so that we can divide it into two equal segments for right and left. moveRand = Math.Abs(moveRand - 0.5f); mDurationTicks = (long)(TimeSpan.TicksPerSecond * (moveRand * 2.0f * (MOVE_SECS_MAX - MOVE_SECS_MIN) + MOVE_SECS_MIN)); steering.Target = BepuConverter.Convert(bcc.Controller.Body.Position + (moveRand > 0.5f ? right : -right) * 100.0f); break; case MovementType.Close: steering.Target = BepuConverter.Convert(opponentBcc.Controller.Body.Position + towardOpponent * 100.0f); mDurationTicks = (long)(TimeSpan.TicksPerSecond * (moveRand * (MOVE_SECS_MAX - MOVE_SECS_MIN) + MOVE_SECS_MIN)); break; case MovementType.Retreat: steering.Target = BepuConverter.Convert(opponentBcc.Controller.Body.Position - towardOpponent * 100.0f); mDurationTicks = (long)(TimeSpan.TicksPerSecond * (moveRand * (MOVE_SECS_MAX - MOVE_SECS_MIN) + MOVE_SECS_MIN)); break; default: steering.Target = BepuConverter.Convert(towardOpponent * 100.0f); mDurationTicks = 0; break; } steering.Weights[(int)SteeringBlender.WeightType.Arrive] = 0.0f; steering.Weights[(int)SteeringBlender.WeightType.Seek] = 0.67f; steering.Weights[(int)SteeringBlender.WeightType.Wander] = 0.33f; steering.Weights[(int)SteeringBlender.WeightType.Wait] = 0.0f; steering.Urgency = 1.0f; steering.ForceScale = 1.0f; }
public static BEPUutilities.Vector3[] Convert(Vector3[] xnaVectors) { var bepuVectors = new BEPUutilities.Vector3[xnaVectors.Length]; for (int i = 0; i < xnaVectors.Length; i++) { Convert(ref xnaVectors[i], out bepuVectors[i]); } return(bepuVectors); }
private void HitSparks(BEPUutilities.Vector3 position) { Actor sparks = GameResources.ActorManager.SpawnTemplate("Sparks"); TransformComponent sparksXForm = sparks.GetComponent <TransformComponent>(ActorComponent.ComponentType.Transform); sparksXForm.Translation = BepuConverter.Convert(position); Sparks sparksBehavior = sparks.GetBehavior <Sparks>(); sparksBehavior.Emit(); }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { //Set up drawers ModelDrawer = new InstancedModelDrawer(this); //Create the space itself Space = new Space(); var parallelLooper = new ParallelLooper(); //This section lets the engine know that it can make use of multithreaded systems //by adding threads to its thread pool. if (Environment.ProcessorCount > 1) { for (int i = 0; i < Environment.ProcessorCount; i++) { parallelLooper.AddThread(); } } Space = new Space(parallelLooper); Space.ForceUpdater.Gravity = new Vector3(0, -9.81f, 0); Space.Add(new Box(Vector3.Zero, 30, 1, 30)); //Create a bunch of boxes randomly. Random random = new Random(); int boxCount = 100; BoundingBox spawnVolume = new BoundingBox(new Vector3(-10, 10, -10), new Vector3(10, 30, 10)); for (int i = 0; i < boxCount; i++) { Vector3 position = new Vector3((float)(random.NextDouble() - 0.5f) * (spawnVolume.Max.X - spawnVolume.Min.X), (float)(random.NextDouble() - 0.5f) * (spawnVolume.Max.Y - spawnVolume.Min.Y), (float)(random.NextDouble() - 0.5f) * (spawnVolume.Max.Z - spawnVolume.Min.Z)) + (spawnVolume.Min + spawnVolume.Max) / 2; Space.Add(new Box(position, 1, 1, 1, 1)); } #region DisplayObject creation foreach (Entity e in Space.Entities) { if ((string)e.Tag != "noDisplayObject") { ModelDrawer.Add(e); } else//Remove the now unnecessary tag. { e.Tag = null; } } #endregion }
private void BashDust(BEPUutilities.Vector3 position) { Actor dust = GameResources.ActorManager.SpawnTemplate("Dust"); TransformComponent dustXForm = dust.GetComponent <TransformComponent>(ActorComponent.ComponentType.Transform); dustXForm.Translation = BepuConverter.Convert(position); Sparks sparksBehavior = dust.GetBehavior <Sparks>(); sparksBehavior.Emit(); }
public void UpdateTransforms(ModelNode pNode, Matrix4 transf) { string nodename = pNode.Name; Matrix4 nodeTransf = Matrix4.Identity; double time; SingleAnimationNode pNodeAnim = FindNodeAnim(nodename, pNode.Mode, out time); if (pNodeAnim != null) { BEPUutilities.Vector3 vec = pNodeAnim.lerpPos(time); BEPUutilities.Quaternion quat = pNodeAnim.lerpRotate(time); Quaternion oquat = new Quaternion((float)quat.X, (float)quat.Y, (float)quat.Z, (float)quat.W); Matrix4 trans; Matrix4.CreateTranslation((float)vec.X, (float)vec.Y, (float)vec.Z, out trans); trans.Transpose(); Matrix4 rot; Matrix4.CreateFromQuaternion(ref oquat, out rot); Matrix4 r2; if (CustomAnimationAdjustments.TryGetValue(nodename, out r2)) { rot *= r2; } rot.Transpose(); Matrix4.Mult(ref trans, ref rot, out nodeTransf); } else { Matrix4 temp; if (CustomAnimationAdjustments.TryGetValue(nodename, out temp)) { temp.Transpose(); nodeTransf = temp; } } Matrix4 global; Matrix4.Mult(ref transf, ref nodeTransf, out global); for (int i = 0; i < pNode.Bones.Count; i++) { if (ForceBoneNoOffset) { pNode.Bones[i].Transform = global; } else { Matrix4.Mult(ref global, ref pNode.Bones[i].Offset, out pNode.Bones[i].Transform); } } for (int i = 0; i < pNode.Children.Count; i++) { UpdateTransforms(pNode.Children[i], global); } }
public MeshCollider(Transform transform, Vector3[] vertices, int[] indices) { BEPUutilities.Vector3[] points = new BEPUutilities.Vector3[vertices.Length]; for (int i = 0; i < vertices.Length; i++) { points[i] = new BEPUutilities.Vector3(vertices[i].X, vertices[i].Y, vertices[i].Z); } MeshHandler = new StaticMesh(points, indices, new BEPUutilities.AffineTransform(new BEPUutilities.Vector3(transform.Position.X, transform.Position.Y, transform.Position.Z))); Physics.Add(MeshHandler); }
private void AddThrough() { Vector3 center = new Vector3(0, 10, 20); int width = 10; int length = 20; int angleX = 0; int angleZ = 100; Through through = new Through(center, width, length, angleX, angleZ); space.Add(through.Box1); space.Add(through.Box2); }
public override void Execute(PlayerCommandEntry entry) { ItemStack stack = entry.Player.Items.GetItemForSlot(entry.Player.Items.cItem); // Don't throw bound items... if (stack.IsBound) { if (stack.Info.Name == "open_hand") // TODO: Better handling of special cases -> Info.Throw() ? { if (entry.Player.GrabJoint != null) { BEPUutilities.Vector3 launchvec = (entry.Player.ItemDir * 100).ToBVector(); // TODO: Strength limits PhysicsEntity pe = entry.Player.GrabJoint.Ent2; entry.Player.TheRegion.DestroyJoint(entry.Player.GrabJoint); entry.Player.GrabJoint = null; pe.Body.ApplyLinearImpulse(ref launchvec); pe.Body.ActivityInformation.Activate(); return; } } entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "^1Can't throw this."); // TODO: Language, entry.output, etc. return; } // Ensure no spam... if (entry.Player.LastThrowTime > entry.Player.TheRegion.GlobalTickTime - 3) { entry.Player.SendMessage(TextChannel.COMMAND_RESPONSE, "^1Thrown too rapidly!"); return; } entry.Player.LastThrowTime = entry.Player.TheRegion.GlobalTickTime; // Actually throw it now... ItemStack item = stack.Duplicate(); item.Count = 1; PhysicsEntity ie = entry.Player.TheRegion.ItemToEntity(item); // TODO: Animate player Location fvel = entry.Player.ItemDir; ie.SetPosition(entry.Player.ItemSource() + fvel * 2); ie.SetOrientation(entry.Player.GetOrientation()); ie.SetVelocity(fvel * 15); entry.Player.TheRegion.SpawnEntity(ie); if (stack.Count > 1) { stack.Count -= 1; entry.Player.Network.SendPacket(new SetItemPacketOut(entry.Player.Items.cItem - 1, stack)); } else { entry.Player.Items.RemoveItem(entry.Player.Items.cItem); } }
public UniverseWall(Game game, BEPUutilities.Vector3 pos, int dimX, int dimY, int dimZ) : this(game) { physicsObject = new CompoundBody(new List <CompoundShapeEntry> { new CompoundShapeEntry(new BoxShape(10f, dimY, dimZ), new BEPUutilities.Vector3(dimX / 2, 0, 0)), new CompoundShapeEntry(new BoxShape(10f, dimY, dimZ), new BEPUutilities.Vector3(-dimX / 2, 0, 0)), new CompoundShapeEntry(new BoxShape(dimX, 10f, dimZ), new BEPUutilities.Vector3(0, dimY / 2, 0)), new CompoundShapeEntry(new BoxShape(dimX, 10f, dimZ), new BEPUutilities.Vector3(0, -dimY / 2, 0)), new CompoundShapeEntry(new BoxShape(dimX, dimY, 10f), new BEPUutilities.Vector3(0, 0, dimZ / 2)), new CompoundShapeEntry(new BoxShape(dimX, dimY, 10f), new BEPUutilities.Vector3(0, 0, -dimZ / 2)), }); physicsObject.CollisionInformation.Tag = this; Game.Services.GetService <Space>().Add(physicsObject); }
public override void Update(Fix64 dt) { base.Update(dt); #if WINDOWS if (Game.MouseInput.RightButton == ButtonState.Pressed) { origin = Game.Camera.Position; direction = Game.Camera.WorldMatrix.Forward; } #endif hitAnything = Space.RayCast(new Ray(origin, direction * 3), 10000, out result); }
public override void Update(float dt) { base.Update(dt); #if WINDOWS if (Game.MouseInput.RightButton == ButtonState.Pressed) { origin = Game.Camera.Position; direction = Game.Camera.WorldMatrix.Forward; } #endif hitAnything = Space.RayCast(new Ray(origin, direction * 3), 10000, out result); }
private void BuildLocations(int count) { while(_locations.Count < count) { int x = GameInformation.Instance.Rand.Next(0, (int)LevelSize.X * 20) - (int)LevelSize.X * 10; int y = GameInformation.Instance.Rand.Next(0, (int)LevelSize.X * 20) - (int)LevelSize.X * 10; int z = GameInformation.Instance.Rand.Next(0, (int)LevelSize.X * 20) - (int)LevelSize.X * 10; Vector3 pos = new Vector3(x, y, z); if ((x * x + y * y + z * z) < (int)LevelSize.X * 20 && !asteroidClose(pos)) _locations.Add(new Vector3(x, y, z)); } }
private void BuildSize(int size) { switch (size) { case 1: LevelSize = new Vector3(300, 300, 300); return; case 2: LevelSize = new Vector3(450, 450, 450); return; case 3: LevelSize = new Vector3(600, 600, 600); return; } }
public static float TestTransformScalarOld(int iterationCount) { bVector3 v1 = new bVector3(1, 2, 3); bVector3 v2 = new bVector3(1, 2, 3); float accumulator = 0; for (int i = 0; i < iterationCount; ++i) { bVector3 r0, r1; bVector3.Cross(ref v1, ref v2, out r0); bVector3.Cross(ref r0, ref v2, out r1); bVector3.Cross(ref r1, ref v2, out r0); bVector3.Cross(ref r0, ref v2, out r1); bVector3.Cross(ref r1, ref v2, out r0); bVector3.Cross(ref r0, ref v2, out r1); bVector3.Cross(ref r1, ref v2, out r0); bVector3.Cross(ref r0, ref v2, out r1); bVector3.Cross(ref r1, ref v2, out r0); bVector3.Cross(ref r0, ref v2, out r1); accumulator += 0.000001f * r1.X; } return accumulator; }
public static float TestTransformScalar(int iterationCount) { bVector3 v = new bVector3(1, 2, 3); bAffineTransform m = bAffineTransform.Identity; float accumulator = 0; for (int i = 0; i < iterationCount; ++i) { bVector3 r0, r1; bAffineTransform.Transform(ref v, ref m, out r0); bAffineTransform.Transform(ref r0, ref m, out r1); bAffineTransform.Transform(ref r1, ref m, out r0); bAffineTransform.Transform(ref r0, ref m, out r1); bAffineTransform.Transform(ref r1, ref m, out r0); bAffineTransform.Transform(ref r0, ref m, out r1); bAffineTransform.Transform(ref r1, ref m, out r0); bAffineTransform.Transform(ref r0, ref m, out r1); bAffineTransform.Transform(ref r1, ref m, out r0); bAffineTransform.Transform(ref r0, ref m, out r1); accumulator += 0.000001f * r1.X; } return accumulator; }
public override void Spawn() { List<BEPUutilities.Vector3> vecs = TheClient.Models.Handler.GetCollisionVertices(model.Original); Location zero = new Location(vecs[0]); AABB abox = new AABB() { Min = zero, Max = zero }; for (int v = 1; v < vecs.Count; v++) { abox.Include(new Location(vecs[v])); } ModelMin = abox.Min.ToBVector(); ModelMax = abox.Max.ToBVector(); }
protected Block(Vector3 position) { Position = position; }
public static void Test() { Vector3 v1 = new Vector3(0, 0, 1); Vector3 v2 = new Vector3(0, 0, 2); Vector3 v3 = new Vector3(0, 0, 3); Vector3 v4 = new Vector3(0, 0, 4); Vector3 v5 = new Vector3(0, 0, 5); Vector3 v6 = new Vector3(0, 0, 6); Vector3 v7 = new Vector3(0, 0, 7); Vector3 v8 = new Vector3(0, 0, 8); Matrix3x3 m = new Matrix3x3 { X = new Vector3(1, 0, 0), Y = new Vector3(0, 1, 0), Z = new Vector3(0, 0, 1) }; Matrix4x4 m4 = new Matrix4x4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); Vector3 t = Matrix3x3.Transform(v1, m); Matrix3x3.Transform(ref t, ref m, out t); Console.WriteLine($"t to preload: {t}"); double time, endTime; const int testIterations = 10000000; time = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Vector3 refAccumulator = new Vector3(); for (int i = 0; i < testIterations; ++i) { Vector3 t1, t2, t3, t4, t5, t6, t7, t8; Matrix3x3.Transform(ref v1, ref m, out t1); Matrix3x3.Transform(ref v2, ref m, out t2); Matrix3x3.Transform(ref v3, ref m, out t3); Matrix3x3.Transform(ref v4, ref m, out t4); Matrix3x3.Transform(ref v5, ref m, out t5); Matrix3x3.Transform(ref v6, ref m, out t6); Matrix3x3.Transform(ref v7, ref m, out t7); Matrix3x3.Transform(ref v8, ref m, out t8); refAccumulator += t1 + t2 + t3 + t4 + t5 + t6 + t7 + t8; } endTime = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Console.WriteLine($"ref time: {endTime - time}, acc: {refAccumulator}"); time = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Vector3 nonrefAccumulator = new Vector3(); for (int i = 0; i < testIterations; ++i) { var t1 = Matrix3x3.Transform(v1, m); var t2 = Matrix3x3.Transform(v2, m); var t3 = Matrix3x3.Transform(v3, m); var t4 = Matrix3x3.Transform(v4, m); var t5 = Matrix3x3.Transform(v5, m); var t6 = Matrix3x3.Transform(v6, m); var t7 = Matrix3x3.Transform(v7, m); var t8 = Matrix3x3.Transform(v8, m); nonrefAccumulator += t1 + t2 + t3 + t4 + t5 + t6 + t7 + t8; } endTime = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Console.WriteLine($"nonref time: {endTime - time}, acc: {nonrefAccumulator}"); time = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Vector3 ref2Accumulator = new Vector3(); for (int i = 0; i < testIterations; ++i) { Vector3 t1, t2, t3, t4, t5, t6, t7, t8; Matrix3x3.Transform2(ref v1, ref m, out t1); Matrix3x3.Transform2(ref v2, ref m, out t2); Matrix3x3.Transform2(ref v3, ref m, out t3); Matrix3x3.Transform2(ref v4, ref m, out t4); Matrix3x3.Transform2(ref v5, ref m, out t5); Matrix3x3.Transform2(ref v6, ref m, out t6); Matrix3x3.Transform2(ref v7, ref m, out t7); Matrix3x3.Transform2(ref v8, ref m, out t8); ref2Accumulator += t1 + t2 + t3 + t4 + t5 + t6 + t7 + t8; } endTime = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Console.WriteLine($"ref2 time: {endTime - time}, acc: {ref2Accumulator}"); time = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Vector3 nonref2Accumulator = new Vector3(); for (int i = 0; i < testIterations; ++i) { var t1 = Matrix3x3.Transform2(v1, m); var t2 = Matrix3x3.Transform2(v2, m); var t3 = Matrix3x3.Transform2(v3, m); var t4 = Matrix3x3.Transform2(v4, m); var t5 = Matrix3x3.Transform2(v5, m); var t6 = Matrix3x3.Transform2(v6, m); var t7 = Matrix3x3.Transform2(v7, m); var t8 = Matrix3x3.Transform2(v8, m); nonref2Accumulator += t1 + t2 + t3 + t4 + t5 + t6 + t7 + t8; } endTime = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Console.WriteLine($"nonref2 time: {endTime - time}, acc: {nonref2Accumulator}"); time = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Vector3 refTransposeAccumulator = new Vector3(); for (int i = 0; i < testIterations; ++i) { Vector3 t1, t2, t3, t4, t5, t6, t7, t8; Matrix3x3.TransformTranspose(ref v1, ref m, out t1); Matrix3x3.TransformTranspose(ref v2, ref m, out t2); Matrix3x3.TransformTranspose(ref v3, ref m, out t3); Matrix3x3.TransformTranspose(ref v4, ref m, out t4); Matrix3x3.TransformTranspose(ref v5, ref m, out t5); Matrix3x3.TransformTranspose(ref v6, ref m, out t6); Matrix3x3.TransformTranspose(ref v7, ref m, out t7); Matrix3x3.TransformTranspose(ref v8, ref m, out t8); refTransposeAccumulator += t1 + t2 + t3 + t4 + t5 + t6 + t7 + t8; } endTime = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Console.WriteLine($"refTranspose time: {endTime - time}, acc: {refTransposeAccumulator}"); time = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Vector3 nonrefTransposeAccumulator = new Vector3(); for (int i = 0; i < testIterations; ++i) { var t1 = Matrix3x3.TransformTranspose(v1, m); var t2 = Matrix3x3.TransformTranspose(v2, m); var t3 = Matrix3x3.TransformTranspose(v3, m); var t4 = Matrix3x3.TransformTranspose(v4, m); var t5 = Matrix3x3.TransformTranspose(v5, m); var t6 = Matrix3x3.TransformTranspose(v6, m); var t7 = Matrix3x3.TransformTranspose(v7, m); var t8 = Matrix3x3.TransformTranspose(v8, m); nonrefTransposeAccumulator += t1 + t2 + t3 + t4 + t5 + t6 + t7 + t8; } endTime = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Console.WriteLine($"nonrefTranspose time: {endTime - time}, acc: {nonrefTransposeAccumulator}"); time = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Vector3 netAccumulator = new Vector3(); for (int i = 0; i < testIterations; ++i) { var t1 = Vector3.TransformNormal(v1, m4); var t2 = Vector3.TransformNormal(v2, m4); var t3 = Vector3.TransformNormal(v3, m4); var t4 = Vector3.TransformNormal(v4, m4); var t5 = Vector3.TransformNormal(v5, m4); var t6 = Vector3.TransformNormal(v6, m4); var t7 = Vector3.TransformNormal(v7, m4); var t8 = Vector3.TransformNormal(v8, m4); netAccumulator += t1 + t2 + t3 + t4 + t5 + t6 + t7 + t8; } endTime = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Console.WriteLine($"net time: {endTime - time}, acc: {netAccumulator}"); time = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; var v1b = new BEPUVector3(0, 0, 1); var v2b = new BEPUVector3(0, 0, 2); var v3b = new BEPUVector3(0, 0, 3); var v4b = new BEPUVector3(0, 0, 4); var v5b = new BEPUVector3(0, 0, 5); var v6b = new BEPUVector3(0, 0, 6); var v7b = new BEPUVector3(0, 0, 7); var v8b = new BEPUVector3(0, 0, 8); BEPUMatrix3x3 mb = new BEPUMatrix3x3(1, 0, 0, 0, 1, 0, 0, 0, 1); BEPUVector3 bepuAccumulator = new BEPUVector3(); for (int i = 0; i < testIterations; ++i) { BEPUVector3 t1, t2, t3, t4, t5, t6, t7, t8; BEPUMatrix3x3.Transform(ref v1b, ref mb, out t1); BEPUMatrix3x3.Transform(ref v2b, ref mb, out t2); BEPUMatrix3x3.Transform(ref v3b, ref mb, out t3); BEPUMatrix3x3.Transform(ref v4b, ref mb, out t4); BEPUMatrix3x3.Transform(ref v5b, ref mb, out t5); BEPUMatrix3x3.Transform(ref v6b, ref mb, out t6); BEPUMatrix3x3.Transform(ref v7b, ref mb, out t7); BEPUMatrix3x3.Transform(ref v8b, ref mb, out t8); BEPUVector3.Add(ref bepuAccumulator, ref t1, out bepuAccumulator); BEPUVector3.Add(ref bepuAccumulator, ref t2, out bepuAccumulator); BEPUVector3.Add(ref bepuAccumulator, ref t3, out bepuAccumulator); BEPUVector3.Add(ref bepuAccumulator, ref t4, out bepuAccumulator); BEPUVector3.Add(ref bepuAccumulator, ref t5, out bepuAccumulator); BEPUVector3.Add(ref bepuAccumulator, ref t6, out bepuAccumulator); BEPUVector3.Add(ref bepuAccumulator, ref t7, out bepuAccumulator); BEPUVector3.Add(ref bepuAccumulator, ref t8, out bepuAccumulator); } endTime = (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency; Console.WriteLine($"bepu time: {endTime - time}, acc: {bepuAccumulator}"); }
public void Render3D(View3D view) { GL.Enable(EnableCap.CullFace); if (view.ShadowsOnly) { for (int i = 0; i < TheRegion.ShadowCasters.Count; i++) { TheRegion.ShadowCasters[i].Render(); } if (view.TranspShadows) { TheRegion.RenderClouds(); } } else { GL.ActiveTexture(TextureUnit.Texture1); Textures.NormalDef.Bind(); GL.ActiveTexture(TextureUnit.Texture0); if (view.FBOid == FBOID.MAIN) { s_fbot.Bind(); RenderSkybox(); s_fbo.Bind(); } if (view.FBOid == FBOID.FORWARD_SOLID || view.FBOid == FBOID.FORWARD_TRANSP) { RenderSkybox(); // TODO: s_fbot equivalent for forward renderer? } if (view.FBOid == FBOID.TRANSP_UNLIT || view.FBOid == FBOID.TRANSP_LIT || view.FBOid == FBOID.TRANSP_SHADOWS || view.FBOid == FBOID.FORWARD_SOLID || view.FBOid == FBOID.FORWARD_TRANSP) { Rendering.SetMinimumLight(1); TheRegion.RenderClouds(); Rendering.SetMinimumLight(0); } for (int i = 0; i < TheRegion.Entities.Count; i++) { TheRegion.Entities[i].Render(); } SetEnts(); if (CVars.g_weathermode.ValueI > 0) { RainCylPos += gDelta * ((CVars.g_weathermode.ValueI == 1) ? 0.5 : 0.1); while (RainCylPos > 1.0) { RainCylPos -= 1.0; } Matrix4d rot = (CVars.g_weathermode.ValueI == 2) ? Matrix4d.CreateRotationZ(Math.Sin(RainCylPos * 2f * Math.PI) * 0.1f) : Matrix4d.Identity; for (int i = -10; i <= 10; i++) { Matrix4d mat = rot * Matrix4d.CreateTranslation(ClientUtilities.ConvertD(MainWorldView.CameraPos + new Location(0, 0, 4 * i + RainCylPos * -4))); MainWorldView.SetMatrix(2, mat); if (CVars.g_weathermode.ValueI == 1) { RainCyl.Draw(); } else if (CVars.g_weathermode.ValueI == 2) { SnowCyl.Draw(); } } } if (MainWorldView.FBOid == FBOID.MAIN) { Rendering.SetMinimumLight(1f); } GL.ActiveTexture(TextureUnit.Texture1); Textures.NormalDef.Bind(); GL.ActiveTexture(TextureUnit.Texture0); Particles.Engine.Render(); } SetEnts(); isVox = false; SetVox(); TheRegion.Render(); SetEnts(); TheRegion.RenderPlants(); if (!view.ShadowsOnly) { GL.ActiveTexture(TextureUnit.Texture1); Textures.NormalDef.Bind(); GL.ActiveTexture(TextureUnit.Texture0); } Textures.White.Bind(); Location mov = (CameraFinalTarget - MainWorldView.CameraPos) / CameraDistance; Location cpos = CameraFinalTarget - (CameraImpactNormal * 0.01f); Location cpos2 = CameraFinalTarget + (CameraImpactNormal * 0.91f); // TODO: 5 -> Variable length (Server controlled?) if (TheRegion.GetBlockMaterial(cpos) != Material.AIR && CameraDistance < 5) { if (CVars.u_highlight_targetblock.ValueB) { Location cft = cpos.GetBlockLocation(); GL.LineWidth(3); Rendering.SetColor(Color4.Blue); Rendering.SetMinimumLight(1.0f); Rendering.RenderLineBox(cft - mov * 0.01f, cft + Location.One - mov * 0.01f); GL.LineWidth(1); } if (CVars.u_highlight_placeblock.ValueB) { Rendering.SetColor(Color4.Cyan); Location cft2 = cpos2.GetBlockLocation(); Rendering.RenderLineBox(cft2, cft2 + Location.One); } Rendering.SetColor(Color4.White); } if (MainWorldView.FBOid == FBOID.MAIN) { Rendering.SetMinimumLight(0f); } if (CVars.n_debugmovement.ValueB) { Rendering.SetColor(Color4.Red); GL.LineWidth(5); foreach (Chunk chunk in TheRegion.LoadedChunks.Values) { if (chunk._VBO == null && !chunk.IsAir) { Rendering.RenderLineBox(chunk.WorldPosition.ToLocation() * Chunk.CHUNK_SIZE, (chunk.WorldPosition.ToLocation() + Location.One) * Chunk.CHUNK_SIZE); } } GL.LineWidth(1); Rendering.SetColor(Color4.White); } Textures.White.Bind(); Rendering.SetMinimumLight(1); TheRegion.RenderEffects(); Textures.GetTexture("effects/beam").Bind(); // TODO: Store for (int i = 0; i < TheRegion.Joints.Count; i++) { if (TheRegion.Joints[i] is ConnectorBeam) { switch (((ConnectorBeam)TheRegion.Joints[i]).type) { case BeamType.STRAIGHT: { Location one = TheRegion.Joints[i].One.GetPosition(); if (TheRegion.Joints[i].One is CharacterEntity) { one = ((CharacterEntity)TheRegion.Joints[i].One).GetEyePosition() + new Location(0, 0, -0.3); } Location two = TheRegion.Joints[i].Two.GetPosition(); Vector4 col = Rendering.AdaptColor(ClientUtilities.ConvertD((one + two) * 0.5), ((ConnectorBeam)TheRegion.Joints[i]).color); Rendering.SetColor(col); Rendering.RenderLine(one, two); } break; case BeamType.CURVE: { Location one = TheRegion.Joints[i].One.GetPosition(); Location two = TheRegion.Joints[i].Two.GetPosition(); Location cPoint = (one + two) * 0.5f; if (TheRegion.Joints[i].One is CharacterEntity) { one = ((CharacterEntity)TheRegion.Joints[i].One).GetEyePosition() + new Location(0, 0, -0.3); cPoint = one + ((CharacterEntity)TheRegion.Joints[i].One).ForwardVector() * (two - one).Length(); } DrawCurve(one, two, cPoint, ((ConnectorBeam)TheRegion.Joints[i]).color); } break; case BeamType.MULTICURVE: { Location one = TheRegion.Joints[i].One.GetPosition(); Location two = TheRegion.Joints[i].Two.GetPosition(); double forlen = 1; Location forw = Location.UnitZ; if (TheRegion.Joints[i].One is CharacterEntity) { one = ((CharacterEntity)TheRegion.Joints[i].One).GetEyePosition() + new Location(0, 0, -0.3); forlen = (two - one).Length(); forw = ((CharacterEntity)TheRegion.Joints[i].One).ForwardVector(); } Location spos = one + forw * forlen; const int curves = 5; BEPUutilities.Vector3 bvec = new BEPUutilities.Vector3(0, 0, 1); BEPUutilities.Vector3 bvec2 = new BEPUutilities.Vector3(1, 0, 0); BEPUutilities.Quaternion bquat; BEPUutilities.Quaternion.GetQuaternionBetweenNormalizedVectors(ref bvec2, ref bvec, out bquat); BEPUutilities.Vector3 forwvec = forw.ToBVector(); GL.LineWidth(6); DrawCurve(one, two, spos, ((ConnectorBeam)TheRegion.Joints[i]).color); for (int c = 0; c < curves; c++) { double tang = TheRegion.GlobalTickTimeLocal + Math.PI * 2.0 * ((double)c / (double)curves); BEPUutilities.Vector3 res = BEPUutilities.Quaternion.Transform(forw.ToBVector(), bquat); BEPUutilities.Quaternion quat = BEPUutilities.Quaternion.CreateFromAxisAngle(forwvec, (float)(tang % (Math.PI * 2.0))); res = BEPUutilities.Quaternion.Transform(res, quat); res = res * (float)(0.1 * forlen); DrawCurve(one, two, spos + new Location(res), ((ConnectorBeam)TheRegion.Joints[i]).color); } } break; } } } Rendering.SetColor(Color4.White); Rendering.SetMinimumLight(0); Textures.White.Bind(); if (!view.ShadowsOnly) { GL.ActiveTexture(TextureUnit.Texture1); GL.BindTexture(TextureTarget.Texture2D, 0); GL.ActiveTexture(TextureUnit.Texture0); Render2D(true); } }
/// <summary> /// Create new StaticCollider from existing collision data<para/> /// Создание нового коллайдера из существующих данных /// </summary> /// <param name="colmesh">Collision data<para/>Данные о коллизиях</param> public StaticCollider(CollisionFile.Group colmesh, Vector3 position, Quaternion angles, Vector3 scale) { // Create base transformation matrix // Создание базовой матрицы трансформации Matrix4 mat = Matrix4.CreateScale(scale) * Matrix4.CreateFromQuaternion(angles) * Matrix4.CreateTranslation(position); // Create bodies // Создание тел List<CollisionEntry> col = new List<CollisionEntry>(); // Spheres // Сферы if (colmesh.Spheres!=null) { foreach (CollisionFile.Sphere s in colmesh.Spheres) { // Transforming positions to world coordinates // Трансформация расположения в мировые координаты Vector3 pos = Vector3.TransformPosition(s.Center, mat); float radius = Vector3.TransformVector(Vector3.UnitX * s.Radius, mat).Length; // Create primitive // Создание примитива EntityShape shape = new SphereShape(radius); col.Add(new CollisionEntry() { Type = PrimitiveType.Sphere, Position = pos, Rotation = Quaternion.Identity, Shape = shape, Body = new Entity(shape) }); } } // Cubes // Кубы if (colmesh.Boxes!=null) { foreach (CollisionFile.Box b in colmesh.Boxes) { // Transforming positions to world coordinates // Трансформация расположения в мировые координаты Vector3 pos = Vector3.TransformPosition( new Vector3( (b.Min.X+b.Max.X)/2f, (b.Min.Y+b.Max.Y)/2f, (b.Min.Z+b.Max.Z)/2f ) , mat); float factor = Vector3.TransformVector(Vector3.UnitX, mat).Length; // Create primitive // Создание примитива EntityShape shape = new BoxShape( (float)Math.Abs(b.Max.X-b.Min.X) * factor, (float)Math.Abs(b.Max.Y-b.Min.Y) * factor, (float)Math.Abs(b.Max.Z-b.Min.Z) * factor ); col.Add(new CollisionEntry() { Type = PrimitiveType.Box, Position = pos, Rotation = angles, Shape = shape, Body = new Entity(shape) }); } } // Trimeshes // Тримеши if (colmesh.Meshes!=null) { // Creating vertices array // Создание массива вершин BEPUutilities.Vector3[] verts = new BEPUutilities.Vector3[colmesh.Vertices.Length]; for (int i = 0; i < colmesh.Vertices.Length; i++) { verts[i] = new BEPUutilities.Vector3( colmesh.Vertices[i].X, colmesh.Vertices[i].Y, colmesh.Vertices[i].Z ); } foreach (CollisionFile.Trimesh m in colmesh.Meshes) { // Creating affine transformation // Создание трансформации BEPUutilities.AffineTransform transform = new BEPUutilities.AffineTransform( new BEPUutilities.Vector3(scale.X, scale.Y, scale.Z), new BEPUutilities.Quaternion(angles.X, angles.Y, angles.Z, angles.W), new BEPUutilities.Vector3(position.X, position.Y, position.Z) ); // Create primitive // Создание примитива col.Add(new CollisionEntry() { Type = PrimitiveType.Mesh, Mesh = new StaticMesh(verts, m.Indices, transform) }); } } subColliders = col.ToArray(); }