public void CreateVehicle(Vector3D pUpDir, CBody pNewtonBody) { m_Handle = Newton.NewtonConstraintCreateVehicle(m_World.Handle, new NewtonVector3(pUpDir).NWVector3, pNewtonBody.Handle); CHashTables.Joint.Add(m_Handle, this); }
CPinnedParticles _oPinnedParticles; // Special component in charge of 'pinning' through Flex springs some of the Flex particles in this softbody to their appropriate position on the body's surface #endregion Fields #region Methods //--------------------------------------------------------------------------- INIT public static CSoftBody Create(CBody oBody, Type oTypeBMesh, string sNameBoneAnchor_HACK) { string sNameSoftBody = oTypeBMesh.Name.Substring(1); // Obtain the name of our detached body part ('Breasts', 'Penis', 'V****a') from a substring of our class name. Must match Blender!! ###WEAK? _sNameBoneAnchor_HACK = sNameBoneAnchor_HACK; CGame.gBL_SendCmd("CBody", "CBodyBase_GetBodyBase(" + oBody._oBodyBase._nBodyID.ToString() + ").oBody.CreateSoftBody('" + sNameSoftBody + "', " + CGame.INSTANCE.nSoftBodyFlexColliderShrinkRatio.ToString() + ")"); // Separate the softbody from the source body. CSoftBody oSoftBody = (CSoftBody)CBMesh.Create(null, oBody._oBodyBase, ".oBody.aSoftBodies['" + sNameSoftBody + "'].oMeshSoftBody", oTypeBMesh); // Create the softbody mesh from the just-created Blender mesh. return oSoftBody; }
public static void WriteEntity(this NetBuffer message, int id, CBody cbody, CTransform ctransform, string modelname, bool isPlayer) { message.Write(id); message.Write(isPlayer); message.WriteCBody(cbody); message.WriteCTransform(ctransform); message.Write(modelname); }
public static int ReadEntityLight(this NetBuffer message, ref CBody cBody, ref CTransform ctransform, ref string modelname, ref bool isPlayer) { int id = message.ReadInt32(); cBody.Velocity = message.ReadVector3(); ctransform.Position = message.ReadVector3(); ctransform.Rotation = message.ReadMatrix(); return(id); }
public static int ReadEntity(this NetBuffer message, ref CBody cBody, ref CTransform ctransform, ref string modelname, ref bool isPlayer) { int id = message.ReadInt32(); isPlayer = message.ReadBoolean(); cBody = ReadCBody(message); ctransform = ReadCTransform(message); modelname = message.ReadString(); return(id); }
public CClothEdit(CBody oBody, string sClothType) { _oBody = oBody; _sClothType = sClothType; // CBody.CBody._aBodies[0].CreateCloth("BodySuit", "_ClothSkinnedArea_Top", "Shirt") ###One of teh body suits? string sCmd = _oBody._oBodyBase._sBlenderInstancePath_CBodyBase + ".CreateCloth('BodySuit', '_ClothSkinnedArea_Top', '" + _sClothType + "')"; //###DESIGN: Pass in all args from Unity? Blender determines? CGame.gBL_SendCmd("CBody", sCmd); _sBlenderInstancePath_CClothEdit = "aCloths['" + _sClothType + "']"; _oClothSource = CBMesh.Create(null, _oBody._oBodyBase, _sBlenderInstancePath_CClothEdit + ".oMeshClothSource", typeof(CBMesh)); }
public void TryToJump() { if (!InVehicle && Upward && !IsFlying && !pup && CBody.SupportFinder.HasSupport) { CBody.Jump(); pup = true; } else if (!Upward) { pup = false; } }
public static ConvexBody3D GetConvexBodyFromUserData(CBody body) { if (body.UserData is ConvexBody3D) { return((ConvexBody3D)body.UserData); } else if (body.UserData is IMapObject) { return((ConvexBody3D)((IMapObject)body.UserData).PhysicsBody); } return(null); }
public static Body GetBodyFromUserData(CBody body) { if (body.UserData is Body) { return((Body)body.UserData); } else if (body.UserData is IMapObject) { return((Body)((IMapObject)body.UserData).PhysicsBody); } return(null); }
public static void WriteCBody(this NetBuffer message, CBody cbody) { message.Write(cbody.Radius); message.Write(cbody.InvMass); message.Write(cbody.LinDrag); message.Write(cbody.Restitution); message.Write(cbody.SpeedMultiplier); message.Write(cbody.RotationMultiplier); message.Write(cbody.Velocity); message.Write(cbody.MaxVelocity); message.Write(cbody.EnableRot); message.WriteRotation(cbody.Rot, 8); message.Write(cbody.RotAx); message.Write(cbody.RotVel); }
public void CreateUserBilateral(int pMaxDOF, EventHandler <CUserBilateralEventArgs> pCallback, CBody pChildBody, CBody pParentBody) { m_UserBilateral = pCallback; m_NewtonUserBilateral = new Newton.NewtonUserBilateral(InvokeUserBilateral); m_Handle = Newton.NewtonConstraintCreateUserJoint(m_World.Handle, pMaxDOF, m_NewtonUserBilateral, pChildBody.Handle, pParentBody.Handle); CHashTables.Joint.Add(m_Handle, this); }
public static CBody ReadCBody(this NetBuffer message) { CBody retval = new CBody(); retval.Radius = message.ReadFloat(); retval.InvMass = message.ReadFloat(); retval.LinDrag = message.ReadFloat(); retval.Restitution = message.ReadFloat(); retval.SpeedMultiplier = message.ReadFloat(); retval.RotationMultiplier = message.ReadFloat(); retval.Velocity = message.ReadVector3(); retval.MaxVelocity = message.ReadFloat(); retval.EnableRot = message.ReadBoolean(); retval.Rot = message.ReadRotation(8); retval.RotAx = message.ReadVector3(); retval.RotVel = message.ReadFloat(); return(retval); }
protected virtual void Dispose(bool disposing) { if (disposing) { if (_body != null) { _body.Destructor -= _body_Destructor; if (_isInitialised) { _body.Dispose(); _isInitialised = false; } _body = null; } } }
public void Initialise(World world) { if (_isInitialised) { return; } if (world == null) { throw new ArgumentNullException("world"); } _world = world; _collision = OnInitialise(world); if (_collision == null) { _collision = new NullCollision(_world); } _body = new CBody(_collision.NewtonCollision); _body.Destructor += _body_Destructor; _body.AutoFreeze = this.AutoPause; _body.UserData = this; _body.Matrix = _visualMatrix.Matrix; OnInitialiseEnd(); // this might adjust the _body.Matrix property // not initialised yet, nothing should be called on property changed event this.Transform = new MatrixTransform3D(_body.Matrix); _body.SetTransform += body_setTransform; _body.ApplyForceAndTorque += body_ApplyForceAndTorque; CalculateMass(this.Mass); world.AddBody(this); _isInitialised = true; }
CHandTarget _oHandTarget_RaycastPin; // Commonly used hand target used during commonly-used raycast to position hands. #endregion Fields #region Methods //void ConfigFingerRoot(int nFingerID, string sFingerName) { //###OBS? //###WEAK: 3dsMax bone rotation for fingers need massive rework... these ranges kept limited to compensate... FIX MODEL! // CJointDriver oJointFingerBoneParent = _oJointExtremity; // oJointFingerBoneParent = ConfigFingerBone(oJointFingerBoneParent, nFingerID, 0, sFingerName, 020f, -020f, -009f, 000f); // First bone: Can twist about y also // oJointFingerBoneParent = ConfigFingerBone(oJointFingerBoneParent, nFingerID, 1, sFingerName, 010f, -020f, 000f, 000f); // Second bone: Only X // oJointFingerBoneParent = ConfigFingerBone(oJointFingerBoneParent, nFingerID, 2, sFingerName, 010f, -020f, 000f, 000f); // Third bone: Only X (more limited) //###CHECK: Joint free vs fixed affecting these?? //} //CJointDriver ConfigFingerBone(CJointDriver oJointFingerBoneParent, int nFingerID, int nFingerBoneID, string sFingerName, float XL, float XH, float YR, float ZR) { //###OBS? // CJointDriver oJointDrv = CJointDriver.Create(this, oJointFingerBoneParent, _sSidePrefixL+sFingerName + (nFingerBoneID+1).ToString(), 1.0f, 0.01f, XL, XH, -YR, YR, -ZR, ZR); //###TODO: Calibrate different fingers specially! // _aJoints.Add(oJointDrv); // JointDrive oDrive = oJointDrv._oConfJoint.slerpDrive; // oDrive.positionSpring = 1; //###TUNE // oDrive.positionDamper = 0;// .001f; //***NOW! // oJointDrv._oConfJoint.slerpDrive = oDrive; // oJointDrv._oRigidBody.mass = 0.0001f; //###TODO! // oJointDrv._oRigidBody.drag = 0; // Remove all damping so finger joint gets the least stress as possible to avoid 'disjointed rubber fingers' // oJointDrv._oRigidBody.angularDrag = 0; // CapsuleCollider oCollCap = (CapsuleCollider)CUtility.FindOrCreateComponent(oJointDrv._oTransform.gameObject, typeof(CapsuleCollider)); // oCollCap.direction = 2; // z = 2 as per docs at http://docs.unity3d.com/Documentation/ScriptReference/CapsuleCollider-direction.html // oCollCap.radius = 0.011f; // oCollCap.height = 0.04f; // _aaFingers[nFingerID, nFingerBoneID] = oJointDrv; // return oJointDrv; //} public static CHandTarget FindHandTarget(CBody oBody, EHandTargets eHandTarget, bool bRightSideOfBody) { //string sNameHandTarget = "CHandTarget-" + eHandTarget.ToString(); // The enum name of hand target is prefixed by 'CHandTarget-' in the bone tree //Transform oHandTargetT = oBody.SearchBone(oBody._oBonesT, sNameHandTarget); //CHandTarget oHandTarget = oHandTargetT.GetComponent<CHandTarget>(); //if (bRightSideOfBody) // The right side of body has 'create as needed' hand targets that are mirrored from the left side... // oHandTarget = CHandTarget.FindOrCreateRightSideHandTarget(oHandTarget); //return oHandTarget; return null; //###BROKEN }
public CBody GetBodyOther(CBody oBody) { // Returns the other body. Assumes only a 2-body scene. return null; //###BROKEN#11 //if (oBody == _aBodyBases[0]) //###DESIGN: Revisit this once we fix assumptions as to bodies in body 0/1 // return _aBodyBases[1]; //else // return _aBodyBases[0]; }
public void AddLookTargetsToOtherBody(CBody oBodyOther) { // Send by CGamePlay when scene gets a body added / removed //###IMPROVE: Have a special 'object of interest' object that overrides... such as end of penis when cumming _aLookTargets.Clear(); _aLookTargets.Add(Camera.main.transform); // We always add the camera //###DESIGN??? if (oBodyOther != null) { //###IMPROVE?? Add parts of self body to look at like penis tip? _aLookTargets.Add(oBodyOther._oBodyBase.FindBone("chest/neck/head")); _aLookTargets.Add(oBodyOther._oBodyBase.FindBone("chest/abdomen")); _aLookTargets.Add(oBodyOther._oBodyBase.FindBone("chest/abdomen/hip")); _aLookTargets.Add(oBodyOther._oBodyBase.FindBone("chest/abdomen/hip/sex")); //_aLookTargets.Add(oBodyOther.FindBone("chest/lCollar/lShldr/lForeArm/lHand")); //###DESIGN??? //_aLookTargets.Add(oBodyOther.FindBone("chest/rCollar/rShldr/rForeArm/rHand")); } _nTimeNextChangeLookTarget = -1; // Force an immediate refresh of node to look at }
//--------------------------------------------------------------------------- ARM RAYCAST PINNING: User selecting where to place the closest arm of the selected body on a body surface through raycasting public void ArmRaycastPin_Begin() { _oHandTarget = _oHandTarget_RaycastPin; _oHandTarget.ConnectHandToHandTarget(this); _oHandTarget.transform.position = _oJointExtremity.transform.position; // Manually set the hand target position to the hand position so slerp in Update doesn't start from some old stale position ###MOVE? _oBodyArmPin = null; //_nArmPinBodyColVert = -1; //_nTimeStartPinSet = 0; // Reset our start-of-slerp time to zero so it's initialize at first real pin position //_bPinByClosestVert = false; // We start pinning by ray position as it's much more accurate. When user releases pinning key we go to vert pinning which will handle changes in body orientation ###IMPROVE: Always have 'ray precision' pinning by storing offset and rotating to closest vert normal? _oConfJoint_Extremity.angularXMotion = _oConfJoint_Extremity.angularYMotion = _oConfJoint_Extremity.angularZMotion = ConfigurableJointMotion.Free; // We free rotation constraint so hand is just attraced by position (and repelled by colliders) Greatly simplifies hand raycasting!! }
private CChild Child(Entity mParent, CBody mCBody) { return(new CChild(mParent, mCBody)); }
private CAI AI(CStats mCStats, CBody mCBody, CMovement mCMovement, CRender mCRender, CLineOfSight mCLineOfSight) { return(new CAI(_game, mCStats, mCBody, mCMovement, mCRender, mCLineOfSight)); }
private CMovement Movement(CBody mCBody) { return(new CMovement(mCBody)); }
public override void Update(float t, float dt) { KeyboardState currentState = Keyboard.GetState(); Keys[] pressedKeys = currentState.GetPressedKeys(); yaw = 0; foreach (var input in Game1.Inst.Scene.GetComponents <CInput>()) { CBody body = null; if (Game1.Inst.Scene.EntityHasComponent <CBody>(input.Key)) { body = (CBody)Game1.Inst.Scene.GetComponentFromEntity <CBody>(input.Key); } var transform = (CTransform)Game1.Inst.Scene.GetComponentFromEntity <CTransform>(input.Key); var inputValue = (CInput)input.Value; //For Network Chat foreach (Keys key in pressedKeys) { if (lastPressedKeys != null && !lastPressedKeys.Contains(key)) { Game1.Inst.RaiseInScene("key_to_write", key); } } lastPressedKeys = pressedKeys; if (!Game1.Inst.Scene.EntityHasComponent <CBody>(input.Key)) { continue; } if (currentState.IsKeyDown(Keys.Escape)) { Game1.Inst.Exit(); // TODO: We Should leave the scene } var movementSpeed = dt * 100f * body.SpeedMultiplier; var rotationSpeed = dt * 2.4f * body.RotationMultiplier; Vector3 acceleration = Vector3.Zero; if (currentState.IsKeyDown(Keys.LeftShift)) { movementSpeed *= 0.4f; } if (currentState.IsKeyDown(inputValue.ForwardMovementKey)) { var w = transform.Frame.Forward; if (!isInAir && isOnGround) { var tx = transform.Position.X; var tz = transform.Position.Z; var fv1 = w; fv1.Normalize(); var fv2 = fv1; fv2 *= 0.05f; // Compute height delta. var y1 = Heightmap.HeightAt(tx, tz); var y2 = Heightmap.HeightAt(tx + fv2.X, tz + fv2.Z); fv2.Y = (float)Math.Max(0.0f, y2 - y1); fv2.Normalize(); var maxAngle = (float)Math.Cos(MathHelper.ToRadians(70.0f)); var fac = (float)Math.Max(0.0f, Vector3.Dot(fv1, fv2) - maxAngle); movementSpeed *= fac; } acceleration += movementSpeed * w; } if (currentState.IsKeyDown(inputValue.BackwardMovementKey)) { var w = transform.Frame.Backward; if (!isInAir && isOnGround) { var tx = transform.Position.X; var tz = transform.Position.Z; var fv1 = w; fv1.Normalize(); var fv2 = fv1; fv2 *= 0.05f; // Compute height delta. var y1 = Heightmap.HeightAt(tx, tz); var y2 = Heightmap.HeightAt(tx + fv2.X, tz + fv2.Z); fv2.Y = (float)Math.Max(0.0f, y2 - y1); fv2.Normalize(); var maxAngle = (float)Math.Cos(MathHelper.ToRadians(70.0f)); var fac = (float)Math.Max(0.0f, Vector3.Dot(fv1, fv2) - maxAngle); movementSpeed *= fac; } acceleration += movementSpeed * w; } acceleration.Y = 0.0f; body.Velocity += acceleration - dt * body.Velocity * 10.0f * new Vector3(1.0f, 0.0f, 1.0f); //if (acceleration.X + body.Velocity.X < body.MaxVelocity && acceleration.X + body.Velocity.X > -body.MaxVelocity) ///body.Velocity.X += acceleration.X; //if (acceleration.Y + body.Velocity.Y < body.MaxVelocity || acceleration.Y + body.Velocity.Y > -body.MaxVelocity) // body.Velocity.Y += acceleration.Y; //if (acceleration.Z + body.Velocity.Z < body.MaxVelocity && acceleration.Z + body.Velocity.Z > -body.MaxVelocity) //body.Velocity.Z += acceleration.Z; if (currentState.IsKeyDown(inputValue.LeftMovementKey)) { yaw = rotationSpeed; } if (currentState.IsKeyDown(inputValue.RightMovementKey)) { yaw = -rotationSpeed; } if (currentState.IsKeyDown(Keys.K) && !prevState.IsKeyDown(Keys.K)) { if (Game1.Inst.Scene.EntityHasComponent <CPlayer>(input.Key)) { var cp = (CPlayer)Game1.Inst.Scene.GetComponentFromEntity <CPlayer>(input.Key); var p = (CHit)Game1.Inst.Scene.GetComponentFromEntity <CHit>(cp.HitId); if (!p.IsAttacking) { SfxUtil.PlaySound("Sounds/Effects/Swing", vol: 1, randomPitch: true); Game1.Inst.Scene.Raise("attack", new HitSystem.HitInfo { EntityID = input.Key, IsAttacking = true, StartTime = t }); } } } if (currentState.IsKeyDown(Keys.Space) && !prevState.IsKeyDown(Keys.Space) && !isInAir) { body.Velocity.Y += 11f; if (transform.Position.Y > WaterY) { isInAir = true; } SfxUtil.PlaySound("Sounds/Effects/jump_start", vol: 1, randomPitch: true); var model = (CImportedModel)Game1.Inst.Scene.GetComponentFromEntity <C3DRenderable>(input.Key); model.animFn = SceneUtils.playerAnimation(input.Key, 12, 0.01f); } if (currentState.IsKeyDown(Keys.H) && !prevState.IsKeyDown(Keys.H)) { if (Game1.Inst.Scene.GetType() == typeof(WorldScene)) { var scene = (WorldScene)Game1.Inst.Scene; var list = Game1.Inst.Scene.GetComponents <CPickUp>(); var inv = (CInventory)Game1.Inst.Scene.GetComponentFromEntity <CInventory>(input.Key); foreach (var ball in list) { var ballBody = (CBody)Game1.Inst.Scene.GetComponentFromEntity <CBody>(ball.Key); if (body.ReachableArea.Intersects(ballBody.Aabb) && !inv.isFull) { var b = new CInventoryItem(ballBody); inv.items.Add(b); inv.IdsToRemove.Add(ball.Key); prevState = currentState; // Return so only one item will be picked up. return; } } } } if (currentState.IsKeyDown(Keys.J) && !prevState.IsKeyDown(Keys.J)) { if (Game1.Inst.Scene.EntityHasComponent <CInventory>(input.Key)) { var inv = (CInventory)Game1.Inst.Scene.GetComponentFromEntity <CInventory>(input.Key); if (inv.items.Count > 0) { var item = inv.items.ElementAt(inv.items.Count - 1); var ts = dt * 100f * item.itemBody.SpeedMultiplier; var newItem = item; newItem.itemBody.Velocity += /*transform.Rotation.Forward */new Vector3(item.itemBody.Aabb.Max.X * 2 + .5f, 0f, item.itemBody.Aabb.Max.Z * 2 + .5f) * ts; inv.items.Remove(item); inv.itemsToRemove.Add(newItem); } } } prevState = currentState; addRot = Matrix.CreateFromYawPitchRoll(yaw, pitch, roll); transform.Heading += yaw; transform.Rotation *= addRot; } }
/// <summary>Checks for and solves collisions against the world bounds.</summary> /// <param name="eid">The ID of the entity to check.</param> /// <param name="body">The body component of the entity to check.</param> /// <param name="transf">The transform component of the entity to check.</param> /// <param name="aabb">The axis-aligned bounding box component of the entity to check.</param> private void CheckBodyWorld(int eid, CBody body, CTransform transf, BoundingBox aabb) { // This function is pretty trivial, so we can solve the collision immediately - no need to // store it for solving during the fine-solver phase. Basically, just check the bounding box // against the world bounds and bounce against them with full restitution. In practice, this // method should only be used to prevent objects from leaving universe to prevent // hard-to-detect errors in the physical simulation. Don't use it for in-game mechanics. if (aabb.Min.X < Bounds.Min.X) { transf.Position.X = Bounds.Min.X - body.Aabb.Min.X; body.Velocity.X *= -body.Restitution; } else if (aabb.Max.X > Bounds.Max.X) { transf.Position.X = Bounds.Max.X - body.Aabb.Max.X; body.Velocity.X *= -body.Restitution; } if (aabb.Min.Y < Bounds.Min.Y) { transf.Position.Y = Bounds.Min.Y - body.Aabb.Min.Y; body.Velocity.Y *= -body.Restitution; } else if (aabb.Max.Y > Bounds.Max.Y) { transf.Position.Y = Bounds.Max.Y - body.Aabb.Max.Y; body.Velocity.Y *= -body.Restitution; } if (aabb.Min.Z < Bounds.Min.Z) { transf.Position.Z = Bounds.Min.Z - body.Aabb.Min.Z; body.Velocity.Z *= -body.Restitution; } else if (aabb.Max.Z > Bounds.Max.Z) { transf.Position.Z = Bounds.Max.Z - body.Aabb.Max.Z; body.Velocity.Z *= -body.Restitution; } // If we have a map system, check that we don't fall below the ground. This part is part of // game mechanics. if (Heightmap != null) { //sometimes nan Values?? if (double.IsNaN(transf.Position.X)) { return; } var mapHeight = Heightmap.HeightAt(transf.Position.X, transf.Position.Z); if (aabb.Min.Y < mapHeight) { transf.Position.Y = mapHeight - body.Aabb.Min.Y; body.Velocity.Y *= -body.Restitution; Scene.Raise("collisionwithground", new CollisionInfo { Entity1 = eid }); } } }
private CRender Render(CBody mCBody, string mTextureName, string mTilesetName = null, string mLabelName = null, float mRotation = 0) { return(new CRender(_game, mCBody, mTextureName, mTilesetName, mLabelName, mRotation)); }
public void OnStart(CBody oBody) { _oBody = oBody; //###MOD: Init segment from code as our component is added at runtime now BendingSegment oSeg = new BendingSegment(); oSeg.firstTransform = _oBody._oBodyBase.FindBone("chest/neck"); //###IMPROVE? Can spine be added (or would interfere with our anim too much?) oSeg.lastTransform = _oBody._oBodyBase.FindBone("chest/neck/head"); oSeg.thresholdAngleDifference = 0; //###??? oSeg.bendingMultiplier = 1.0f; //###IMPROVE!!!: Add 'eyes' and get them to move part of the way oSeg.maxAngleDifference = 90; oSeg.maxBendingAngle = 40; //###IMPROVE: Reduce angle for head up / down and wider for head left/right oSeg.responsiveness = 3.0f; //###TUNE!!! segments[0] = oSeg; if (rootNode == null) rootNode = transform; // Setup segments foreach (BendingSegment segment in segments) { Quaternion parentRot = segment.firstTransform.parent.rotation; Quaternion parentRotInv = Quaternion.Inverse(parentRot); segment.referenceLookDir = parentRotInv * rootNode.rotation * headLookVector.normalized; segment.referenceUpDir = parentRotInv * rootNode.rotation * headUpVector.normalized; segment.angleH = 0; segment.angleV = 0; segment.dirUp = segment.referenceUpDir; segment.chainLength = 1; Transform t = segment.lastTransform; while (t != segment.firstTransform && t != t.root) { segment.chainLength++; t = t.parent; } segment.origRotations = new Quaternion[segment.chainLength]; t = segment.lastTransform; for (int i=segment.chainLength - 1; i >= 0; i--) { segment.origRotations[i] = t.localRotation; t = t.parent; } } }
/// <summary> Message loop to check type of message and handle it accordingly </summary> public void MessageLoop() { while ((_msg = _peer.ReadMessage()) != null) { s_bpsBytes += _msg.LengthBytes; switch (_msg.MessageType) { case NetIncomingMessageType.DiscoveryRequest: //Debug.WriteLine("ReceivePeersData DiscoveryRequest"); _peer.SendDiscoveryResponse(null, _msg.SenderEndPoint); break; case NetIncomingMessageType.DiscoveryResponse: // just connect to first server discovered //Debug.WriteLine("ReceivePeersData DiscoveryResponse CONNECT"); if (_peer.Connections.Any(x => x.RemoteEndPoint.Address.Equals(_msg.SenderEndPoint.Address))) { Debug.WriteLine("allreadyConnected"); } else { _peer.Connect(_msg.SenderEndPoint); } break; case NetIncomingMessageType.ConnectionApproval: //Debug.WriteLine("ReceivePeersData ConnectionApproval"); _msg.SenderConnection.Approve(); //broadcast this to all connected clients SendPeerInfo(_msg.SenderEndPoint.Address, _msg.SenderEndPoint.Port); break; case NetIncomingMessageType.Data: //another client sent us data //Read TypeData First Enums.MessageType mType = (Enums.MessageType)_msg.ReadByte(); if (mType == Enums.MessageType.String) { var metadata = _msg.ReadString(); if (metadata == "StartEvent") { var map = _msg.ReadString(); _isMaster = false; MasterNetConnection = _peer.Connections.FirstOrDefault(x => x.RemoteEndPoint.Address.ToString() == _msg.SenderEndPoint.Address.ToString()); Game1.Inst.Scene.Raise("startgame", map); } else if (metadata == "metadata") { Game1.Inst.Scene.Raise("network_data_text", _msg.ReadString()); } } else if (mType == Enums.MessageType.PeerInformation) { int byteLenth = _msg.ReadInt32(); byte[] addressBytes = _msg.ReadBytes(byteLenth); IPAddress ip = new IPAddress(addressBytes); int port = _msg.ReadInt32(); //connect IPEndPoint endPoint = new IPEndPoint(ip, port); Debug.WriteLine("Data::PeerInfo::Detecting if we're connected"); if (_peer.GetConnection(endPoint) == null) { //are we already connected? //Don't try to connect to ourself! if (_peer.Configuration.LocalAddress.GetHashCode() != endPoint.Address.GetHashCode() || _peer.Configuration.Port.GetHashCode() != endPoint.Port.GetHashCode()) { Debug.WriteLine(string.Format("Data::PeerInfo::Initiate new connection to: {0}:{1}", endPoint.Address.ToString(), endPoint.Port.ToString())); _peer.Connect(endPoint); } } } else if (mType == Enums.MessageType.Entity || mType == Enums.MessageType.EntityLight) { var cbody = new CBody(); var ctransform = new CTransform(); string modelname = ""; bool isPlayer = false; int id = 0; id = mType == Enums.MessageType.EntityLight ? _msg.ReadEntityLight(ref cbody, ref ctransform, ref modelname, ref isPlayer) : _msg.ReadEntity(ref cbody, ref ctransform, ref modelname, ref isPlayer); Game1.Inst.Scene.Raise("entityupdate", new EntitySync { ID = id, CBody = cbody, CTransform = ctransform, ModelFileName = modelname, IsPlayer = isPlayer }); } else if (mType == Enums.MessageType.CTransform) { var metadata = _msg.ReadString(); var data = _msg.ReadCTransform(); //Game1.Inst.Scene.Raise("network_data", data); } else if (mType == Enums.MessageType.Vector3) { var metadata = _msg.ReadString(); var data = _msg.ReadCTransform(); //Game1.Inst.Scene.Raise("network_data", data); } else if (mType == Enums.MessageType.CText) { var id = _msg.ReadInt32(); var data = _msg.ReadCText(); Game1.Inst.Scene.Raise("network_menu_data_received", new MenuItem { CText = data, Id = id }); } else if (mType == Enums.MessageType.Int32) { var metadata = _msg.ReadString(); var data = _msg.ReadInt32(); if (metadata == "network_game_end") { Game1.Inst.Scene.Raise("game_end", data); } } else if (mType == Enums.MessageType.PlayerInfo) { var date = _msg.ReadInt64(); if (!players.Any(x => x.IP == _msg.SenderEndPoint.Address.ToString() + " " + _msg.SenderEndPoint.Port.ToString())) { players.Add(new NetworkPlayer { IP = _msg.SenderEndPoint.Address.ToString() + " " + _msg.SenderEndPoint.Port.ToString(), Time = new DateTime(date), You = false }); Game1.Inst.Scene.Raise("update_peers", players.OrderBy(x => x.Time).ToList()); } } //Console.WriteLine("END ReceivePeersData Data"); break; case NetIncomingMessageType.UnconnectedData: Debug.WriteLine("UnconnectedData: " + _msg.ReadString()); break; case NetIncomingMessageType.VerboseDebugMessage: Debug.WriteLine(NetIncomingMessageType.VerboseDebugMessage + " " + _msg.ReadString()); break; case NetIncomingMessageType.DebugMessage: Debug.WriteLine(NetIncomingMessageType.DebugMessage + " " + _msg.ReadString()); break; case NetIncomingMessageType.WarningMessage: Debug.WriteLine(NetIncomingMessageType.WarningMessage + " " + _msg.ReadString()); break; case NetIncomingMessageType.ErrorMessage: Debug.WriteLine(NetIncomingMessageType.ErrorMessage + " " + _msg.ReadString()); break; default: Debug.WriteLine("ReceivePeersData Unknown type: " + _msg.MessageType.ToString()); try { Debug.WriteLine(_msg.SenderConnection); if (_msg.SenderConnection.Status == NetConnectionStatus.Disconnected) { //Maybe try to reconnect } Debug.WriteLine(_msg.ReadString()); } catch { Debug.WriteLine("Couldn't parse unknown to string."); } break; } } }
//--------------------------------------------------------------------------- CREATE / DESTROY public virtual void OnStart(CBody oBody) { _oBody = oBody; _eBodySide = gameObject.name.EndsWith("R") ? EBodySide.Right : EBodySide.Left; // Extract what side we are from our node name (e.g. ArmL, LegR, etc) _sSidePrefixL = (_eBodySide == 0) ? "l" : "r"; _sSidePrefixU = _sSidePrefixL.ToUpper(); _oConfJoint_Extremity = GetComponent<ConfigurableJoint>(); GetComponent<Renderer>().enabled = false; // Hidden by default. CGame shows/hides us with call to OnBroadcast_HideOrShowHelperObjects OnStart_DefineLimb(); _oObj.PropSet(EActorNode.Pinned, 1); //###NOW### Pin by default?? SetActorPosToBonePos(); //###CHECK }
List<int> aShapeVerts = new List<int>(); // Array of which vert / particle is also a shape #endregion Fields #region Methods public static CFlexSkin_OBS Create(CBody oBody, string sNameFlexSkin) { // Static function override from CBMesh::Create() to route to proper Blender request command string sBodyID = "CBodyBase_GetBodyBase(" + oBody._oBodyBase._nBodyID.ToString() + ")."; CFlexSkin_OBS.s_sNameFlexSkin_HACK = "aFlexSkins['" + sNameFlexSkin + "']"; string sBlenderInstancePath = CFlexSkin_OBS.s_sNameFlexSkin_HACK + ".oMeshFlexSkin"; CGame.gBL_SendCmd("CBody", sBodyID + "CreateFlexSkin('" + sNameFlexSkin + "')"); // Create the Blender-side CCloth entity to service our requests CFlexSkin_OBS oFlexSkin = (CFlexSkin_OBS)CBMesh.Create(null, oBody._oBodyBase, sBlenderInstancePath, typeof(CFlexSkin_OBS)); return oFlexSkin; }
private CControl Control(CBody mCBody, CStats mCStats, CMovement mCMovement, CRender mCRender) { return(new CControl(_game, mCStats, mCBody, mCMovement, mCRender)); }
private void _body_Destructor(object sender, CBodyDestructorEventArgs e) { _body.Destructor -= _body_Destructor; _body = null; }
public void OnChangeBodyMode(EBodyBaseModes eBodyBaseMode) { if (_eBodyBaseMode == eBodyBaseMode) return; Debug.LogFormat("MODE: Body#{0} going from '{1}' to '{2}'", _nBodyID.ToString(), _eBodyBaseMode.ToString(), eBodyBaseMode.ToString()); //=== Perform special processing when going from configure to play to update the morph mesh in Blender === if (_eBodyBaseMode == EBodyBaseModes.Configure && eBodyBaseMode == EBodyBaseModes.Play) { //###HACK#14: Better way to do mode changes??? //=== Going from configure to play mode. Destroy all configure-time Flex objects for performance. They will have to be re-created upon re-entry into configure mode === FlexObjects_Destroy(); //=== Send Blender all the sliders values so it updates its morphing body for game-time body generation === foreach (CProp oProp in _oObj._aProps) // Manually dump all our Blender properties into Blender so UpdateMorphResultMesh() has the user's morph sliders. (We don't update at every slider value change for performance) oProp._nValueLocal = float.Parse(CGame.gBL_SendCmd("CBody", _oObj._sBlenderAccessString + ".PropSetString('" + oProp._sNameProp + "'," + oProp._nValueLocal.ToString() + ")")); //=== Ask Blender to update its morphing body from user-selected slider choices === CGame.gBL_SendCmd("CBody", _sBlenderInstancePath_CBodyBase + ".UpdateMorphResultMesh()"); _oMeshMorphResult.UpdateVertsFromBlenderMesh(true); // Morphing can radically change normals. Recompute them. (Accurate normals needed below anyways for Flex collider) } //=== Set the new game mode === _eBodyBaseMode = eBodyBaseMode; //=== Notify Blender of the switch of body mode. Makes a lot of things happen! === CGame.gBL_SendCmd("CBody", _sBlenderInstancePath_CBodyBase + ".OnChangeBodyMode('" + _eBodyBaseMode.ToString() + "')"); //=== Hide or show the body base components depending on new body mode === bool bShowBodyBase = (_eBodyBaseMode == EBodyBaseModes.Configure); _oMeshMorphResult.GetComponent<MeshRenderer>().enabled = bShowBodyBase; // Hide / show the morphing mesh _oCanvas.gameObject.SetActive(bShowBodyBase); // Hide / show the entire morphing UI //=== Switch body mode === switch (_eBodyBaseMode) { case EBodyBaseModes.Startup: CUtility.ThrowException("CBodyBase.OnChangeBodyMode() cannot go back to Startup mode!"); break; case EBodyBaseModes.Configure: FlexObjects_Create(); // Re-create the Flex objects if (_oBody != null) _oBody = _oBody.DoDestroy(); // Destroys *everthing* related to gametime (softbodies, cloth, flex colliders, etc) on both Unity and Blender side! break; case EBodyBaseModes.Play: if (_oBody == null) // If entering play mode (while having null body), create everything game-play related on Unity & Blender side (huge operation) _oBody = new CBody(this); else _oBody.DoEnable(true); break; case EBodyBaseModes.Disabled: if (_oBody == null) CUtility.ThrowException("CBodyBase.OnChangeBodyMode() went to disabled mode with no _oBody!"); _oBody.DoEnable(false); break; } }
public override void Update(float t, float dt) { KeyboardState currentState = Keyboard.GetState(); if (currentState.IsKeyDown(Keys.Escape)) { Game1.Inst.Exit(); } foreach (var input in Game1.Inst.Scene.GetComponents <CInput>()) { CBody body = null; if (Game1.Inst.Scene.EntityHasComponent <CBody>(input.Key)) { body = (CBody)Game1.Inst.Scene.GetComponentFromEntity <CBody>(input.Key); } var inputValue = (CInput)input.Value; if (Game1.Inst.Scene.EntityHasComponent <CCamera>(input.Key)) { var transform = (CTransform)Game1.Inst.Scene.GetComponentFromEntity <CTransform>(input.Key); CCamera cameraComponent = (CCamera)Game1.Inst.Scene.GetComponentFromEntity <CCamera>(input.Key); if (lastMouseState == null) { lastMouseState = Mouse.GetState(); } if (currentState.IsKeyDown(inputValue.CameraMovementForward)) { transform.Position += CAMERASPEED * new Vector3((float)(cameraComponent.Distance * Math.Sin(cameraComponent.Heading + Math.PI * 0.5f)), 0, (float)((-cameraComponent.Distance) * Math.Cos(cameraComponent.Heading + Math.PI * 0.5f))); cameraComponent.Target += CAMERASPEED * new Vector3((float)(cameraComponent.Distance * Math.Sin(cameraComponent.Heading + Math.PI * 0.5f)), 0, (float)((-cameraComponent.Distance) * Math.Cos(cameraComponent.Heading + Math.PI * 0.5f))); } if (currentState.IsKeyDown(inputValue.CameraMovementBackward)) { transform.Position -= CAMERASPEED * new Vector3((float)(cameraComponent.Distance * Math.Sin(cameraComponent.Heading + Math.PI * 0.5f)), 0, (float)((-cameraComponent.Distance) * Math.Cos(cameraComponent.Heading + Math.PI * 0.5f))); cameraComponent.Target -= CAMERASPEED * new Vector3((float)(cameraComponent.Distance * Math.Sin(cameraComponent.Heading + Math.PI * 0.5f)), 0, (float)((-cameraComponent.Distance) * Math.Cos(cameraComponent.Heading + Math.PI * 0.5f))); } if (Mouse.GetState().X < lastMouseState.X || currentState.IsKeyDown(inputValue.CameraMovementLeft)) { cameraComponent.Heading -= 0.05f; transform.Position = Vector3.Subtract(cameraComponent.Target, new Vector3((float)(cameraComponent.Distance * Math.Sin(cameraComponent.Heading + Math.PI * 0.5f)), cameraComponent.Height, (float)((-cameraComponent.Distance) * Math.Cos(cameraComponent.Heading + Math.PI * 0.5f)))); } if (Mouse.GetState().X > lastMouseState.X || currentState.IsKeyDown(inputValue.CameraMovementRight)) { cameraComponent.Heading += 0.05f; transform.Position = Vector3.Subtract(cameraComponent.Target, new Vector3((float)(cameraComponent.Distance * Math.Sin(cameraComponent.Heading + Math.PI * 0.5f)), cameraComponent.Height, (float)((-cameraComponent.Distance) * Math.Cos(cameraComponent.Heading + Math.PI * 0.5f)))); } lastMouseState = Mouse.GetState(); } if (!Game1.Inst.Scene.EntityHasComponent <CBody>(input.Key)) { continue; } if (_mapSystem != null) { body.Position.Y = _mapSystem.HeightPosition(body.Position.X, body.Position.Z); } if (currentState.IsKeyDown(inputValue.ForwardMovementKey)) { body.Velocity.Z -= 50f * dt; } if (currentState.IsKeyDown(inputValue.BackwardMovementKey)) { body.Velocity.Z += 50f * dt; } if (currentState.IsKeyDown(inputValue.LeftMovementKey)) { body.Velocity.X -= 50f * dt; } if (currentState.IsKeyDown(inputValue.RightMovementKey)) { body.Velocity.X += 50f * dt; } if (currentState.IsKeyDown(Keys.X)) { body.Velocity.Y -= 50f * dt; } if (currentState.IsKeyDown(Keys.Z)) { body.Velocity.Y += 50f * dt; } body.LinDrag = 0.3f; /* * * //((LookAtCamera)Camera).Target = new Vector3(m.M41, m.M42*0.0f, m.M43); * //var ta = ((LookAtCamera)Camera).Target; * var p = b.Position; * var c = ((LookAtCamera)Camera).Position; * var dist = 30f; * var yDist = -20f; * var h = b.Heading; * * // Vi positionerar kamera utifrån karaktärens heading (h), p = karaktärerns position, c = kamerans position, t = kamerans target, dist = avstånd till objektet * // yDist = höjd för kameran, samt t = p -- alltså att kamerans target är position för karaktären. * // Då gäller c=p-[d*sin(h + pi/2), y, (-d)*cos(h + pi/2)] * * c = Vector3.Subtract(p, new Vector3((float)(dist * Math.Sin(h + Math.PI * 0.5f)), yDist, (float)((-dist) * Math.Cos(h + Math.PI * 0.5f)))); * * c.Y = -yDist; // Lock camera to given height * p.Y = 0; // Target too because it was really ugly otherwise * * ((LookAtCamera)Camera).Target = p; * ((LookAtCamera)Camera).Position = c; * * return Matrix.CreateLookAt(Position, (Vector3)m_Target, Up); * */ } }
public void OnStart(CBody oBody) { _oEvalProxy = gameObject.AddComponent<CEvalProxy>(); _oEvalProxy.OnStart(oBody); }