Ejemplo n.º 1
0
            public Blip(IMapObject item, BlipVisual[] visuals)
            {
                this.Item = item;
                this.Visuals = visuals;

                this.HasUprightVisual = visuals.Any(o => o.IsVisualUpright);
            }
 public MapObject_ChasePoint_Velocity GetChaseObject(IMapObject item)
 {
     return new MapObject_ChasePoint_Velocity(item)
     {
         Multiplier = trkMultiplier.Value,
         MaxVelocity = chkMaxVelocity.IsChecked.Value ? trkMaxVelocity.Value : (double?)null,
     };
 }
Ejemplo n.º 3
0
            public double Lifespan = 45d;       // seconds

            #region Public Methods

            public void BotAdded(IMapObject item)
            {
                lock (_parentLock)
                {
                    this.Bot = (ArcBotNPC)item;
                    this.Rules = GetRules(this.Bot);

                    this.State = BotState.Added;
                }
            }
Ejemplo n.º 4
0
            public TrackedItem(IMapObject mapObject, MapObject_ChasePoint_Forces translate, MapObject_ChaseOrientation_Torques rotate, double? graduleTo100PercentDuration, double? delayBeforeGradule, bool didOriginalLimitRotation)
            {
                this.MapObject = mapObject;
                this.Translate = translate;
                this.Rotate = rotate;

                this.GraduleTo100PercentDuration = graduleTo100PercentDuration;
                this.DelayBeforeGradule = delayBeforeGradule;
                this.ElapsedTime = 0d;

                this.DidOriginalLimitRotation = didOriginalLimitRotation;
            }
        public MapObject_ChasePoint_Direct(IMapObject item, Vector3D offset, bool shouldMoveWithSpring, bool shouldSpringCauseTorque, bool shouldDampenWhenSpring, Viewport3D viewport, Color? springColor = null)
        {
            this.Item = item;
            this.Offset = item.PhysicsBody.DirectionFromWorld(offset);       // convert to model coords
            _viewport = viewport;

            this.SpringForceMultiplier = 1d;

            // Newton uses zero (or maybe negative?) mass for bodies that ignore physics.  So a spring is only effective on
            // bodies with mass
            //TODO: See if PhysicsBody.IsFrozen will block the spring
            if (shouldMoveWithSpring && item.PhysicsBody.MassMatrix.Mass > 0)
            {
                #region Init spring

                this.IsUsingSpring = true;
                this.ShouldDampenWhenSpring = shouldDampenWhenSpring;
                _shouldSpringCauseTorque = shouldSpringCauseTorque;

                if (springColor != null)
                {
                    _springVisual = new ScreenSpaceLines3D();
                    _springVisual.Thickness = 1d;
                    _springVisual.Color = springColor.Value;
                    _viewport.Children.Add(_springVisual);
                }
                else
                {
                    _springVisual = null;
                }

                _springConstant = item.PhysicsBody.MassMatrix.Mass * 50d;

                this.Item.PhysicsBody.ApplyForceAndTorque += new EventHandler<NewtonDynamics.BodyApplyForceAndTorqueArgs>(PhysicsBody_ApplyForceAndTorque);

                #endregion
            }
            else
            {
                #region Init direct move

                this.IsUsingSpring = false;
                this.ShouldDampenWhenSpring = false;
                _shouldSpringCauseTorque = false;
                _springVisual = null;
                _springConstant = 0d;

                #endregion
            }
        }
Ejemplo n.º 6
0
        public double GetDamage_Collision(IMapObject collidedWith, Point3D positionModel, Vector3D velocityModel, double mass1, double mass2)
        {
            const double MAXMASSRATIO = 3;

            TakesDamageWorker_Props props = GetTypeModifier(collidedWith);

            double speed = velocityModel.Length;

            // If the impact velocity is low enough, there won't be damage
            if (speed < props.VelocityThreshold)
            {
                return 0;
            }

            // Restrict mass
            // If the difference in mass is large enough, then the larger could just be considered as a stationary object.  Including more of the larger's
            // mass would make it appear like there is more energy than there actually is (a probe hitting a large asteroid or a planet will feel the
            // same impulse, even though the masses are very different)
            UtilityCore.MinMax(ref mass1, ref mass2);
            if (mass2 > mass1 * MAXMASSRATIO)
            {
                mass2 = mass1 * MAXMASSRATIO;
            }

            // Next check is the collision energy
            // Energy = m/2 * v^2
            double energy = ((mass1 + mass2) / 2d) * speed * speed;

            //May or may not want this check
            // If one of the masses is significantly small relative to the other, then velocity will need to be very large for damage to occur

            // Next is the min energy threshold
            if (energy < props.EnergyTheshold)
            {
                return 0;
            }

            // Final step should just be to convert energy into hitpoint loss
            // HitPointLoss = Energy * c
            double retVal = energy * props.EnergyToHitpointMult;

            // Finally, run it through a randomization
            retVal *= StaticRandom.GetRandomForThread().NextBellPercent(ItemOptions.DAMAGE_RANDOMBELL, props.RandomPercent);

            //LogHit(mass1, mass2, speed, energy);

            return retVal;
        }
        public MapObject_ChasePoint_Forces GetChaseObject_Linear(IMapObject item)
        {
            if (!_isLinear)
            {
                throw new InvalidOperationException("This method can only be called when the control represents linear");
            }

            MapObject_ChasePoint_Forces retVal = new MapObject_ChasePoint_Forces(item, false);

            //TODO: May want to expose these.  I think they're unnecessary, and the result of overdesign
            //retVal.MaxAcceleration = 
            //retVal.MaxForce = 

            List<ChasePoint_Force> forces = new List<ChasePoint_Force>();

            foreach (UIElement entry in pnlForces.Children)
            {
                ChasePoint_Force chaseObject = null;
                if (entry is ForceEntry)
                {
                    chaseObject = ((ForceEntry)entry).GetChaseObject_Linear();
                }
                else
                {
                    throw new ApplicationException("Unknown type of entry: " + entry.ToString());
                }

                //NOTE: Doing a null check, because if they uncheck enabled, it will come back null
                if (chaseObject != null)
                {
                    forces.Add(chaseObject);
                }
            }

            if (forces.Count > 0)
            {
                retVal.Forces = forces.ToArray();
                return retVal;
            }
            else
            {
                // Don't bother returning something that will fail on update
                return null;
            }
        }
        public SelectedItemSwimbots(IMapObject item, Vector3D offset, ShipViewerWindow shipViewer, FrameworkElement viewportContainer, Viewport3D viewport, Canvas canvas, PerspectiveCamera camera, bool shouldMoveWidthSpring, bool shouldSpringCauseTorque, Color? springColor)
            : base(item, offset, shouldMoveWidthSpring, shouldSpringCauseTorque, true, viewport, springColor)
        {
            this.Viewer = shipViewer;
            _viewportContainer = viewportContainer;
            _canvas = canvas;
            _camera = camera;

            if (this.Viewer != null)
            {
                this.Viewer.Closed += new EventHandler(Viewer_Closed);
            }

            item.PhysicsBody.BodyMoved += new EventHandler(Item_BodyMoved);
            _camera.Changed += new EventHandler(Camera_Changed);
            _viewportContainer.SizeChanged += new SizeChangedEventHandler(ViewportContainer_SizeChanged);

            UpdateHightlight();
        }
