Beispiel #1
0
        //AboutBox aboutForm = new AboutBox();

        #endregion
        //--------------------------------
        #endregion
        //========= CONSTRUCTORS =========
        #region Constructors

        /** <summary> Constructs the form. </summary> */
        public GroupForm(string[] args)
        {
            InitializeComponent();

            Pathing.SetPathSprites();
            Water.LoadResources();
            ColorRemapping.LoadResources();
            Terrain.LoadResources();

            this.fontBold = new SpriteFont(Resources.BoldFont, ' ', 'z', 10);

            this.drawSettings.Remap1 = RemapColors.IndianRed;
            this.drawSettings.Remap2 = RemapColors.Gold;
            this.drawSettings.Remap3 = RemapColors.Bark;
            this.drawSettings.Slope  = -1;



            this.labelCurrentObject.Text = "";

            this.objectImage = new Bitmap(190, 254);


            this.LoadSettings(null, null);

            //this.directory = this.defaultDirectory;

            this.sceneryGroup = new SceneryGroup();

            this.sceneryGroup = (SceneryGroup)ObjectData.FromBuffer(Resources.SCGCUST);
            this.sceneryGroup.ObjectHeader.Flags = 0x7;
            LoadSceneryGroup();
        }
Beispiel #2
0
    private void createVIP(int team)
    {
        Transform v = (Transform)Instantiate(VIPPrefab, teamStartPositions [team], Quaternion.identity);             //instantiate a VIP for this team

        v.GetComponent <Renderer> ().material.color = teamColours [team];                                            //set the VIP's color
        v.tag = "VIP" + team.ToString();                                                                             //set the VIP's tag
        v.GetComponent <AILogic>().teamID = team;
        VIPs[team] = v;
        for (int i = 0; i < numTeams; i++)
        {
            visibleVIPs[i].Add(v, false);
        }
        // path nodes
        Pathing pth = v.GetComponent <Pathing> ();
        //GameObject pathNodes = GameObject.Find ("VIPpath" + i);
        //print(i);
        GameObject pathNodes = GameObject.Find("/VIPpath" + team);

        //print(pathNodes);
        Transform[] nodes = pathNodes.GetComponentsInChildren <Transform> ();
        // !!!! k=1, because i think the parent transform will be included (a bad location).
        for (int k = 1; k < nodes.Length; k++)
        {
            pth.insertPathNode(nodes [k].gameObject);
//			print (k + ": " + nodes [k].gameObject.transform.position);
        }
    }
Beispiel #3
0
    IEnumerator walk(Point target)
    {
        List <Point> path = Pathing.getPath(myPosition(), target);

        //List<Point> path = new List<Point>(){ new Point(0,5)};
        Debug.Log("Walk towards: " + target.x + " " + target.y);

        foreach (Point p in path)
        {
            //rotate towards point
            rotationRoutine = rotateTowardsPoint(p);
            StartCoroutine(rotationRoutine);
            while (rotationRoutine != null)
            {
                yield return(null);
            }

            //moves toward point
            movingToPointRoutine = moveToPoint(p);
            StartCoroutine(movingToPointRoutine);
            while (movingToPointRoutine != null)
            {
                yield return(null);
            }
        }
    }
Beispiel #4
0
        /// <summary>
        ///     Decisions picking for the bot.
        /// </summary>
        public static void Decisions()
        {
            // Picks best position for the bot.
            if (Core.GameTickCount - LastUpdate > 75)
            {
                /*
                 * foreach (var hero in EntityManager.Heroes.AllHeroes.Where(a => a != null && a.IsValidTarget() && !a.Added() && ObjectsManager.HealthRelics.Any(hr => a.Path.LastOrDefault().Distance(hr.Position) <= 1)))
                 * {
                 *  hero.Add();
                 *  Logger.Send("Added: " + hero.BaseSkinName + " - " + hero.NetworkId, Logger.LogLevel.Warn);
                 * }*/

                Pathing.BestPosition();
                LastUpdate = Core.GameTickCount;
            }

            // Ticks for the modes manager.
            ModesManager.OnTick();

            if (!(Program.Moveto.Contains("Enemy") || Program.Moveto.Contains("AllySpawn")) && !(ModesManager.Flee || ModesManager.None) && Player.Instance.IsRanged && ObjectsManager.NearestEnemy != null && Pathing.Position.CountEnemiesInRange(Player.Instance.GetAutoAttackRange()) > 1)
            {
                Pathing.Position = ObjectsManager.NearestEnemy.Position.Extend(ObjectsManager.AllySpawn, Misc.KiteDistance(ObjectsManager.NearestEnemy)).To3D();
            }

            if (Pathing.Position.UnderEnemyTurret() && !Misc.SafeToDive && ObjectsManager.AllySpawn != null)
            {
                Pathing.Position = Pathing.Position.Extend(ObjectsManager.AllySpawn.Position, 250).To3D();
            }

            // Moves to the Bot selected Position.
            if (Pathing.Position != Vector3.Zero && Pathing.Position.IsValid() && !Pathing.Position.IsZero)
            {
                Pathing.MoveTo(Pathing.Position);
            }
        }
Beispiel #5
0
        public void AddFile(string path, string entryPath, WADEntry entry)
        {
            char pathSeparator = Pathing.GetPathSeparator(path);

            string[] folders = path.Split(pathSeparator);

            //If folders length is 1 then we can add the file to this directory
            //if not, then we pass it down the hierarchy
            if (folders.Length == 1)
            {
                this.Items.Add(new WadFileViewModel(this._wadViewModel, this, entryPath, folders[0], entry));
            }
            else
            {
                //If the folder exists we pass the file to it
                //if it doesn't then we create it before passing the file
                if (this.Items.FirstOrDefault(x => x.Name == folders[0]) is WadFolderViewModel folder)
                {
                    folder.AddFile(path.Substring(path.IndexOf(pathSeparator) + 1), entryPath, entry);
                }
                else
                {
                    string             newFolderPath = string.Format("{0}/{1}", this.Path, folders[0]);
                    WadFolderViewModel newFolder     = new WadFolderViewModel(this._wadViewModel, this, newFolderPath);

                    newFolder.AddFile(path.Substring(path.IndexOf(pathSeparator) + 1), entryPath, entry);
                    this.Items.Add(newFolder);
                }
            }
        }
Beispiel #6
0
 public override HashSet <Tile> GetHover(Tile tile)
 {
     Tile[] path;
     Pathing.CheapestPath(unit.tile, tile, out var result, pather, cc);
     path = result.path;
     return(new HashSet <Tile>(path));
 }
Beispiel #7
0
    /// <summary> Utility method that returns a list of Tiles that satisfy the range values in TargetAbilityData. </summary>
    protected IEnumerable <Tile> GetDefaultRangeTiles()
    {
        var tile = unit.tile;
        IEnumerable <Tile> res;

        if (range.enabled)
        {
            if (rangeMode == RangeMode.Distance)
            {
                res = Game.grid.Radius(tile, range.current);
            }
            else
            {
                res = Pathing.GetDistanceField(tile, range.current, Pathers.For(rangeMode)).tiles.Keys;
            }
        }
        else
        {
            res = Game.grid.tiles.Values;
        }

        if (requiresVision.current)
        {
            res = res.Where(h => Game.grid.HasSight(tile, h));
        }

        return(res);
    }
Beispiel #8
0
        //--------------------------------
        #endregion
        //========= CONSTRUCTORS =========
        #region Constructors

        /** <summary> Constructs the form. </summary> */
        public AudioForm()
        {
            InitializeComponent();

            Pathing.SetPathSprites();
            Water.LoadResources();
            Terrain.LoadResources();
            ColorRemapping.LoadResources();

            this.dataDirectory = "";
            string[] possibleDirectories =
            {
                "%PROGRAMFILES%\\Steam\\steamapps\\common\\Rollercoaster Tycoon 2\\ObjData",
                "%PROGRAMFILES%\\Infogrames\\Rollercoaster Tycoon 2\\ObjData",
                "%PROGRAMFILES%\\Atari\\Rollercoaster Tycoon 2\\ObjData",
                "%PROGRAMFILES(x86)%\\Steam\\steamapps\\common\\Rollercoaster Tycoon 2\\ObjData",
                "%PROGRAMFILES(x86)%\\Infogrames\\Rollercoaster Tycoon 2\\ObjData",
                "%PROGRAMFILES(x86)%\\Atari\\Rollercoaster Tycoon 2\\ObjData",
                "%USERPROFILE%\\Desktop"
            };

            for (int i = 0; i < possibleDirectories.Length; i++)
            {
                if (Directory.Exists(Environment.ExpandEnvironmentVariables(possibleDirectories[i])))
                {
                    this.dataDirectory = Environment.ExpandEnvironmentVariables(possibleDirectories[i]);
                    break;
                }
            }
            this.LoadSettings(null, null);
        }
Beispiel #9
0
    protected void Awake()
    {
        if (Hole == null)
        {
            Debug.LogError($"{name}: no hole assigned!");
        }

        gm = FindObjectOfType <GameManager>();

        if (gm == null)
        {
            Debug.LogError($"{name}: no game manager found!");
        }

        pathing = GetComponent <Pathing>();

        if (pathing == null)
        {
            Debug.LogError($"{name}: No pathing component attached!");
        }

        graphics = GetComponentsInChildren <SpriteRenderer>();

        if (graphics[0] == null)
        {
            Debug.LogError($"{name}: missing child graphic object!");
        }

        // Register listeners
        TileUpdateEvent.RegisterListener(TileUpdated);
    }
Beispiel #10
0
        private void PackWadFolders(string wadLocation)
        {
            //Loop through each WAD folder
            foreach (string wadFolder in Directory.EnumerateDirectories(wadLocation))
            {
                char   separator = Pathing.GetPathSeparator(wadFolder);
                string wadName   = wadFolder.Split(separator).Last();

                using (WADFile wad = new WADFile(3, 0))
                {
                    //Add each file to the WAD
                    foreach (string wadFolderFile in Directory.EnumerateFiles(wadFolder, "*", SearchOption.AllDirectories))
                    {
                        string path      = wadFolderFile.Replace(wadFolder + separator, "").Replace('\\', '/');
                        ulong  hash      = XXHash.XXH64(Encoding.ASCII.GetBytes(path.ToLower()));
                        string extension = Path.GetExtension(wadFolderFile);

                        wad.AddEntry(hash, File.ReadAllBytes(wadFolderFile), extension != ".wpk" && extension != ".bnk" ? true : false);
                    }

                    //After WAD creation is finished we can write the WAD to the ZIP
                    ZipArchiveEntry archiveEntry = this.Content.CreateEntry(string.Format(@"WAD\{0}", wadName));
                    wad.Write(archiveEntry.Open());
                }
            }
        }
Beispiel #11
0
        public LeagueFileIndex(string leagueFolder)
        {
            string wadRootPath = Path.Combine(leagueFolder, @"DATA\FINAL");

            this.Version = new Version(FileVersionInfo.GetVersionInfo(Path.Combine(leagueFolder, "League of Legends.exe")).FileVersion);

            foreach (string wadFile in Directory.GetFiles(wadRootPath, "*", SearchOption.AllDirectories).Where(x => x.Contains(".wad")))
            {
                using (WADFile wad = new WADFile(wadFile))
                {
                    List <ulong> fileHashes = new List <ulong>();
                    foreach (WADEntry entry in wad.Entries)
                    {
                        fileHashes.Add(entry.XXHash);

                        string gameWadPath = wadFile.Replace(leagueFolder + Pathing.GetPathSeparator(leagueFolder), "");

                        if (this._gameIndex.ContainsKey(entry.XXHash))
                        {
                            this._gameIndex[entry.XXHash].Add(gameWadPath);
                        }
                        else
                        {
                            this._gameIndex.Add(entry.XXHash, new List <string>()
                            {
                                gameWadPath
                            });
                        }
                    }
                }
            }

            Write();
        }