Ejemplo n.º 9
0
        private void SetSelected(IMapObject selection)
        {
            this.InvokeLater(() =>
            {
                if (selection == null)
                {
                    return;
                }

                var item = EntityList.Items.OfType <ListViewItem>().FirstOrDefault(x => x.Tag == selection);
                if (item == null)
                {
                    return;
                }

                item.Selected = true;
                EntityList.EnsureVisible(EntityList.Items.IndexOf(item));
            });
        }
        //public IMapObject[,] level1 = new IMapObject[28,112];


        public static IMapObject[,] LoadMapWithObjects(Level level)
        {
            IMapObject[,] objectRenderedMap = new IMapObject[28, 112];

            for (int y = 0; y < level.LevelAsCharArray.GetLength(1); y++)
            {
                for (int x = 0; x < level.LevelAsCharArray.GetLength(0); x++)
                {
                    PositionOnMap currentPosition = new PositionOnMap {
                        X = x, Y = y
                    };
                    char symbol = level.LevelAsCharArray[x, y];

                    switch (symbol)
                    {
                    case '|':
                        objectRenderedMap[x, y] = new WallObject(symbol, currentPosition);
                        break;

                    case '@':
                        objectRenderedMap[x, y] = new PlayerObject(symbol, currentPosition);
                        break;

                    case 'T':
                        objectRenderedMap[x, y] = new GroundObject(symbol, currentPosition);
                        break;

                    case ' ':
                        objectRenderedMap[x, y] = new MapObject(symbol, currentPosition);
                        break;

                    case '_':
                        objectRenderedMap[x, y] = new RoofObject(symbol, currentPosition);
                        break;

                    default:
                        break;
                    }
                }
            }
            return(objectRenderedMap);
        }