Beispiel #12
0
        /// <summary>
        ///     Detect a fixed drive by letter.
        /// </summary>
        /// <param name="driveName">A valid drive letter.</param>
        /// <param name="queryType">The QueryType.</param>
        /// <param name="useFallbackQuery">Use QueryType.SeekPenalty as fallback.</param>
        /// <returns>A list of DriveInfoExtended.</returns>
        /// <exception cref="IOException"></exception>
        /// <exception cref="UnauthorizedAccessException"></exception>
        /// <exception cref="DriveNotFoundException"></exception>
        /// <exception cref="SecurityException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="DetectionFailedException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static DriveInfoExtended DetectFixedDrive(string driveName, QueryType queryType = QueryType.SeekPenalty,
                                                         bool useFallbackQuery = true)
        {
            var driveInfoExtended = new DriveInfoExtended();
            var logicalDrive      = new DriveInfo(driveName);

            if (logicalDrive.DriveType == DriveType.Fixed)
            {
                if (logicalDrive.IsReady)
                {
                    var tmp = new DriveInfoExtended
                    {
                        DriveFormat        = logicalDrive.DriveFormat,
                        VolumeLabel        = logicalDrive.VolumeLabel,
                        Name               = logicalDrive.Name,
                        UncPath            = Pathing.GetUNCPath(logicalDrive.Name),
                        DriveType          = logicalDrive.DriveType,
                        AvailableFreeSpace = logicalDrive.AvailableFreeSpace,
                        TotalSize          = logicalDrive.TotalSize,
                        TotalFreeSpace     = logicalDrive.TotalFreeSpace,
                        RootDirectory      = logicalDrive.RootDirectory,
                        DriveLetter        = logicalDrive.Name.Substring(0, 1).ToCharArray()[0]
                    };

                    var driveId = GetDiskId(tmp.DriveLetter);
                    if (driveId != -1)
                    {
                        tmp.Id = driveId;
                        if (queryType == QueryType.SeekPenalty)
                        {
                            tmp.HardwareType = DetectHardwareTypeBySeekPenalty(driveId);
                        }
                        else
                        {
                            if (IsAdministrator())
                            {
                                tmp.HardwareType = DetectHardwareTypeByRotationRate(driveId);
                            }
                            else
                            {
                                if (useFallbackQuery)
                                {
                                    tmp.HardwareType = DetectHardwareTypeBySeekPenalty(driveId);
                                }
                                else
                                {
                                    throw new SecurityException(
                                              "DetectHardwareTypeBySeekPenalty needs administrative access.");
                                }
                            }
                        }
                        if (tmp.HardwareType != HardwareType.Unknown)
                        {
                            driveInfoExtended = tmp;
                        }
                    }
                }
            }
            return(driveInfoExtended);
        }
Beispiel #13
0
 void OnGUI()
 {
     if (targetAble)
     {
         targetCoordinates = new Vector3(ScreenCoordinates.x - (TargetBox.width / 2),
                                         Screen.height - ScreenCoordinates.y - (TargetBox.height / 2),
                                         0);
         textureCoordinate = Pathing.Approach(textureCoordinate, targetCoordinates, lockQuality);
         if (Vector3.Distance(textureCoordinate, targetCoordinates) > 7)
         {
             GUI.Label(new Rect(textureCoordinate.x, textureCoordinate.y,
                                TargetBox.width, TargetBox.height), TargetBox);
             Lock = false;
         }
         else
         {
             GUI.Label(new Rect(textureCoordinate.x, textureCoordinate.y,
                                TargetBox.width, TargetBox.height), TargetBoxLocked);
             textureCoordinate.x += Random.Range(-30, 30);
             textureCoordinate.y += Random.Range(-30, 30);
             lockQuality          = Pathing.Approach(lockQuality, 1, .01f);
             Lock = true;
         }
     }
 }
Beispiel #14
0
        static void Postfix(Pathing __instance, bool calledFromUI)
        {
            try
            {
                if (__instance.ResultDestination == null || __instance.CurrentPath == null || __instance.OwningActor == null || __instance.CurrentGrid == null)
                {
                    Mod.Log.Warn?.Write($"UpdateMeleePath diagnostics failed - CU patch may NRE shortly!");
                    Mod.Log.Warn?.Write($"  -- OwningActor != null? {(__instance.OwningActor != null)}  owningActor: {__instance.OwningActor.DistinctId()}");
                    Mod.Log.Warn?.Write($"  -- CurrentGrid != null? {(__instance.CurrentGrid != null)}  ResultDestination != null? {(__instance.ResultDestination != null)}");
                    Mod.Log.Warn?.Write($"  -- CurrentPath != null? {(__instance.CurrentPath != null)}");
                }

                if (__instance.CurrentPath != null)
                {
                    foreach (PathNode node in __instance.CurrentPath)
                    {
                        if (node.Position == null)
                        {
                            Mod.Log.Warn?.Write($"Found a path node with no position! This should not happen!");
                            Mod.Log.Warn?.Write($"  -- nodeIndex: {node.Index}  occupyingActor: {node.OccupyingActor}");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Mod.Log.Warn?.Write(e, $"UpdateMeleePath diagnostics failed - CU patch may NRE shortly!");
                Mod.Log.Warn?.Write(e, $"  -- OwningActor != null? {(__instance.OwningActor != null)}  owningActor: {__instance.OwningActor.DistinctId()}");
                Mod.Log.Warn?.Write(e, $"  -- CurrentGrid != null? {(__instance.CurrentGrid != null)}  ResultDestination != null? {(__instance.ResultDestination != null)}");
                Mod.Log.Warn?.Write(e, $"  -- CurrentPath != null? {(__instance.CurrentPath != null)}");
            }
        }
Beispiel #15
0
        void UpdatePath(ref InstanceData instance, List <Transform> path, ref PathProps path_props)
        {
            var dirty = path_props.Update(path, this.p, this.m);

            if (dirty)
            {
                this.p.UpdatePath(ref path_props._cached_path);         // send updated path to gpu if path changed
            }
            // optional debug path drawing
            if (path_props.draw_path)
            {
                // Draw path
                Pathing.DebugDrawPath(path_props._cached_path, path: p.path.Array, path_up: p.path_up.Array, path_t: p.path_t.Array, start_index: p.StartIndexOfPath(path_props._cached_path), n_samples: 100);

                // Draw orientation of instance
                Vector3 position, direction, up;
                p.CalculatePathPositionDirection(path_props._cached_path, instance, out position, out direction, out up);
                Debug.DrawLine(position, position + direction * 1.5f, Color.blue);
                Debug.DrawLine(position, position + up * 1.5f, Color.green);
                Debug.DrawLine(position, position + Vector3.Cross(up, direction).normalized * 1.5f, Color.red);
            }

            // update instance if speed was changed or the path changed
            if (instance.props_pathSpeed != path_props.speed || dirty)
            {
                instance.SetPath(path_props._cached_path, this.m, path_props.speed);
                this.m.Append(ref instance);
                path_props.speed = instance.props_pathSpeed;
            }
        }
Beispiel #16
0
 public static void SetMeleeTarget(Pathing __instance, AbstractActor target)
 {
     try {
         thisMeleeAttacker = __instance.OwningActor;
         thisMeleeTarget   = target;
     }                 catch (Exception ex) { Error(ex); }
 }
Beispiel #17
0
    void SellPlantAI(float plantSmoothing)
    {
        int tileX = Mathf.FloorToInt(smoothPosition.x);
        int tileY = Mathf.FloorToInt(smoothPosition.z);

        heldPlant.EaseToWorldPosition(smoothPosition.x, smoothPosition.y + .08f, smoothPosition.z, plantSmoothing);

        if (storeX == -1)
        {
            int storeTileHash = Pathing.SearchForOne(tileX, tileY, 30, Pathing.IsNavigableAll, Pathing.IsStore, Pathing.fullMapZone);
            if (storeTileHash != -1)
            {
                Pathing.Unhash(storeTileHash, out storeX, out storeY);
            }
        }
        else
        {
            if (tileX == storeX && tileY == storeY)
            {
                Farm.SellPlant(heldPlant, storeX, storeY);
                targetPlant = null;
                heldPlant   = null;
            }
            else
            {
                position.y = Mathf.MoveTowards(position.y, hoverHeight, ySpeed * Time.deltaTime);
                position.x = Mathf.MoveTowards(position.x, storeX + .5f, xzSpeed * Time.deltaTime);
                position.z = Mathf.MoveTowards(position.z, storeY + .5f, xzSpeed * Time.deltaTime);
            }
        }
    }
Beispiel #18
0
        private void SmashRocksAi()
        {
            if (_targetRock == null)
            {
                _targetRock = Pathing.FindNearbyRock(TileX, TileY, 20, path);
                if (_targetRock == null)
                {
                    intention = Intention.None;
                }
            }
            else
            {
                if (path.xPositions.Count == 1)
                {
                    _attackingARock = true;

                    _targetRock.TakeDamage(1);
                }

                if (_targetRock.health > 0)
                {
                    return;
                }
                _targetRock = null;
                intention   = Intention.None;
            }
        }
    void SmashRocksAI()
    {
        if (targetRock == null)
        {
            targetRock = Pathing.FindNearbyRock(tileX, tileY, 20, path);
            if (targetRock == null)
            {
                intention = Intention.None;
            }
        }
        else
        {
            if (path.xPositions.Count == 1)
            {
                attackingARock = true;

                targetRock.TakeDamage(1);
            }
            if (targetRock.health <= 0)
            {
                targetRock = null;
                intention  = Intention.None;
            }
        }
    }
Beispiel #20
0
        public void Start()
        {
            // Need to create all the threads
            if (Running)
            {
                return;
            }
            Running = true;

            requests = new BucketedQueue <PathingRequest>(ThreadCount);
            threads  = new Thread[ThreadCount];
            pathers  = new Pathing[ThreadCount];

            for (int i = 0; i < ThreadCount; i++)
            {
                Thread t = new Thread(Run);
                threads[i] = t;
                t.Name     = "Pathfinding #" + i;

                Pathing p = new Pathing();
                pathers[i] = p;

                t.Start(i);
            }
        }
Beispiel #21
0
        /// <summary>
        ///     Decisions picking for the bot.
        /// </summary>
        public static void Decisions()
        {
            // Picks best position for the bot.
            Pathing.BestPosition();

            // Ticks for the modes manager.
            ModesManager.OnTick();

            // Moves to the Bot selected Position.
            if (Pathing.Position != Vector3.Zero && Pathing.Position != null)
            {
                Pathing.MoveTo(Pathing.Position);
            }

            // Removes HealthRelics if a hero is in range with them.
            var HR = ObjectsManager.HealthRelics.FirstOrDefault(h => EntityManager.Heroes.AllHeroes.Any(a => !a.IsDead && a.IsInRange(h, h.BoundingRadius * 2)));

            if (HR != null)
            {
                ObjectsManager.HealthRelics.Remove(HR);
                Chat.Print("Removed HR");
            }

            var trap = ObjectsManager.EnemyTraps.FirstOrDefault(h => EntityManager.Heroes.Allies.Any(a => !a.IsDead && a.IsInRange(h, h.BoundingRadius * 2)));

            if (trap != null)
            {
                ObjectsManager.EnemyTraps.Remove(trap);
                Chat.Print("remove trap");
            }
        }
Beispiel #22
0
        public Mob(ContentManager content, Vector2 position, CharactersInRange charactersInRange, OnDeath onDeath, CollisionCheck collisionCheck, String monsterName)
            : base(content, position, SPEED, charactersInRange, onDeath, Constants.DEFAULT_HEALTH)
        {
            StaticDrawable2D character = getCharacterSprite(content, position, monsterName);

            base.init(character);

            BehaviourFinished idleCallback = delegate() {
                swapBehaviours(this.idleBehaviour, State.Idle);
            };
            BehaviourFinished restartPathing = delegate() {
#if DEBUG
                Debug.log("Restarting");
#endif
                //this.activeBehaviour.Target = this.LastKnownLocation;
                pathToWaypoint(this.LastKnownLocation);
            };

            this.seekingBehaviour    = new Tracking(position, SPEED, idleCallback, collisionCheck);
            this.lostTargetBehaviour = new LostTarget(this.seekingBehaviour.Position, this.seekingBehaviour.Position, SPEED, idleCallback);
            this.pathingBehaviour    = new Pathing(position, SPEED, idleCallback, collisionCheck, restartPathing);
            this.idleBehaviour       = new IdleBehaviour(position);
            this.activeBehaviour     = this.idleBehaviour;
            this.CurrentState        = State.Idle;
            updateBoundingSphere();
            this.previousPoint     = base.Position.toPoint();
            this.LastKnownLocation = base.Position;

            this.skills       = new List <Skill>();
            this.explosionSfx = LoadingUtils.load <SoundEffect>(content, "CorpseExplosion");
            initSkills();
        }
Beispiel #23
0
        private void PackWadFolder(string wadFolderLocation)
        {
            string[] wadFolderFiles = Directory.GetFiles(wadFolderLocation, "*", SearchOption.AllDirectories);
            if (wadFolderFiles.Length > 0)
            {
                char   separator = Pathing.GetPathSeparator(wadFolderLocation);
                string wadName   = wadFolderLocation.Split(separator).Last();

                WadBuilder wad = new WadBuilder();

                //Add each file to the WAD
                foreach (string wadFolderFile in Directory.EnumerateFiles(wadFolderLocation, "*", SearchOption.AllDirectories))
                {
                    string path = wadFolderFile.Replace(wadFolderLocation + separator, "").Replace('\\', '/');
                    ulong  hash = XXHash.XXH64(Encoding.ASCII.GetBytes(path.ToLower()));

                    WadEntryBuilder entryBuilder = new();

                    entryBuilder
                    .WithPathXXHash(hash)
                    .WithFileDataStream(File.OpenRead(wadFolderFile));

                    wad.WithEntry(entryBuilder);
                }

                //After WAD creation is finished we can write the WAD to the ZIP
                ZipArchiveEntry archiveEntry = this.Content.CreateEntry(string.Format("WAD/{0}", wadName));
                wad.Build(archiveEntry.Open(), false);
            }
        }
Beispiel #24
0
        void MoveToTargetPoint()
        {
            if (!_moving || _dead || _dying || _resurrecting || _usingSkill || overrideMode != null)
            {
                return;
            }

            var newPath = Pathing.BuildPath(iso.pos, _targetPoint, size: size, self: gameObject);

            if (newPath.Count == 0)
            {
                _moving = false;
                return;
            }
            if (path.Count == 0 || newPath[newPath.Count - 1].pos != path[path.Count - 1].pos)
            {
                AbortPath();
                path.AddRange(newPath);
            }

            if (path.Count == 1 && Vector2.Distance(path[0].pos, _targetPoint) < 1.0f)
            {
                // smooth straightforward movement
                var pathStep = path[0];
                pathStep.pos       = _targetPoint;
                pathStep.direction = _targetPoint - iso.pos;
                path[0]            = pathStep;
            }

            MoveAlongPath();
        }
Beispiel #25
0
        public void Pathing_SupportUnitsLimit_Constructor(int suppU, int suppUResult)
        {
            //Act
            Pathing pathing = new Pathing(true, true, 0, suppU);

            //Assert
            Assert.AreEqual(suppUResult, pathing.SupportUnits);
        }
Beispiel #26
0
 /* Start is called before the first frame update and sets the starting values of this object */
 void Start()
 {
     health    = startHealth;
     speed     = startSpeed * Pathing.acceleration;
     isDead    = false;
     isSlowed  = false;
     enemyPath = this.GetComponent <Pathing>();
 }
Beispiel #27
0
        public void Pathing_Constructor_OK()
        {
            //Act
            Pathing pathing = new Pathing();

            //Assert
            Assert.NotNull(pathing);
        }
Beispiel #28
0
        public void Pathing_MainUnitsLimit_Constructor(int mainU, int mainUResult)
        {
            //Act
            Pathing pathing = new Pathing(true, true, mainU);

            //Assert
            Assert.AreEqual(mainUResult, pathing.MainUnits);
        }
Beispiel #29
0
 public Path getTradeRoute(Building building)
 {
     if (!tradeRoute.ContainsKey(building))
     {
         tradeRoute[building]   = Pathing.findPath(getBase().getDock(), building.getDock(), building.getDockRadius());
         unitsTrading[building] = new HashSet <Unit>();
     }
     return(tradeRoute[building].copy());
 }
Beispiel #30
0
    /**
     *  Sets the necessary parameters to start the movement of the shape, along with its animation
     *  and pathfinding.
     */
    public void moveAnimation(Vector3 targetTile)
    {
        this.GetComponent <Animator>().SetBool("moving", true);
        hasMoved = true;
        GameObject.Find("Main Camera").GetComponent <UIManager>().SetButtons(hasMoved, hasInteracted, name);

        target     = new Vector3(targetTile.x, targetTile.y + Constants.UNIT_TILE_DIFF, targetTile.z);
        targetPath = Pathing.AStar(this.transform.parent.position, target);
    }
        public List<Point> pathNodes(int level, Point origin, Point dest, Pathing.PathingPermission permission)
        {
            List<Point> returnNodes = new List<Point>();

            TCODFov mapToUse;

            switch (permission)
            {
                case Pathing.PathingPermission.Normal:
                    mapToUse = levelTCODMaps[level];
                    break;
                case Pathing.PathingPermission.IgnoreDoors:
                    mapToUse = levelTCODMapsIgnoringClosedDoors[level];
                    break;
                case Pathing.PathingPermission.IgnoreDoorsAndLocks:
                    mapToUse = levelTCODMapsIgnoringClosedDoorsAndLocks[level];
                    break;
                default:
                    mapToUse = levelTCODMaps[level];
                    break;
            }

            //Try to walk the path
            TCODPathFinding path = new TCODPathFinding(mapToUse, 1.0);
            path.ComputePath(origin.x, origin.y, dest.x, dest.y);

            returnNodes.Add(origin);

            int x = origin.x;
            int y = origin.y;

            path.WalkPath(ref x, ref y, false);
            returnNodes.Add(new Point(x, y));

            //If the x and y of the next step it means the path is blocked

            if (x == origin.x && y == origin.y)
            {
                //Return 1 node list
                return returnNodes.GetRange(0, 1);
            }

            do
            {
                path.WalkPath(ref x, ref y, false);
                returnNodes.Add(new Point(x, y));
                if (x == dest.x && y == dest.y)
                    return returnNodes;
            } while (true);
        }
        public Simulation(Pathing.NavMesh navMesh)
        {
            this.NavMesh = navMesh;
            this.Settings = new Settings();
            Running = true;

            sweepAndPrune = new SweepAndPrune1D<Unit>(false);

            //staticObjects = new BruteForceBoundingVolumeHierarchy<Object>();
            //staticObjects = new Quadtree<Object>(0, 0, width, height, 5);
            staticObjects = new Quadtree<Object>(10);
            StaticObjectsProbe = new BVHProbe<Object>(staticObjects);

            //unitObjects = new BruteForceBoundingVolumeHierarchy<Unit>();
            //unitObjects = new Quadtree<Unit>(0, 0, width, height, 5);
            unitObjects = new Quadtree<Unit>(4);
            UnitObjectsProbe = new BVHProbe<Unit>(unitObjects);

            projectiles = new List<Projectile>();
        }
Beispiel #33
0
	/*static private void SetUserVelocityAction(int objectID, Vector3 newVelocity)
	{
		mCurrentInstance.GetObject<Pathing>(objectID).SetUserVelocity(newVelocity);
	}*/

	public void UpdateMoveVelocity(Pathing objectID, double time, Vector3 newVelocity, Vector3 position)
	{
		//double test = 0;
		
		/*if (!mCurrentInstance.IsServer())
		{
			test = EngineManager.CLIENT_DELAY_TIME;
		}*/

		/*if (newVelocity.sqrMagnitude == 0 && mCurrentInstance.IsServer())
		{
			NewEventAllRemote(mCurrentInstance.GetEngineTime() + test, "DoObjectFunction", objectID, "UpdateUserVelocity", newVelocity, position);
		}
		else
		{
			//NewEventAllRemote(mCurrentInstance.GetEngineTime() + test, "DoObjectFunction", objectID, "UpdateUserVelocity", newVelocity, position);
			NewObjectEventAllRemote(objectID, "UpdateUserVelocity", newVelocity, position);
		}*/

		NewObjectEventAllRemote(objectID, "UpdateUserVelocity", time, newVelocity, position);
	}	
	//This needs to be OnRecievedID, or something
	void Start()
	{
		PhysicObject tempObject = gameObject.GetComponent<PhysicObject>();

		if (tempObject != null)
		{
			mThisManager = tempObject.GetInstance();

			if (tempObject.GetInstance().GetSyncedClient() != null)
			{
				int objectID = tempObject.GetObjectID();

				tempObject = tempObject.GetInstance().GetSyncedClient().GetObject<PhysicObject>(objectID);

				mSyncedObject = tempObject.transform;
				mSyncedPhysics = tempObject;
				mSyncedPathing = tempObject.GetComponent<Pathing>();
				mSyncedRigidbody = tempObject.rigidbody2D;
			}
		}
	}
Beispiel #35
0
	//Can use objectID(int), or the actual Class interchangably
	public void SetUserVelocity(Pathing objectID, Vector3 newVelocity)
	{
		if (mCurrentInstance.IsGraphics())
		{
			NewObjectEventLocalOnly(objectID, "SetUserVelocity", newVelocity);
		}
		/*else
		{
			NewObjectEventServerOnly(objectID, "SetUserVelocity", newVelocity);
		}*/
		//NewEventLocalOnly(mCurrentInstance.GetEngineTime() + EngineManager.CLIENT_DELAY_TIME, "DoObjectFunction", objectID, "SetUserVelocity", newVelocity);

		//NewEventAllRemote(mCurrentInstance.GetEngineTime(), "DoObjectFunction", objectID, "UpdateUserVelocity", newVelocity, objectID.transform.localPosition);

		//Use the above command to create events from functions defined in other objects (must be of type EngineObject) - the type will be detected at runtime
		//Further, this function will automatically convert objectIDs to the object type required by the function (again, must be of type EngineObject to convert)
		

		//If you need some complex control over the command, then define a second private function and Call that, as shown below

		//NewEvent("SetUserVelocityAction", objectID, newVelocity);
	}
Beispiel #36
0
	//Test junk
	public void CloneObject(Pathing pathing)
	{
		NewEvent("CloneObjectAction", pathing);
	}
 public Sprite(string _type, int _ID, int _index, Rectangle _rect, Color _color, bool _fliph, bool _flipV, bool _awake, bool _visible,
               bool _collide, int _hitPoints, bool _mobile, float _vel, Vector2 _dir, bool _rotating, float _rotspd, float _totrot, 
               float _scale, bool _animated, bool _awhilestop, bool _bounce, float _fps,
               Sprite.Pathing _pathing, int _pathX, int _pathY, int _pathspd, int _pathstart, bool _pathInert, float _timeDelay )
 {
     spriteType = _type;
     textureID = _ID;
     textureIndex = _index;
     SpriteRectangle = _rect; //calls property to also set location
     tintColor = _color;
     IsFlippedHorizontally = _fliph;
     if (!_fliph) IsFlippedVertically = _flipV;
     isAwake = _awake;
     isVisible = _visible;
     isCollidable = _collide;
     hitPoints = _hitPoints;
     isMobile = _mobile;
     velocity = _vel;
     direction = _dir;
     isRotating = _rotating;
     rotationSpeed = _rotspd;
     totalRotation = _totrot;
     scale = _scale;
     isAnimated = _animated;
     isAnimatedWhileStopped = _awhilestop;
     isBounceAnimated = _bounce;
     animationFPS = _fps;
     pathing = _pathing;
     pathingRadiusX = _pathX;
     pathingRadiusY = _pathY;
     pathingSpeed = _pathspd;
     pathingPercentComplete = _pathstart;
     isPathingInertia = _pathInert;
     timeDelay = _timeDelay;
 }
Beispiel #38
0
        private void PlayPath(string pathName, Pathing pType, bool forawrd, int index, dynamic log = null)
        {
            if (Moving)
                return;
            Moving = true;

            var zoneId = Funcs.GetZoneId();

            HaltFlag = false;
            float heading;
            float tobeHeading;

            foreach (
                var waypoint in
                    RebuildList(_Waypoints.Zone.First(p => p.ID == zoneId).Path.First(i => i.Name == pathName).Point,
                        forawrd, pType, index))
            {
                if (CorDelay)
                    Funcs.SetMoveStatus(WalkingStatus.Standing);

                ModelRotation(waypoint);

                if (CamReset)
                    SendKeyPress(KeyStates.Toggled, Key.End);

                if (CorDelay)
                    Thread.Sleep(HeadToll);

                var decX = (Funcs.GetPOS(EntityType.PCMob, Axis.X, 0) > waypoint.x);

                Funcs.SetMoveStatus(WalkingStatus.Autorun | WalkingStatus.Running);

                if (decX)
                {
                    while (Funcs.GetPOS(EntityType.PCMob, Axis.X, 0) > waypoint.x)
                    {
                        if (HaltFlag)
                        {
                            Funcs.SetMoveStatus(WalkingStatus.Standing);
                            Moving = false;
                            return;
                        }
                        if (AICorrection)
                        {
                            heading = Funcs.GetHeading(EntityType.PCMob, 0);

                            tobeHeading = HeadingToRad(AllEntities.Get2DPos(), waypoint);

                            // Check if our heading is within our tolerance.
                            if (tobeHeading - heading < 0 ? tobeHeading - heading < -0.1f : tobeHeading - heading > 0.1f)
                                ModelRotation(waypoint);
                        }
                        Thread.Sleep(10);
                    }
                }
                else
                {
                    while (Funcs.GetPOS(EntityType.PCMob, Axis.X, 0) < waypoint.x)
                    {
                        if (HaltFlag)
                        {
                            Funcs.SetMoveStatus(WalkingStatus.Standing);
                            Moving = false;
                            return;
                        }
                        if (AICorrection)
                        {
                            heading = Funcs.GetHeading(EntityType.PCMob, 0);
                            tobeHeading = HeadingToRad(AllEntities.Get2DPos(), waypoint);

                            // Check if our heading is within our tolerance.
                            if (tobeHeading - heading < 0 ? tobeHeading - heading < -0.1f : tobeHeading - heading > 0.1f)
                                ModelRotation(waypoint);
                        }
                        Thread.Sleep(10);
                    }
                }
                if (log != null)
                    log.AppendTextP(string.Format("{0} {1} {2}\u2028", pathName, waypoint.x, waypoint.y));
            }
            Funcs.SetMoveStatus(WalkingStatus.Standing);
            Moving = false;
        }
Beispiel #39
0
 public void Waypoint(Pathing.NavMesh.Waypoint waypoint)
 {
     if (waypoint.Edge == null)
     {
         Seek(waypoint.OptimalPoint, seekDistance);
         return;
     }
     state = State.Waypoint;
     currentWaypoint = waypoint;
 }
        private void FindPath_Click(object sender, RoutedEventArgs e)
        {
            StartingPoint.State = NodeState.Open;

            foreach (var node in MainGrid.Children.OfType<Polygon>().Where(x => x.Fill == Brushes.LightGreen))
            {
                node.Fill = Brushes.White;
            }

            var path = new Pathing(Obstructions, 0, 0, 31, 31, 1).CreatePath(StartingPoint, EndingPoint);

            path.Remove(path.Where(x => x.X == StartingPoint.X && x.Y == StartingPoint.Y).FirstOrDefault());
            path.Remove(path.Where(x => x.X == EndingPoint.X && x.Y == EndingPoint.Y).FirstOrDefault());

            if (!path.Any())
                MessageBox.Show("Path Not Found");

            foreach (var item in path)
            {
                var currentX = (item.X * 20) + 1;
                var currentY = (item.Y * 20) + 1;

                MainGrid.Children.OfType<Polygon>().Where(x => x.Points.Where(y => y.X == currentX && y.Y == currentY).Any()).First().Fill = Brushes.LightGreen;
            }
        }
Beispiel #41
0
 /// <summary>   Plays the given file. </summary>
 ///
 ///
 /// <param name="pathName" type="string">       Full pathname of the file. </param>
 /// <param name="pType" type="Pathing">         The type. </param>
 /// <param name="forward" type="bool">          (Optional) true to forward. </param>
 /// <param name="index" type="int">             (Optional) zero-based index of the. </param>
 /// <param name="callback" type="SelfModify">   (Optional) the callback. </param>
 public void Play(string pathName, Pathing pType, bool forward = true, int index = 0, SelfModify callback = null)
 {
     new Thread(() =>
     {
         var halted = PlayPath(pathName, pType, forward, index, callback);
         if (PathComplete != null)
             PathComplete(Thread.CurrentThread, halted, pathName, pType, forward, index);
     }).Start();
 }
Beispiel #42
0
 public void Waypoint(Pathing.NavMesh.Waypoint waypoint)
 {
     #if(MOTION_NPC_CONSOLE_OUTPUT)
     Console.WriteLine("Motion: Waypoint");
     #endif
     if (waypoint.Edge == null)
     {
         Seek(waypoint.OptimalPoint);
         return;
     }
     state = State.Waypoint;
     this.waypoint = waypoint;
     npc.RunVelocity = Math.ToVector2(Vector2.Normalize(Math.ToVector2(waypoint.OptimalPoint - npc.Position))) * npc.MaxSpeed;
     if (npc.ZombieMoveCallback != null)
         npc.ZombieMoveCallback(waypoint.OptimalPoint);
 }
Beispiel #43
0
        private bool PlayPath(string pathName, Pathing pType, bool forawrd, int index, SelfModify callback = null)
        {
            if (!_mut.WaitOne(1000))
            {
                Console.WriteLine("Asynchronous action taken on synchronic function.");
                return true;
            }

            var zoneId = Funcs.GetZoneId();
            HaltFlag = false;
            float heading;
            float tobeHeading;
            var count = 0;
            var rebuiltPath =
                RebuildList(_Waypoints.Zone.First(p => p.ID == zoneId).Path.First(i => i.Name == pathName).Point,
                    forawrd, pType, index);
            foreach (
                var waypoint in rebuiltPath)
            {
                if (callback != null)
                    callback(pathName, waypoint, forawrd);

                if (CorDelay)
                    Bolter.GlobalInterface.GlobalMovement.Status = WalkingStatus.Standing;

                RotateCharacter(waypoint);

                if (CamReset)
                    Bolter.GlobalInterface.GlobalInput.SendKeyPress(KeyStates.Toggled, Key.End);

                if (CorDelay)
                    Thread.Sleep(HeadToll);

                var decX = (Funcs.GetPOS(EntityType.PCMob, Axis.X, 0) > waypoint.x);

                var ttl = (long)(1000f * (Distance(Funcs.Get2DPos(), waypoint) / Bolter.GlobalInterface.GlobalMovement.ForwardSpeed));

                Bolter.GlobalInterface.GlobalMovement.Status = WalkingStatus.Autorun | WalkingStatus.Running;
                var timer = new Stopwatch();
                timer.Start();
                if (decX)
                {
                    while (Funcs.GetPOS(EntityType.PCMob, Axis.X, 0) > waypoint.x)
                    {
                        if (HaltFlag)
                        {
                            Bolter.GlobalInterface.GlobalMovement.Status = WalkingStatus.Standing;
                            timer.Stop();
                            goto CleanUpTrue;
                        }
                        if (AICorrection)
                        {
                            heading = Funcs.GetHeading(EntityType.PCMob, 0);

                            tobeHeading = HeadingToRad(Funcs.GetPOS(EntityType.PCMob, Axis.X, 0), Funcs.GetPOS(EntityType.PCMob, Axis.Y, 0), waypoint);

                            // Check if our heading is within our tolerance.
                            if (tobeHeading - heading < 0 ? tobeHeading - heading < -0.1f : tobeHeading - heading > 0.1f)
                                RotateCharacter(waypoint);
                        }
                        Thread.Sleep(10);
                        if (timer.ElapsedMilliseconds <= ttl + JumpTolerance) continue;
                        if (waypoint.Jump == false) continue;
                        if ((waypoint.Direction == PointDirection.Forward && forawrd) || (waypoint.Direction == PointDirection.Back && !forawrd) || (waypoint.Direction == PointDirection.Both))
                            Bolter.GlobalInterface.GlobalInput.SendKeyPress(KeyStates.Toggled, Key.Space);
                    }
                }
                else
                {
                    while (Funcs.GetPOS(EntityType.PCMob, Axis.X, 0) < waypoint.x)
                    {
                        if (HaltFlag)
                        {
                            Bolter.GlobalInterface.GlobalMovement.Status = WalkingStatus.Standing;
                            timer.Stop();
                            goto CleanUpTrue;
                        }
                        if (AICorrection)
                        {
                            heading = Funcs.GetHeading(EntityType.PCMob, 0);
                            tobeHeading = HeadingToRad(Funcs.GetPOS(EntityType.PCMob, Axis.X, 0), Funcs.GetPOS(EntityType.PCMob, Axis.Y, 0), waypoint);

                            // Check if our heading is within our tolerance.
                            if (tobeHeading - heading < 0 ? tobeHeading - heading < -0.1f : tobeHeading - heading > 0.1f)
                                RotateCharacter(waypoint);
                        }
                        Thread.Sleep(10);
                        if (timer.ElapsedMilliseconds <= ttl + JumpTolerance) continue;
                        if (waypoint.Jump == false) continue;
                        if ((waypoint.Direction == PointDirection.Forward && forawrd) || (waypoint.Direction == PointDirection.Back && !forawrd) || (waypoint.Direction == PointDirection.Both))
                            Bolter.GlobalInterface.GlobalInput.SendKeyPress(KeyStates.Toggled, Key.Space);
                    }
                }
                count++;
                timer.Stop();
            }
            Bolter.GlobalInterface.GlobalMovement.Status = WalkingStatus.Standing;
            _mut.ReleaseMutex();
            return false;
            CleanUpTrue:
            _mut.ReleaseMutex();
            return true;
        }
Beispiel #44
0
	private void CloneObjectAction(Pathing pathing)
	{
		SampleObject.NewSampleObject(pathing, -1, 1, 2);
	}
 public bool arePointsConnected(int level, Point origin, Point dest, Pathing.PathingPermission permission)
 {
     return pathNodes(level, origin, dest, permission).Count > 1;
 }
 //public Sprite(Type _type, int _ID, int _index, Rectangle _rect, Color _color, bool _fliph, bool _flipV, bool _awake, bool _visible,
 //              bool _collide, int _hitPoints, bool _mobile, float _vel, Vector2 _dir, bool _rotating, float _rotspd, float _totrot,
 //              float _scale, bool _animated, bool _awhilestop, bool _bounce, float _fps,
 //              Sprite.Pathing _pathing, int _pathX, int _pathY, int _pathspd, int _pathstart, bool _pathInert, float _timeDelay)
 //{
 //    spriteType = _type;
 //    textureID = _ID;
 //    textureIndex = _index;
 //    SpriteRectangle = _rect; //calls property to also set location
 //    tintColor = _color;
 //    IsFlippedHorizontally = _fliph;
 //    IsFlippedVertically = _flipV;
 //    isAwake = _awake;
 //    isVisible = _visible;
 //    isCollidable = _collide;
 //    hitPoints = _hitPoints;
 //    isMobile = _mobile;
 //    velocity = _vel;
 //    direction = _dir;
 //    isRotating = _rotating;
 //    rotationSpeed = _rotspd;
 //    totalRotation = _totrot;
 //    scale = _scale;
 //    isAnimated = _animated;
 //    isAnimatedWhileStopped = _awhilestop;
 //    isBounceAnimated = _bounce;
 //    animationFPS = _fps;
 //    pathing = _pathing;
 //    pathingRadiusX = _pathX;
 //    pathingRadiusY = _pathY;
 //    pathingSpeed = _pathspd;
 //    pathingPercentComplete = _pathstart;
 //    isPathingInertia = _pathInert;
 //    timeDelay = _timeDelay;
 //}
 public Sprite(Type _type, int _ID, int _index, Rectangle _rect, Color _color, bool _fliph, bool _flipV, int _hitPoints, float _totrot,
                       float _scale, Sprite.Pathing _pathing, int _pathX, int _pathY, int _pathspd, int _pathstart, bool _pathInert, float _timeDelay)
 {
     spriteType = _type;
     textureID = _ID;
     textureIndex = _index;
     SpriteRectangle = _rect; //calls property to also set location
     tintColor = _color;
     IsFlippedHorizontally = _fliph;
     if (!_fliph) IsFlippedVertically = _flipV;
     hitPoints = _hitPoints;
     totalRotation = _totrot;
     scale = _scale;
     pathing = _pathing;
     pathingRadiusX = _pathX;
     pathingRadiusY = _pathY;
     pathingSpeed = _pathspd;
     pathingPercentComplete = _pathstart;
     isPathingInertia = _pathInert;
     timeDelay = _timeDelay;
 }
Beispiel #47
0
        private IEnumerable<D3DXVECTOR2> RebuildList(IEnumerable<D3DXVECTOR2> pList, bool forward, Pathing pType, int index = 0)
        {
            var rPlist = new List<D3DXVECTOR2>(pList);

            if (!forward)
                rPlist.Reverse();

            int localIndex;

            if (pType == Pathing.Normal)
                localIndex = 0;
            else
                localIndex = pType == Pathing.At_Index ? index : GetClosestIndex(rPlist, AllEntities.Get2DPos());

            return rPlist.Skip(localIndex);
        }
Beispiel #48
0
 public void Play(string pathName, Pathing pType, bool forward = true, int index = 0, dynamic log = null)
 {
     new Thread(() => PlayPath(pathName, pType, forward, index, log)).Start();
 }