Ejemplo n.º 11
0
 public static VmfObject Serialise(IMapObject obj)
 {
     if (obj is Root r)
     {
         return(new VmfWorld(r));
     }
     if (obj is Entity e)
     {
         return(new VmfEntity(e));
     }
     if (obj is Group g)
     {
         return(new VmfGroup(g));
     }
     if (obj is Solid s)
     {
         return(new VmfSolid(s));
     }
     return(null);
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Push a new or existing object to a layer cache.
        /// </summary>
        /// <param name="layerIdentifier"></param>
        /// <param name="graphic"></param>
        public void Push(string layerIdentifier, IMapObject graphic)
        {
            Guid   id      = graphic.Id;
            string layerId = layerIdentifier;

            if (!_layerCache.TryGetValue(layerId, out var graphicCache))
            {
                graphicCache = new ConcurrentDictionary <Guid, IMapObject>();
                _layerCache.TryAdd(layerId, graphicCache);
            }

            if (graphicCache.TryGetValue(id, out var existingGraphic))
            {
                graphicCache[id] = graphic;
            }
            else
            {
                graphicCache.TryAdd(id, graphic);
            }
        }
Ejemplo n.º 13
0
        private string GetNodeText(IMapObject obj)
        {
            var text = obj.ID + " - " + obj.GetType().Name;

            var ed = obj.Data.GetOne <EntityData>();

            if (ed != null)
            {
                if (!String.IsNullOrWhiteSpace(ed.Name))
                {
                    text += " - " + ed.Name;
                }
                var tn = ed.Get <string>("targetname") ?? ed.Get <string>("name");
                if (!String.IsNullOrWhiteSpace(tn))
                {
                    text += " - " + tn;
                }
            }

            return(text);
        }
Ejemplo n.º 14
0
        public static float GetAngleToPlayer(this IMapObject mapObject, Player player)
        {
            var         eyeX        = MathF.Sin(player.DirectionAngle);
            var         eyeY        = MathF.Cos(player.DirectionAngle);
            var         playerAngle = MathF.Atan2(eyeY, eyeX);
            const float pi2         = MathF.PI * 0.5f;
            var         dv          = mapObject.Position - player.Position;
            var         angle       = playerAngle - MathF.Atan2(dv.Y, dv.X);

            if (angle < -MathF.PI)
            {
                angle += pi2;
            }

            if (angle > MathF.PI)
            {
                angle -= pi2;
            }

            return(angle);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Removes a map object from the map.
        /// </summary>
        /// <param name="obj">The map object to remove.</param>
        /// <returns>True if the map object was removed.</returns>
        public bool RemoveFromMap(IMapObject obj)
        {
            if (Map.MapObjects.ContainsKey(obj.ClientId))
            {
                var player = obj as Models.Entities.Player;
                if (player != null)
                {
                    if (!Map.Players.TryRemove(player.ClientId, out player))
                    {
                        player.ClientSocket.Disconnect(Drivers.Messages.Errors.FAILED_TO_REMOVE_FROM_MAP);
                    }
                }

                if (Map.MapObjects.TryRemove(obj.ClientId, out obj))
                {
                    obj.Map = null;
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 16
0
        public virtual void SetDamage(int damage, IMapObject attackingObject)
        {
            if (random.Next(0, 101) > dodgeChance * 100)
            {
                if (damage - armor > 0)
                {
                    currentHealtPoint -= damage - armor;

                    EventLog.doEvent(name + " получил " + damage + " урона от: " + attackingObject.name, ConsoleColor.DarkGreen);

                    ObjectDeath();
                }
                else
                {
                    EventLog.doEvent(("Атака от: " + attackingObject.name + "по " + name + " не пробила броню"), ConsoleColor.DarkRed);
                }
            }
            else
            {
                EventLog.doEvent(("Уворот, " + name + " избежал урона от: " + attackingObject.name), ConsoleColor.DarkRed);
            }
        }
Ejemplo n.º 17
0
        public Box GetBoundingBox(IMapObject obj)
        {
            // Try and get a bounding box for point entities
            var name   = obj.Data.GetOne <EntityData>()?.Name;
            var origin = obj.Data.GetOne <Origin>()?.Location ?? Vector3.Zero;

            if (name == null)
            {
                return(null);
            }

            // Get the class (must be point)
            var cls = _data.Classes.FirstOrDefault(x => String.Equals(x.Name, name, StringComparison.InvariantCultureIgnoreCase) && x.ClassType == ClassType.Point);

            if (cls == null)
            {
                return(null);
            }

            // Default to 16x16
            var sub = new Vector3(-8, -8, -8);
            var add = new Vector3(8, 8, 8);

            // Get the size behaviour
            var behav = cls.Behaviours.SingleOrDefault(x => x.Name == "size");

            if (behav != null && behav.Values.Count >= 6)
            {
                sub = behav.GetVector3(0) ?? Vector3.Zero;
                add = behav.GetVector3(1) ?? Vector3.Zero;
            }
            else if (cls.Name == "infodecal")
            {
                // Special handling for infodecal if it's not specified
                sub = Vector3.One * -4;
                add = Vector3.One * 4;
            }
            return(new Box(origin + sub, origin + add));
        }
Ejemplo n.º 18
0
        private SerialisedObject SerialiseEntity(IMapObject obj)
        {
            var self = VmfObject.Serialise(obj);

            if (self == null)
            {
                return(null);
            }

            var so = self.ToSerialisedObject();

            foreach (var solid in obj.FindAll().OfType <Solid>())
            {
                var s = VmfObject.Serialise(solid);
                if (s != null)
                {
                    so.Children.Add(s.ToSerialisedObject());
                }
            }

            return(so);
        }
Ejemplo n.º 19
0
        public void Remove(IMapObject item)
        {
            for (int cntr = 0; cntr < _items.Count; cntr++)
            {
                if (_items[cntr].MapObject.Equals(item))
                {
                    if (_items[cntr].Translate != null)
                    {
                        _items[cntr].Translate.Dispose();
                    }

                    if (_items[cntr].Rotate != null)
                    {
                        _items[cntr].Rotate.Dispose();
                    }

                    _items.RemoveAt(cntr);

                    return;
                }
            }
        }
Ejemplo n.º 20
0
        public Task Convert(BufferBuilder builder, MapDocument document, IMapObject obj, ResourceCollector resourceCollector)
        {
            var points = new[]
            {
                // X axis - red
                new VertexStandard {
                    Position = Vector3.Zero, Colour = Vector4.UnitX + Vector4.UnitW
                },
                new VertexStandard {
                    Position = Vector3.UnitX * 100, Colour = Vector4.UnitX + Vector4.UnitW
                },

                // Y axis - green
                new VertexStandard {
                    Position = Vector3.Zero, Colour = Vector4.UnitY + Vector4.UnitW
                },
                new VertexStandard {
                    Position = Vector3.UnitY * 100, Colour = Vector4.UnitY + Vector4.UnitW
                },

                // Z axis - blue
                new VertexStandard {
                    Position = Vector3.Zero, Colour = Vector4.UnitZ + Vector4.UnitW
                },
                new VertexStandard {
                    Position = Vector3.UnitZ * 100, Colour = Vector4.UnitZ + Vector4.UnitW
                },
            };

            var indices = new uint[] { 0, 1, 2, 3, 4, 5 };

            builder.Append(points, indices, new []
            {
                new BufferGroup(PipelineType.Wireframe, CameraType.Perspective, 0, (uint)indices.Length)
            });

            return(Task.FromResult(0));
        }
Ejemplo n.º 21
0
    // Token: 0x06000392 RID: 914 RVA: 0x0001BAA8 File Offset: 0x00019CA8
    public PlayerDart(global::Char charBelong, int dartType, SkillPaint sp, int x, int y)
    {
        this.skillPaint = sp;
        this.charBelong = charBelong;
        this.info       = GameScr.darts[dartType];
        this.va         = this.info.va;
        this.x          = x;
        this.y          = y;
        IMapObject mapObject;

        if (charBelong.mobFocus == null)
        {
            IMapObject charFocus = charBelong.charFocus;
            mapObject = charFocus;
        }
        else
        {
            mapObject = charBelong.mobFocus;
        }
        IMapObject mapObject2 = mapObject;

        this.setAngle(Res.angle(mapObject2.getX() - x, mapObject2.getY() - y));
    }
Ejemplo n.º 22
0
        /// <summary>
        /// Adds a map object to the map.
        /// </summary>
        /// <param name="obj">The object to add.</param>
        /// <returns>True if the object was added.</returns>
        public bool AddToMap(IMapObject obj)
        {
            var player = obj as Models.Entities.Player;

            if (player != null)
            {
                if (!Map.Players.TryAdd(obj.ClientId, player))
                {
                    player.ClientSocket.Disconnect(Drivers.Messages.Errors.FAILED_TO_ADD_TO_MAP);
                    return(false);
                }
            }

            if (Map.MapObjects.TryAdd(obj.ClientId, obj))
            {
                obj.Map = Map;
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// This informs the caller that an item was selected, and gives them a chance to instantiate an overriden
        /// SelectedItems instance that holds custom selection visuals
        /// </summary>
        protected virtual MapObject_ChasePoint_Direct OnItemSelected(IMapObject item, Vector3D offset, Point clickPoint)
        {
            if (this.ItemSelected == null)
            {
                // No listeners
                return(new MapObject_ChasePoint_Direct(item, offset, this.ShouldMoveItemWithSpring, this.ShouldSpringCauseTorque, this.ShouldDampenWhenSpring, _viewport, this.SpringColor));
            }

            ItemSelectedArgs args = new ItemSelectedArgs(item, offset, clickPoint, this.ShouldMoveItemWithSpring, this.ShouldSpringCauseTorque, this.SpringColor);

            // Raise the event
            this.ItemSelected(this, args);

            // See if they created a custom instance
            if (args.Requested_SelectedItem_Instance != null)
            {
                return(args.Requested_SelectedItem_Instance);
            }
            else
            {
                return(new MapObject_ChasePoint_Direct(item, offset, this.ShouldMoveItemWithSpring, this.ShouldSpringCauseTorque, this.ShouldDampenWhenSpring, _viewport, this.SpringColor));
            }
        }
Ejemplo n.º 24
0
        private int TryPush(IMapObject target, Point position, out Point currentPosition)
        {
            currentPosition = position;
            var initialForce = GetInitialForce(target);

            for (var remainingForce = initialForce; remainingForce > 0; remainingForce--)
            {
                var nextPosition   = Point.GetPointInDirection(currentPosition, direction);
                var movementResult = MovementHelper.MoveObject(target, currentPosition, nextPosition);
                if (!movementResult.Success)
                {
                    return(remainingForce);
                }

                if (!movementResult.NewPosition.Equals(nextPosition))
                {
                    return(0);
                }
                currentPosition = nextPosition;
            }

            return(0);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Add property into mapping setting
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <typeparam name="TDestination"></typeparam>
        /// <param name="mapObject"></param>
        /// <param name="sourceExpression"></param>
        /// <param name="destinationExpression"></param>
        /// <returns></returns>
        public static IMapObject <TSource, TDestination> Add <TSource, TDestination>(this IMapObject <TSource, TDestination> mapObject,
                                                                                     Expression <Func <TSource, object> > sourceExpression, Expression <Func <TDestination, object> > destinationExpression)
        {
            var map = GetMapSetting <TSource, TDestination>();

            if (map.Key == Guid.Empty)
            {
                throw new ArgumentException($"Setting not found (Source: \"{ typeof(TSource).Name}\", Destination: \"{typeof(TDestination).Name}\").");
            }

            string toProperty = GetPropertyName(destinationExpression);

            // remove if exist in ignore listing
            if (map.Value.IgnoreProperties.Any(x => x == toProperty))
            {
                map.Value.IgnoreProperties.Remove(toProperty);
            }

            var mapProperty = map.Value.MapProperties.FirstOrDefault(x => x.ToProperty == toProperty);

            if (mapProperty != null)
            {
                map.Value.MapProperties.Remove(mapProperty);
            }

            // TODO: need to check the same type
            string fromProperty = GetPropertyName(sourceExpression);

            map.Value.MapProperties.Add(new MapProperty
            {
                ToProperty   = toProperty,
                MapType      = MapType.MapProperty,
                FromProperty = fromProperty
            });

            return(mapObject);
        }
Ejemplo n.º 26
0
        private void ReadMapBase(Map map, IMapObject obj, BinaryReader br)
        {
            var visgroupId = br.ReadInt32();

            if (visgroupId > 0)
            {
                obj.Data.Add(new VisgroupID(visgroupId));
            }

            var c = br.ReadRGBColour();

            obj.Data.Add(new ObjectColor(c));

            var numChildren = br.ReadInt32();

            for (var i = 0; i < numChildren; i++)
            {
                var child = ReadObject(map, br);
                if (child != null)
                {
                    child.Hierarchy.Parent = obj;
                }
            }
        }
Ejemplo n.º 27
0
 public bool CanAdd(IMapObject item)
 {
     return(BoundingRect.Contains(item.MidLat, item.MidLon));
 }
Ejemplo n.º 28
0
 public bool IsSelected(IMapObject parent, Face face)
 {
     return(_selectedFaces.ContainsKey(parent) && _selectedFaces[parent].Contains(face.ID));
 }
Ejemplo n.º 29
0
 public void RemoveFillObject(IMapObject mapObject)
 {
     objectsOnMap.Remove(mapObject);
 }
Ejemplo n.º 30
0
        private static Vector3D? GetNeighborAccel(IMapObject thisBot, Tuple<MapObjectInfo, double, ForceSettings_Initial>[] neighbors, Point3D position, Vector3D velocity)
        {
            Vector3D? retVal = null;

            foreach (var neighbor in neighbors)
            {
                #region attract/repel

                ChasePoint_GetForceArgs args = new ChasePoint_GetForceArgs(thisBot, neighbor.Item1.Position - position);

                Vector3D? attractRepelAccel = MapObject_ChasePoint_Forces.GetForce(args, neighbor.Item3.Forces);

                #endregion
                #region match velocity

                Vector3D? accel = null;
                if (neighbor.Item3.MatchVelocityPercent != null)
                {
                    Vector3D matchVelocity = GetMatchVelocityForce(neighbor.Item1, velocity);

                    // Combine forces
                    if (attractRepelAccel == null)
                    {
                        accel = matchVelocity;
                    }
                    else
                    {
                        accel = Math3D.GetAverage(new[]
                        {
                            Tuple.Create(attractRepelAccel.Value, 1d),
                            Tuple.Create(matchVelocity, neighbor.Item3.MatchVelocityPercent.Value)        //NOTE: When the percent is 1 (100%), this will cause a 50/50 average with the other accel
                        });
                    }
                }
                else
                {
                    accel = attractRepelAccel;
                }

                #endregion

                // Add to total
                if (accel != null)
                {
                    if (retVal == null)
                    {
                        retVal = accel;
                    }
                    else
                    {
                        retVal = retVal.Value + accel.Value;
                    }
                }
            }

            return retVal;
        }
Ejemplo n.º 31
0
 public int CompareTo(IMapObject other)
 {
     return MapObjectUtil.CompareToT(this, other);
 }
Ejemplo n.º 32
0
        public virtual void TakeDamage_Collision(IMapObject collidedWith, Point3D positionModel, Vector3D velocityModel, double mass1, double mass2)
        {
            if (_parts == null || _parts.AllPartsArray == null || _parts.AllPartsArray.Length == 0)
            {
                return;
            }

            #region EXTREME

            // This is a lot of work, but just finding the closest point seems to return the same thing

            //var allHits = _parts.AllPartsArray.
            //    Select(o =>
            //    {
            //        Point3D nearest = Math3D.GetClosestPoint_Line_Point(positionModel, velocityModel, o.Position);

            //        return new
            //        {
            //            Part = o,
            //            PartRadius = Math1D.Avg(o.ScaleActual.X, o.ScaleActual.Y, o.ScaleActual.Z) / 2,
            //            Nearest = nearest,
            //            DistFromLineSqr = (nearest - o.Position).LengthSquared,
            //            DistFromHitSqr = (o.Position - positionModel).LengthSquared,
            //        };
            //    }).
            //    //OrderBy(o => o.DistFromHitSqr).       // don't bother yet
            //    ToArray();

            // Only consider parts that the impact velocity line pierces
            //var bestHit = allHits.
            //    Where(o => o.DistFromLineSqr <= o.PartRadius * o.PartRadius).
            //    OrderBy(o => o.DistFromHitSqr).
            //    FirstOrDefault();

            //if (bestHit == null)
            //{
            //    // The impact line doesn't intersect any parts.  Just choose the part that is closest to the impact point
            //    bestHit = allHits.
            //        OrderBy(o => o.DistFromHitSqr).
            //        First();
            //}

            #endregion

            //TODO: If it's a hard enough impact, damage parts that are in line and touching - make the chance of distribution higher if the impacted
            //part is already destroyed

            // Find the nearest part
            Tuple<PartBase, int> nearestPart = _parts.AllPartsArray.
                Select((o, i) => Tuple.Create(o, i)).
                OrderBy(o => (o.Item1.Position - positionModel).LengthSquared).
                First();

            // Transform the hit into part's coords
            Point3D positionPart = _partTransformToModel[nearestPart.Item2].Transform(positionModel);
            Vector3D velocityPart = _partTransformToModel[nearestPart.Item2].Transform(velocityModel);

            nearestPart.Item1.TakeDamage_Collision(collidedWith, positionPart, velocityPart, mass1, mass2);
        }
Ejemplo n.º 33
0
        //NOTE: The map WILL remove the ModelVisual3D's from the main viewport
        public void RemoveItem(IMapObject item)
        {
            int index = -1;

            if (item is Mineral)
            {
                #region Mineral

                index = _minerals.IndexOf((Mineral)item);

                if (_mineralBlips[index] != null)
                {
                    _viewportMap.Children.Remove(_mineralBlips[index]);
                }

                foreach (ModelVisual3D model in item.Visuals3D)
                {
                    _viewport.Children.Remove(model);
                }

                _minerals.RemoveAt(index);
                _mineralBlips.RemoveAt(index);

                _world.RemoveBody(item.PhysicsBody);

                #endregion
            }
            else if (item is Asteroid)
            {
                #region Asteroid

                index = _asteroids.IndexOf((Asteroid)item);

                if (_asteroidBlips[index] != null)
                {
                    _viewportMap.Children.Remove(_asteroidBlips[index]);
                }

                foreach (ModelVisual3D model in item.Visuals3D)
                {
                    _viewport.Children.Remove(model);
                }

                _asteroids.RemoveAt(index);
                _asteroidBlips.RemoveAt(index);

                _world.RemoveBody(item.PhysicsBody);

                #endregion
            }
            else if (item is SpaceStation)
            {
                #region Space Station

                index = _spaceStations.IndexOf((SpaceStation)item);

                _viewportMap.Children.Remove(_spaceStationBlips[index]);

                foreach (ModelVisual3D model in item.Visuals3D)
                {
                    _viewport.Children.Remove(model);
                }

                _spaceStations.RemoveAt(index);
                _spaceStationBlips.RemoveAt(index);

                #endregion
            }
            else if (item is Ship)
            {
                #region Ship

                throw new ApplicationException("finish this");

                _ship = null;
                _viewportMap.Children.Remove(_shipBlip);
                _shipBlip = null;

                foreach (ModelVisual3D model in item.Visuals3D)
                {
                    _viewport.Children.Remove(model);
                }

                _world.RemoveBody(item.PhysicsBody);

                #endregion
            }
            else if (item is SwarmBot2)
            {
                #region SwarmBot2

                ((SwarmBot2)item).ShouldDrawThrustLine = false;		// it's leaving its thrust line on the viewport (thrustline isn't returned by Visuals3D)
                ((SwarmBot2)item).ShouldShowDebugVisuals = false;

                foreach (ModelVisual3D model in item.Visuals3D)
                {
                    _viewport.Children.Remove(model);
                }

                _swarmbots.Remove((SwarmBot2)item);

                _world.RemoveBody(item.PhysicsBody);

                #endregion
            }
            else
            {
                throw new ApplicationException("Unknown item type: " + item.ToString());
            }
        }
Ejemplo n.º 34
0
        //NOTE: The map won't load ModelVisual3D's to the main viewport, because the physics engine needs them added in it's constructor
        public void AddItem(IMapObject item)
        {
            ModelVisual3D blip = null;

            // These if statements are in order of what is most likely to be added
            if (item is Mineral)
            {
                #region Mineral

                blip = GetMineralBlip((Mineral)item);

                _minerals.Add((Mineral)item);
                _mineralBlips.Add(blip);

                if (blip != null)        // I may not bother making a blip for the tiny minerals
                {
                    _viewportMap.Children.Add(blip);
                }

                #endregion
            }
            else if (item is Asteroid)
            {
                #region Asteroid

                blip = GetAsteroidBlip((Asteroid)item);

                _asteroids.Add((Asteroid)item);
                _asteroidBlips.Add(blip);

                if (blip != null)        // I may not bother making a blip for the tiny asteroids
                {
                    _viewportMap.Children.Add(blip);
                }

                #endregion
            }
            else if (item is SpaceStation)
            {
                #region Space Station

                blip = GetSpaceStationBlip((SpaceStation)item);

                _spaceStations.Add((SpaceStation)item);
                _spaceStationBlips.Add(blip);

                _viewportMap.Children.Add(blip);

                #endregion
            }
            else if (item is Ship)
            {
                #region Ship

                _ship = (Ship)item;

                _shipBlip = GetShipBlip(_ship);
                _shipCompassBlip = GetShipCompassBlip(_ship);
                _viewportMap.Children.Add(_shipBlip);
                _viewportMap.Children.Add(_shipCompassBlip);

                #endregion
            }
            else if (item is SwarmBot2)
            {
                #region SwarmBot2

                _swarmbots.Add((SwarmBot2)item);

                #endregion
            }
            else
            {
                throw new ApplicationException("Unknown item type: " + item.ToString());
            }
        }
Ejemplo n.º 35
0
        public virtual void TakeDamage_Collision(IMapObject collidedWith, Point3D positionModel, Vector3D velocityModel, double mass1, double mass2)
        {
            if (_damageWorker == null)
            {
                return;
            }

            double damage = _damageWorker.GetDamage_Collision(collidedWith, positionModel, velocityModel, mass1, mass2);

            AdjustHitpoints(-damage);
        }
        //TODO: Have a way to determine which props will be needed up front, and only populate those
        public ChaseOrientation_GetTorqueArgs(IMapObject item, Quaternion rotation)
        {
            this.Item = item;
            this.ItemMass = item.PhysicsBody.Mass;

            this.Rotation = rotation;
            Vector3D direction = rotation.Axis;

            // Angular Velocity
            Vector3D angularVelocity = this.Item.PhysicsBody.AngularVelocity;
            this.AngVelocityLength = angularVelocity.Length;
            this.AngVelocityUnit = angularVelocity.ToUnit(false);

            // Along
            Vector3D velocityAlong = angularVelocity.GetProjectedVector(direction);
            this.AngVelocityAlongLength = velocityAlong.Length;
            this.AngVelocityAlongUnit = velocityAlong.ToUnit(false);
            this.IsAngVelocityAlongTowards = Vector3D.DotProduct(direction, angularVelocity) > 0d;

            // Orth
            Vector3D orth = Vector3D.CrossProduct(direction, angularVelocity);       // the first cross is orth to both (outside the plane)
            orth = Vector3D.CrossProduct(orth, direction);       // the second cross is in the plane, but orth to distance
            Vector3D velocityOrth = angularVelocity.GetProjectedVector(orth);

            this.AngVelocityOrthLength = velocityOrth.Length;
            this.AngVelocityOrthUnit = velocityOrth.ToUnit(false);
        }
        public MapObject_ChaseOrientation_Velocity(IMapObject item)
        {
            this.Item = item;

            this.Item.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(PhysicsBody_ApplyForceAndTorque);
        }
Ejemplo n.º 38
0
 private Image GetImageForMapObject(IMapObject o, IGameEngine engine)
 {
     Image i = new Image();
     switch (o.Name)
     {
         case "Opened Door":
             i.Source = m_images["OpenDoor"].Source;
             break;
         case "Closed Door":
             i.Source = m_images["ClosedDoor"].Source;
             break;
         case "Stairs Up":
         {  
             StairMovmentType type = engine.GameState.IsStairMovementSpecial(o.Position);
             switch (type)
             {
                 case StairMovmentType.QuitGame:
                     i.Source = m_images["LastStairsUp"].Source;
                     break;
                 case StairMovmentType.None:
                 default:
                     i.Source = m_images["StairsUp"].Source;
                     break;
             }
             break;
         }
         case "Stairs Down":
         {  
             StairMovmentType type = engine.GameState.IsStairMovementSpecial(o.Position);
             switch (type)
             {
                 case StairMovmentType.WinGame:
                     i.Source = m_images["LastStairsDown"].Source;
                     break;
                 case StairMovmentType.None:
                 default:
                     i.Source = m_images["StairsDown"].Source;
                     break;
             }
             break;
         }
         case "Treasure Chest":
             i.Source = m_images["Chest"].Source;
             break;
         case "Fountain":
             i.Source = m_images["Fountain"].Source;
             break;
         default:
             throw new InvalidOperationException("GetImageForMapObject - can't find image for: " + o.Name);
     }
     return i;
 }
Ejemplo n.º 39
0
 // Token: 0x06000394 RID: 916 RVA: 0x0001BB48 File Offset: 0x00019D48
 public void update()
 {
     if (!this.isActive)
     {
         return;
     }
     if (this.charBelong.mobFocus == null && this.charBelong.charFocus == null)
     {
         this.endMe();
     }
     else
     {
         IMapObject mapObject;
         if (this.charBelong.mobFocus == null)
         {
             IMapObject charFocus = this.charBelong.charFocus;
             mapObject = charFocus;
         }
         else
         {
             mapObject = this.charBelong.mobFocus;
         }
         IMapObject mapObject2 = mapObject;
         for (int i = 0; i < (int)this.info.nUpdate; i++)
         {
             if (this.info.tail.Length > 0)
             {
                 this.darts.addElement(new SmallDart(this.x, this.y));
             }
             int num = (this.charBelong.getX() <= mapObject2.getX()) ? -10 : 10;
             this.dx = mapObject2.getX() + num - this.x;
             this.dy = mapObject2.getY() - mapObject2.getH() / 2 - this.y;
             this.life++;
             if (Res.abs(this.dx) < 20 && Res.abs(this.dy) < 20)
             {
                 if (this.charBelong.charFocus != null && this.charBelong.charFocus.me)
                 {
                     this.charBelong.charFocus.doInjure(this.charBelong.charFocus.damHP, 0, this.charBelong.charFocus.isCrit, this.charBelong.charFocus.isMob);
                 }
                 this.endMe();
                 return;
             }
             int num2 = Res.angle(this.dx, this.dy);
             if (global::Math.abs(num2 - this.angle) < 90 || this.dx * this.dx + this.dy * this.dy > 4096)
             {
                 if (global::Math.abs(num2 - this.angle) < 15)
                 {
                     this.angle = num2;
                 }
                 else if ((num2 - this.angle >= 0 && num2 - this.angle < 180) || num2 - this.angle < -180)
                 {
                     this.angle = Res.fixangle(this.angle + 15);
                 }
                 else
                 {
                     this.angle = Res.fixangle(this.angle - 15);
                 }
             }
             if (!this.isSpeedUp && this.va < 8192)
             {
                 this.va += 1024;
             }
             this.vx  = this.va * Res.cos(this.angle) >> 10;
             this.vy  = this.va * Res.sin(this.angle) >> 10;
             this.dx += this.vx;
             int num3 = this.dx >> 10;
             this.x  += num3;
             this.dx &= 1023;
             this.dy += this.vy;
             int num4 = this.dy >> 10;
             this.y  += num4;
             this.dy &= 1023;
         }
         for (int j = 0; j < this.darts.size(); j++)
         {
             SmallDart smallDart = (SmallDart)this.darts.elementAt(j);
             smallDart.index++;
             if (smallDart.index >= this.info.tail.Length)
             {
                 this.darts.removeElementAt(j);
             }
         }
     }
 }
Ejemplo n.º 40
0
        public void Remove(IMapObject item)
        {
            for (int cntr = 0; cntr < _items.Count; cntr++)
            {
                if (_items[cntr].MapObject.Equals(item))
                {
                    if (_items[cntr].Forces != null)
                    {
                        _items[cntr].Forces.Dispose();
                    }

                    if (_items[cntr].ShouldLimitRotation)
                    {
                        item.PhysicsBody.ApplyForceAndTorque -= new EventHandler<BodyApplyForceAndTorqueArgs>(PhysicsBody_ApplyForceAndTorque);
                    }

                    _items.RemoveAt(cntr);

                    return;
                }
            }
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Makes this class show the item passed in
        /// </summary>
        /// <param name="sizePercent">
        /// If several items are shown next to each other, the camera of each viewport needs to be zoomed so that
        /// their relative sizes are the same, so this is this item's radius relative to the largest item's radius
        /// </param>
        public void SetItem(IMapObject item, double sizePercent)
        {
            // Remove previous item
            if (_item != null)
            {
                RemoveVisual();
            }

            // Store it
            _item = item;

            // Display new item
            if (_item != null)
            {
                CreateVisual(sizePercent);
            }
        }
Ejemplo n.º 42
0
        public void Add(IMapObject item, bool shouldLimitRotation)
        {
            if (_items.Any(o => o.MapObject.Equals(item)))
            {
                // It's already added
                return;
            }

            //#region Forces

            //MapObject_ChasePoint_Forces chaseForces = new MapObject_ChasePoint_Forces(item, false);
            //if (item.PhysicsBody != null)
            //{
            //    //TODO: This could change over time.  Need to adjust it every once in a while
            //    chaseForces.Offset = item.PhysicsBody.CenterOfMass.ToVector();
            //}

            //// Attraction Force
            //chaseForces.Forces.Add(new ChaseForcesGradient<ChaseForcesConstant>(new[]
            //        {
            //            new ChaseForcesGradientStop<ChaseForcesConstant>(new ChaseDistance(true, 0d), new ChaseForcesConstant(ChaseDirectionType.Direction) { BaseAcceleration = 20d, ApplyWhenUnderSpeed = 100d }),
            //            new ChaseForcesGradientStop<ChaseForcesConstant>(new ChaseDistance(false, 1d), new ChaseForcesConstant(ChaseDirectionType.Direction) { BaseAcceleration = 500d, ApplyWhenUnderSpeed = 100d }),
            //            new ChaseForcesGradientStop<ChaseForcesConstant>(new ChaseDistance(true, double.MaxValue), new ChaseForcesConstant(ChaseDirectionType.Direction) { BaseAcceleration = 500d, ApplyWhenUnderSpeed = 100d })
            //        }));

            //// These act like a shock absorber
            //chaseForces.Forces.Add(new ChaseForcesDrag(ChaseDirectionType.Velocity_AlongIfVelocityAway) { BaseAcceleration = 50d });

            //chaseForces.Forces.Add(new ChaseForcesGradient<ChaseForcesDrag>(new[]
            //        {
            //            new ChaseForcesGradientStop<ChaseForcesDrag>(new ChaseDistance(true, 0d), new ChaseForcesDrag(ChaseDirectionType.Velocity_AlongIfVelocityToward) { BaseAcceleration = 100d }),
            //            new ChaseForcesGradientStop<ChaseForcesDrag>(new ChaseDistance(false, .75d), new ChaseForcesDrag(ChaseDirectionType.Velocity_AlongIfVelocityToward) { BaseAcceleration = 20d }),
            //            new ChaseForcesGradientStop<ChaseForcesDrag>(new ChaseDistance(false, 2d), new ChaseForcesDrag(ChaseDirectionType.Velocity_AlongIfVelocityToward) { BaseAcceleration = 0d }),
            //        }));

            //#endregion



            //if (shouldLimitRotation)
            //{
            //item.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(PhysicsBody_ApplyForceAndTorque);
            //}

            //_items.Add(new TrackedItem(item, chaseForces, shouldLimitRotation));
            _items.Add(new TrackedItem(item, null, shouldLimitRotation));
        }
Ejemplo n.º 43
0
 public bool Equals(IMapObject other)
 {
     return MapObjectUtil.EqualsT(this, other);
 }
Ejemplo n.º 44
0
        /// <summary>
        /// This informs the caller that an item was selected, and gives them a chance to instantiate an overriden
        /// SelectedItems instance that holds custom selection visuals
        /// </summary>
        protected virtual MapObject_ChasePoint_Direct OnItemSelected(IMapObject item, Vector3D offset, Point clickPoint)
        {
            if (this.ItemSelected == null)
            {
                // No listeners
                return new MapObject_ChasePoint_Direct(item, offset, this.ShouldMoveItemWithSpring, this.ShouldSpringCauseTorque, this.ShouldDampenWhenSpring, _viewport, this.SpringColor);
            }

            ItemSelectedArgs args = new ItemSelectedArgs(item, offset, clickPoint, this.ShouldMoveItemWithSpring, this.ShouldSpringCauseTorque, this.SpringColor);

            // Raise the event
            this.ItemSelected(this, args);

            // See if they created a custom instance
            if (args.Requested_SelectedItem_Instance != null)
            {
                return args.Requested_SelectedItem_Instance;
            }
            else
            {
                return new MapObject_ChasePoint_Direct(item, offset, this.ShouldMoveItemWithSpring, this.ShouldSpringCauseTorque, this.ShouldDampenWhenSpring, _viewport, this.SpringColor);
            }
        }
Ejemplo n.º 45
0
 public void AddToFill(IMapObject mapObject)
 {
     objectsOnMap.Add(mapObject);
 }
Ejemplo n.º 46
0
 public ItemSelectedArgs(IMapObject item, Vector3D offset, Point clickPoint, bool shouldMoveItemWithSpring, bool shouldSpringCauseTorque, Color? springColor)
 {
     this.Item = item;
     this.Offset = offset;
     this.ClickPoint = clickPoint;
     this.ShouldMoveItemWithSpring = shouldMoveItemWithSpring;
     this.ShouldSpringCauseTorque = shouldSpringCauseTorque;
     this.SpringColor = springColor;
 }
Ejemplo n.º 47
0
 public DamageBlockedMessage(IMapObject target, int blockedValue, Element damageElement)
 {
     this.target        = target;
     this.blockedValue  = blockedValue;
     this.damageElement = damageElement;
 }
Ejemplo n.º 48
0
        private TakesDamageWorker_Props GetTypeModifier(IMapObject collidedWith)
        {
            if (_typeModifiers == null)
            {
                return _default;
            }

            Type type = collidedWith.GetType();

            // Look for an exact type match
            var retVal = _typeModifiers.
                FirstOrDefault(o => type.Equals(o.Item1));

            if (retVal == null)
            {
                // No match, look for a match with a base type
                retVal = _typeModifiers.
                    FirstOrDefault(o => type.IsSubclassOf(o.Item1));
            }

            if (retVal == null)
            {
                return null;
            }
            else
            {
                return retVal.Item2;
            }
        }
Ejemplo n.º 49
0
 public void OnTap(IMapObject obj)
 {
 }
Ejemplo n.º 50
0
 public TrackedItem(IMapObject mapObject, MapObject_ChasePoint_Forces forces, bool shouldLimitRotation)
 {
     this.MapObject = mapObject;
     this.Forces = forces;
     this.ShouldLimitRotation = shouldLimitRotation;
 }
Ejemplo n.º 51
0
 public virtual void HandleCollision(IMapObject collidee)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 52
0
        public void Add(IMapObject item, bool shouldLimitRotation)
        {
            if (_items.Any(o => o.MapObject.Equals(item)))
            {
                // It's already added
                return;
            }

            #region Forces

            List<ChasePoint_Force> forces = new List<ChasePoint_Force>();

            // Attraction Force
            var gradient = new[]
                {
                    Tuple.Create(0d, .04d),     // distance, %
                    Tuple.Create(1d, 1d),
                };
            forces.Add(new ChasePoint_Force(ChaseDirectionType.Attract_Direction, 500, gradient: gradient));

            // These act like a shock absorber
            forces.Add(new ChasePoint_Force(ChaseDirectionType.Drag_Velocity_AlongIfVelocityAway, 50));

            gradient = new[]
                {
                    Tuple.Create(0d, 1d),
                    Tuple.Create(.75d, .2d),
                    Tuple.Create(2d, 0d),
                };
            forces.Add(new ChasePoint_Force(ChaseDirectionType.Drag_Velocity_AlongIfVelocityToward, 100d, gradient: gradient));


            MapObject_ChasePoint_Forces chaseForces = new MapObject_ChasePoint_Forces(item, false);
            if (item.PhysicsBody != null)
            {
                //TODO: This could change over time.  Need to adjust it every once in a while
                chaseForces.Offset = item.PhysicsBody.CenterOfMass.ToVector();
            }

            chaseForces.Forces = forces.ToArray();

            #region ORIG

            //// Attraction Force
            //chaseForces.Forces.Add(new ChasePoint_ForcesGradient<ChasePoint_ForcesAttract>(new[]
            //        {
            //            new ChasePoint_ForcesGradientStop<ChasePoint_ForcesAttract>(new ChasePoint_Distance(true, 0d), new ChasePoint_ForcesAttract() { BaseAcceleration = 20d, ApplyWhenUnderSpeed = 100d }),
            //            new ChasePoint_ForcesGradientStop<ChasePoint_ForcesAttract>(new ChasePoint_Distance(false, 1d), new ChasePoint_ForcesAttract() { BaseAcceleration = 500d, ApplyWhenUnderSpeed = 100d }),
            //            new ChasePoint_ForcesGradientStop<ChasePoint_ForcesAttract>(new ChasePoint_Distance(true, double.MaxValue), new ChasePoint_ForcesAttract() { BaseAcceleration = 500d, ApplyWhenUnderSpeed = 100d })
            //        }));

            //// These act like a shock absorber
            //chaseForces.Forces.Add(new ChasePoint_ForcesDrag(ChasePoint_DirectionType.Velocity_AlongIfVelocityAway) { BaseAcceleration = 50d });

            //chaseForces.Forces.Add(new ChasePoint_ForcesGradient<ChasePoint_ForcesDrag>(new[]
            //        {
            //            new ChasePoint_ForcesGradientStop<ChasePoint_ForcesDrag>(new ChasePoint_Distance(true, 0d), new ChasePoint_ForcesDrag(ChasePoint_DirectionType.Velocity_AlongIfVelocityToward) { BaseAcceleration = 100d }),
            //            new ChasePoint_ForcesGradientStop<ChasePoint_ForcesDrag>(new ChasePoint_Distance(false, .75d), new ChasePoint_ForcesDrag(ChasePoint_DirectionType.Velocity_AlongIfVelocityToward) { BaseAcceleration = 20d }),
            //            new ChasePoint_ForcesGradientStop<ChasePoint_ForcesDrag>(new ChasePoint_Distance(false, 2d), new ChasePoint_ForcesDrag(ChasePoint_DirectionType.Velocity_AlongIfVelocityToward) { BaseAcceleration = 0d }),
            //        }));

            #endregion

            #endregion

            //if (shouldLimitRotation)
            //{
            //    item.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(PhysicsBody_ApplyForceAndTorque);
            //}

            _items.Add(new TrackedItem(item, chaseForces, shouldLimitRotation));
            //_items.Add(new TrackedItem(item, null, shouldLimitRotation));
        }
Ejemplo n.º 53
0
 protected VmfObject(IMapObject obj)
 {
     ID     = obj.ID;
     Editor = new VmfEditor(obj);
 }
Ejemplo n.º 54
0
 public int CompareTo(IMapObject other)
 {
     return(MapObjectUtil.CompareToT(this, other));
 }
Ejemplo n.º 55
0
 protected VmfEntity(IMapObject obj) : base(obj)
 {
     EntityData = obj.Data.GetOne <EntityData>() ?? new EntityData();
     Origin     = obj.Data.GetOne <Origin>()?.Location ?? Vector3.Zero;
 }
Ejemplo n.º 56
0
        private static Vector3D? GetNeighborAccel(IMapObject thisBot, Tuple<MapObjectInfo, double, ForceSettings_Initial>[] neighbors, Point3D position, Vector3D velocity, double minSpeed)
        {
            Vector3D? retVal = null;

            foreach (var neighbor in neighbors)
            {
                #region attract/repel

                ChasePoint_GetForceArgs args = new ChasePoint_GetForceArgs(thisBot, neighbor.Item1.Position - position);

                Vector3D? attractRepelAccel = MapObject_ChasePoint_Forces.GetForce(args, neighbor.Item3.Forces);

                #endregion
                #region match velocity

                Vector3D? accel = null;
                if (neighbor.Item3.MatchVelocityPercent != null)
                {
                    Vector3D matchVelocity = GetMatchVelocityForce(neighbor.Item1, velocity);

                    // Combine forces
                    if (attractRepelAccel == null)
                    {
                        accel = matchVelocity;
                    }
                    else
                    {
                        accel = Math3D.GetAverage(new[]
                        {
                            Tuple.Create(attractRepelAccel.Value, 1d),
                            Tuple.Create(matchVelocity, neighbor.Item3.MatchVelocityPercent.Value)        //NOTE: When the percent is 1 (100%), this will cause a 50/50 average with the other accel
                        });
                    }
                }
                else
                {
                    accel = attractRepelAccel;
                }

                #endregion

                // Add to total
                if (accel != null)
                {
                    if (retVal == null)
                    {
                        retVal = accel;
                    }
                    else
                    {
                        retVal = retVal.Value + accel.Value;
                    }
                }
            }

            #region min speed

            if (minSpeed > 0 && !minSpeed.IsNearZero())
            {
                Vector3D thisVel = thisBot.VelocityWorld;

                if (thisVel.LengthSquared < minSpeed * minSpeed)
                {
                    thisVel = thisVel.ToUnit(false);
                    if (thisVel.LengthSquared.IsNearZero())
                    {
                        thisVel = Math3D.GetRandomVector_Spherical(minSpeed);
                    }
                    else
                    {
                        thisVel *= minSpeed;
                    }

                    retVal += thisVel;
                }
            }

            #endregion

            return retVal;
        }
Ejemplo n.º 57
0
        public void Remove(IMapObject item)
        {
            for (int cntr = 0; cntr < _items.Count; cntr++)
            {
                if (_items[cntr].MapObject.Equals(item))
                {
                    if (_items[cntr].Translate != null)
                    {
                        _items[cntr].Translate.Dispose();
                    }

                    if (_items[cntr].Rotate != null)
                    {
                        _items[cntr].Rotate.Dispose();
                    }

                    _items.RemoveAt(cntr);

                    return;
                }
            }
        }
Ejemplo n.º 58
0
        public SwarmBot1b(double radius, Point3D position, IMapObject parent, World world, Map map, SwarmObjectiveStrokes strokes, int materialID, double healRate, double damageAtMaxSpeed, double maxHealth, Color? color = null)
        {
            _parent = parent;
            _parentType = parent != null ? parent.GetType() : null;
            _map = map;
            _strokes = strokes;

            this.Radius = radius;
            this.SearchRadius = radius * 100;

            _settings_Parent = CreateForceSettingInitial_Parent();
            _settings_OtherBot_Chase = CreateForceSettingInitial_OtherBot_Chase();
            _settings_OtherBot_Passive = CreateForceSettingInitial_OtherBot_Passive();
            _settings_Asteroid = CreateForceSettingInitial_Asteroid();

            #region WPF Model

            this.Model = GetModel(radius, color);
            this.Model.Transform = new ScaleTransform3D(radius, radius, radius);

            // Model Visual
            ModelVisual3D visual = new ModelVisual3D();
            visual.Content = this.Model;

            #endregion

            #region Physics Body

            Transform3DGroup transform = new Transform3DGroup();
            transform.Children.Add(new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRandomRotation())));
            transform.Children.Add(new TranslateTransform3D(position.ToVector()));

            double mass = GetMass(radius);

            using (CollisionHull hull = CollisionHull.CreateSphere(world, 0, new Vector3D(radius / 2, radius / 2, radius / 2), null))
            {
                this.PhysicsBody = new Body(hull, transform.Value, mass, new Visual3D[] { visual });
                //this.PhysicsBody.IsContinuousCollision = true;
                this.PhysicsBody.MaterialGroupID = materialID;
                this.PhysicsBody.LinearDamping = .01d;
                this.PhysicsBody.AngularDamping = new Vector3D(.01d, .01d, .01d);

                this.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(Body_ApplyForceAndTorque);
            }

            #endregion

            _hitPoints = new Container()
            {
                QuantityMax = maxHealth,
                QuantityCurrent = maxHealth,
            };

            _healRate = healRate;
            _damageAtMaxSpeed = damageAtMaxSpeed;

            this.CreationTime = DateTime.UtcNow;
        }
Ejemplo n.º 59
0
 public bool Equals(IMapObject other)
 {
     return(MapObjectUtil.EqualsT(this, other));
 }
 public ShowMapObjectMessage(IMapObject mapObject)
 {
     MapObject = mapObject;
 }