Exemplo n.º 1
0
    public override bool Evaluate(int compareValue, int op)
    {
        if (!IsActive)
        {
            return(false);
        }

        if (!IsForDurability)
        {
            int value = GetValue();

            return(StaticUtility.CompareIntWithOp(value, compareValue, op));
        }
        else
        {
            //get a list of all items with ItemID
            //see if any of them has durability percent greater than DurabilityPercent
            float               desiredDurabilityPercent = Convert.ToSingle(compareValue) / 100f;
            HumanCharacter      player = GameManager.Inst.PlayerControl.SelectedPC;
            List <GridItemData> items  = player.Inventory.FindItemsInBackpack(ItemID);
            foreach (GridItemData item in items)
            {
                float durability = item.Item.Durability / item.Item.MaxDurability;
                if (durability >= desiredDurabilityPercent)
                {
                    return(true);
                }
            }
        }

        return(false);
    }
        private bool FillGaps(int period, DateTime dateStart, string apiKey, ref List <List <AssetModel> > model, DirSwitcher switcher)
        {
            var difference    = period - CountArrElements(model);
            var requestsCount = Convert.ToInt32(difference / 100) + 1;
            var tmpDate       = dateStart;
            var tmpModelSet   = new List <List <AssetModel> >();
            var counter       = 0;

            while (requestsCount != 0)
            {
                counter++;
                var firstItemInModel = StaticUtility.TimeConverter(model.First().First().TimeClose);
                var dtMax            = tmpDate;

                if (firstItemInModel.Subtract(tmpDate).TotalMinutes > 60)
                {
                    dtMax = dtMax.AddHours(1);
                }
                var dtMin = dtMax.AddDays(-4);

                var url = BuildCoinUrl(apiUrl, coinName, dtMin.ToString("s"), dtMax.ToString("s"));
                switch (switcher)
                {
                case DirSwitcher.Auto:
                    if (!Build(url, apiKey, ref tmpModelSet, switcher))
                    {
                        return(false);
                    }
                    break;

                case DirSwitcher.Manual:
                    Build(url, apiKey, ref tmpModelSet, switcher);
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(switcher), switcher, null);
                }
                tmpDate = tmpDate.AddDays(-4);
                requestsCount--;
            }



            StaticUtility.AddRequestCount(counter);
            //manager.UpdateRequests(counter);

            if (!tmpModelSet.Any())
            {
                return(false);
            }

            var tmpCounterfForModel = CountArrElements(tmpModelSet);

            if (tmpCounterfForModel <= difference)
            {
                return(false);
            }
            model.Insert(0, (RemoveExcessFromEnd(period, tmpModelSet, model)));
            return(true);
        }
        public bool FillModel(string url, DateTime dtMin, DateTime dtMax, string apiKey, ref List <List <AssetModel> > modelSet, DirSwitcher switcher)
        {
            var counter = 0;

            while (dtMin < dtMax.AddDays(4))
            {
                var dateStartStr = dtMin.ToString("s");
                var dateEndStr   = dtMin.AddDays(4).ToString("s");
                var coinUrl      = BuildCoinUrl(url, coinName, dateStartStr, dateEndStr);
                switch (switcher)
                {
                case DirSwitcher.Auto:
                    if (!Build(coinUrl, apiKey, ref modelSet, switcher))
                    {
                        return(false);
                    }
                    break;

                case DirSwitcher.Manual:
                    Build(coinUrl, apiKey, ref modelSet, switcher);
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(switcher), switcher, null);
                }


                dtMin = dtMin.AddDays(4);
                counter++;
            }

            StaticUtility.AddRequestCount(counter);
            return(true);
            //manager.UpdateRequests(counter);
        }
Exemplo n.º 4
0
    private void HandleMoveStateCloseJoust()
    {
        if (_targetDist > (float)MyAI.Whiteboard.Parameters["EnemyCloseRange"])
        {
            ChangeState(MoveStates.LongRange);
            return;
        }


        if (_targetFacingAngle <= 120)
        {
            ChangeState(MoveStates.CloseChase);
            return;
        }

        if (_evadeDir == Vector3.zero)
        {
            _evadeDir = StaticUtility.FindEvadeDirWithTarget(MyAI.MyShip, _target.transform.position, 0.4f);
            if (Vector3.Angle(MyAI.RB.velocity, _target.transform.position - MyAI.MyShip.transform.position) > 145)
            {
                MyAI.Whiteboard.Parameters["IsEngineKilled"] = true;
            }
            MyAI.Whiteboard.Parameters["Destination"] = MyAI.MyShip.transform.position + _evadeDir * 30f;
        }

        Debug.DrawRay(MyAI.MyShip.transform.position, _evadeDir.normalized * 10, Color.red);
        MyAI.Whiteboard.Parameters["EvadeDir"]  = _evadeDir;
        MyAI.Whiteboard.Parameters["AimTarget"] = _target;
    }
Exemplo n.º 5
0
        public IActionResult GetForecastData(Indicator indicator, string assetName, int periods)
        {
            var viewModel = new MainViewModel();

            var manager = new DirectoryManager(_appSettings, currentLocation);
            var folder  = manager.GetLastFolder(DirSwitcher.Auto);

            try
            {
                string indicatorDir;
                string dir;
                switch (indicator)
                {
                case Indicator.Positive:
                    indicatorDir = manager.DirPositive;
                    dir          = Path.Combine(folder, indicatorDir);
                    break;

                case Indicator.Neutral:
                    indicatorDir = manager.DirNeutral;
                    dir          = Path.Combine(folder, indicatorDir);
                    break;

                case Indicator.Negative:
                    indicatorDir = manager.DirNegative;
                    dir          = Path.Combine(folder, indicatorDir);
                    break;

                case Indicator.StrongPositive:
                    indicatorDir = manager.DirStrongPositive;
                    dir          = Path.Combine(folder, indicatorDir);
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(indicator), indicator, null);
                }

                var targetFolder           = DirectoryManager.GetForecastFolderByName(dir, assetName);
                var pathToOut              = Path.Combine(dir, targetFolder, manager.OutFile);
                var pathToComponentsForImg = Path.Combine(_appSettings.Value.ForecastDir, manager.DirForImages(DirSwitcher.Auto), indicatorDir, targetFolder, manager.OutComponents);
                var pathToForecastForImg   = Path.Combine(_appSettings.Value.ForecastDir, manager.DirForImages(DirSwitcher.Auto), indicatorDir, targetFolder, manager.OutForecast);

                viewModel.ComponentsPath = Path.DirectorySeparatorChar + pathToComponentsForImg;
                viewModel.ForecastPath   = Path.DirectorySeparatorChar + pathToForecastForImg;
                viewModel.RequestsPerDay = manager.GetRequestCount();
                viewModel.AssetName      = assetName;
                viewModel.Indicator      = indicator;
                viewModel.Table          = StaticUtility.BuildOutTableRows(pathToOut, periods);
            }
            catch (Exception e)
            {
                return(NotFound(new { message = e.Message }));
            }


            return(Json(viewModel));
        }
    public override bool Evaluate(int compareValue, int op)
    {
        if (!IsActive)
        {
            return(false);
        }

        int value = GetValue();

        //Debug.Log("eval condition current value " + _value + " against " + compareValue);
        return(StaticUtility.CompareIntWithOp(value, compareValue, op));
    }
Exemplo n.º 7
0
    protected void UpdateAvoidance()
    {
        AvoidanceDetector.AvoidanceUpdate();
        if (AvoidanceDetector.Avoidance != Vector3.zero)
        {
            float cap      = 30;
            float maxValue = StaticUtility.GetMaxElementV3(AvoidanceDetector.Avoidance);
            float forceMag = 5f + 10f * Mathf.Clamp01(maxValue / 30);

            Vector3 force1 = (AvoidanceDetector.transform.position - AvoidanceDetector.RaySource1.position).normalized * (AvoidanceDetector.Avoidance.x / maxValue);
            Vector3 force2 = (AvoidanceDetector.transform.position - AvoidanceDetector.RaySource2.position).normalized * (AvoidanceDetector.Avoidance.y / maxValue);
            Vector3 force3 = (AvoidanceDetector.transform.position - AvoidanceDetector.RaySource3.position).normalized * (AvoidanceDetector.Avoidance.z / maxValue);
            Vector3 force4 = Vector3.zero;

            if (AvoidanceDetector.Avoidance.x > cap && AvoidanceDetector.Avoidance.y > cap && AvoidanceDetector.Avoidance.z > cap)
            {
                force4 = (RB.velocity * -1).normalized;
            }

            _avoidanceForce = forceMag * (force1 + force2 + force3 + force4).normalized;
        }
        else
        {
            _avoidanceForce = Vector3.zero;
        }

        //check if any ships are too close to me
        float thres     = 5f;
        float magnitude = 6f;

        if (AvoidanceDetector.State == AvoidanceState.Combat)
        {
            thres     = 10f;
            magnitude = 15f;
        }

        foreach (ShipBase ship in GameManager.Inst.NPCManager.AllShips)
        {
            if (ship == GameManager.Inst.PlayerControl.PlayerShip || ship.MyAI.IsActive)
            {
                Vector3 dist = ship.transform.position - MyShip.transform.position;

                if (dist.magnitude < thres)
                {
                    _avoidanceForce += Vector3.Lerp(dist.normalized * -1 * magnitude, Vector3.zero, (dist.magnitude / thres));
                }
            }
        }
        //Debug.DrawRay(MyShip.transform.position, _avoidanceForce, Color.green);
    }
Exemplo n.º 8
0
    private void UpdatePipPosition()
    {
        if (GameManager.Inst.PlayerControl.TargetShip != null)
        {
            float targetshipAngle = Vector3.Angle(Camera.main.transform.forward, (GameManager.Inst.PlayerControl.TargetShip.transform.position - Camera.main.transform.position));
            if (targetshipAngle > 50)
            {
                Pip.alpha = 0;
            }
            else
            {
                ShipBase target   = GameManager.Inst.PlayerControl.TargetShip;
                ShipBase myShip   = GameManager.Inst.PlayerControl.PlayerShip;
                Vector3  aimPoint = StaticUtility.FirstOrderIntercept(myShip.transform.position, myShip.RB.velocity,
                                                                      50, target.transform.position, target.RB.velocity);
                Vector3 viewPos   = GameManager.Inst.UIManager.UICamera.WorldToViewportPoint(aimPoint);
                Vector3 screenPos = GameManager.Inst.UIManager.UICamera.ViewportToScreenPoint(viewPos);
                //float multiplier = 1;//(float)GameManager.Inst.UIManager.Root.manualHeight / (float)Screen.height;


                //Pip.transform.OverlayPosition(aimPoint, GameManager.Inst.MainCamera, GameManager.Inst.UIManager.UICamera);
                //Vector3 overlay = NGUIMath.WorldToLocalPoint(aimPoint, GameManager.Inst.MainCamera, GameManager.Inst.UIManager.UICamera, Pip.transform);
                Vector3 overlay = Camera.main.WorldToScreenPoint(aimPoint);
                overlay = new Vector3(overlay.x - Screen.width / 2f, overlay.y - Screen.height / 2f, 0) * 0.65f;
                Pip.transform.localPosition = GameManager.Inst.UIManager.GetTargetScreenPos(aimPoint);
                Pip.alpha = 1f;

                if (Vector3.Distance(aimPoint, GameManager.Inst.PlayerControl.PlayerShip.transform.position) > GameManager.Inst.PlayerControl.PlayerShip.GetMaxWeaponRange())
                {
                    PipCenter.alpha = 0;
                }
                else
                {
                    PipCenter.alpha = 1;
                }

                if (_currentSelectMarker != null)
                {
                    Vector3    los = _currentSelectMarker.Marker.transform.localPosition - Pip.transform.localPosition;
                    Quaternion rot = Quaternion.FromToRotation(PipLine.transform.right, los);
                    PipLine.transform.rotation = rot * PipLine.transform.rotation;
                    PipLine.width = (int)(los.magnitude);
                }
            }
        }
        else
        {
            Pip.alpha = 0;
        }
    }
Exemplo n.º 9
0
    private bool IsViewInBoundary(Transform camera, out Vector3 lookAheadPos, out float overDistance)
    {
        Vector3 los           = camera.forward;
        Vector3 flatCamPos    = new Vector3(camera.position.x, 0, camera.position.z);
        Vector2 flatLoS       = new Vector3(los.x, los.z).normalized;
        float   distViewPoint = camera.position.y * Mathf.Tan((90 - camera.localEulerAngles.x) * Mathf.Deg2Rad);
        Vector2 viewPoint     = distViewPoint * flatLoS + new Vector2(camera.position.x, camera.position.z);

        lookAheadPos = camera.position;
        overDistance = 0;

        bool isCamOutside = false;

        if (!StaticUtility.ContainsPoint(_boundaryPoints, new Vector2(camera.position.x, camera.position.z)))
        {
            isCamOutside = true;
        }

        Vector3 borderPoint;
        bool    isInside = false;

        if (isCamOutside)
        {
            Vector3 playerPos = GameManager.Inst.PlayerControl.SelectedPC.transform.position;
            isInside = StaticUtility.ContainsPoint(_boundaryPoints, viewPoint, playerPos, out borderPoint);

            if (!isInside)
            {
                Vector3 borderDist = new Vector3(viewPoint.x, 0, viewPoint.y) - flatCamPos;
                lookAheadPos = borderPoint - borderDist.normalized * distViewPoint + new Vector3(0, camera.position.y, 0);
                overDistance = 10;
            }
        }
        else
        {
            isInside = StaticUtility.ContainsPoint(_boundaryPoints, viewPoint, camera.position, out borderPoint);

            if (!isInside)
            {
                Vector3 borderDist = borderPoint - flatCamPos;
                lookAheadPos = borderPoint - borderDist.normalized * distViewPoint + new Vector3(0, camera.position.y, 0);
                overDistance = (viewPoint - new Vector2(borderPoint.x, borderPoint.z)).magnitude;
            }
        }



        return(isInside);
    }
Exemplo n.º 10
0
    private void HandleStateTooClose()
    {
        if (_targetDist >= (float)MyAI.Whiteboard.Parameters["MinEnemyRange"] * 1.5f)
        {
            ChangeState(MoveStates.LongRange);
            return;
        }

        if (_evadeDir == Vector3.zero)
        {
            _evadeDir = StaticUtility.FindEvadeDirWithTarget(MyAI.MyShip, _target.transform.position, 0.4f);
        }
        MyAI.Whiteboard.Parameters["IsThrusting"] = true;
        MyAI.Whiteboard.Parameters["Destination"] = MyAI.MyShip.transform.position + _evadeDir * 30f;
        MyAI.Whiteboard.Parameters["EvadeDir"]    = _evadeDir;
        MyAI.Whiteboard.Parameters["AimTarget"]   = null;
    }
        private static bool Build(string url, string key, ref List <List <AssetModel> > modelSet, DirSwitcher switcher)
        {
            var response            = StaticUtility.GenerateRestUrl(url, key);
            List <AssetModel> model = null;

            switch (switcher)
            {
            case DirSwitcher.Auto:
                if (response.StatusDescription == "OK")
                {
                    model = JsonConvert.DeserializeObject <List <AssetModel> >(response.Content);
                    if (model.Any())
                    {
                        modelSet.Add(model);
                    }
                }
                else
                {
                    return(false);
                }
                break;

            case DirSwitcher.Manual:
                if (response.StatusDescription != "OK")
                {
                    throw new Exception(response.Content);
                }
                model = JsonConvert.DeserializeObject <List <AssetModel> >(response.Content);
                if (model.Any())
                {
                    modelSet.Add(model);
                    return(true);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(switcher), switcher, null);
            }

            return(true);
        }
Exemplo n.º 12
0
    private void HandleMoveStateLongRange()
    {
        if (_targetDist <= (float)MyAI.Whiteboard.Parameters["EnemyCloseRange"])
        {
            if (_targetFacingAngle > 120)
            {
                ChangeState(MoveStates.CloseJoust);
                return;
            }
            else
            {
                ChangeState(MoveStates.CloseChase);
                return;
            }
        }


        //strafe left and right
        if (_timer > 2)
        {
            float strafeForce = (float)MyAI.Whiteboard.Parameters["StrafeForce"];
            if (strafeForce == 0)
            {
                strafeForce = (2 + UnityEngine.Random.value * 3) * StaticUtility.FlipCoin();
            }
            else
            {
                strafeForce *= -1;
            }
            _timer = 0;
        }
        MyAI.Whiteboard.Parameters["IsThrusting"] = true;
        MyAI.Whiteboard.Parameters["AimTarget"]   = _target;
        //set destination to target
        MyAI.Whiteboard.Parameters["Destination"] = _target.transform.position;
    }
Exemplo n.º 13
0
        public void RepairMonster(PlayerData player, int reference)
        {
            PartData part = player.Monster.Parts[reference];

            int full = 2;

            switch (part.PartRarity)
            {
            case 0:
                full = 1000;
                break;

            case 1:
                full = 500;
                break;

            case 2:
                full = 200;
                break;

            case 3:
                full = 100;
                break;

            case 4:
                full = 50;
                break;

            case 5:
                full = 10;
                break;

            default:
                throw new Exception("Cannot Repair Unknown PartRarity");
            }

            int cost = ((Int32)((1 - part.PartDurability) * 100) * full) / 100;

            if (cost < 0)
            {
                cost = 0;
            }
            int intInput = 1;

            if (!player.IsAI)
            {
                Console.WriteLine("Full repair will cost " + cost + " " + StaticReference.structureList[part.PartStructure] + " parts. You currently have " + player.ComponentList[part.PartStructure] + ".");
                Console.WriteLine("Confirm repair?");
                Console.WriteLine("1 - Yes");
                Console.WriteLine("2 - No");
                intInput = StaticUtility.CheckInput(1, 2);
            }
            if (intInput == 1)
            {
                if (cost <= player.ComponentList[part.PartStructure])
                {
                    player.ComponentList[part.PartStructure] = player.ComponentList[part.PartStructure] - cost;
                    part.PartDurability = 1;
                }
                else
                {  //This could be stated in two lines, but this was easier to debug
                    decimal percentage = ((decimal)player.ComponentList[part.PartStructure] / cost);
                    decimal remaining  = (1 - part.PartDurability);
                    part.PartDurability += remaining * percentage;
                    player.ComponentList[part.PartStructure] = 0;
                }

                if (!player.IsAI)
                {
                    Console.WriteLine(part.PartName + " is now at " + part.PartDurability + " durability.");
                    Console.WriteLine("You now have " + player.ComponentList[part.PartStructure] + " " + StaticReference.structureList[part.PartStructure] + " parts.");
                }
            }
        }
Exemplo n.º 14
0
    // Update is called once per frame
    public void PerFrameUpdate()
    {
        Vector3 playerPos = GameManager.Inst.PlayerControl.PlayerShip.transform.position;

        if (StaticUtility.IsInArea(playerPos, transform.position, new Vector3(Size.x / 2 + 0.5f, Size.y / 2 + 0.5f, Size.z / 2 + 0.5f) * CellSize))
        {
            List <Vector3> nearestCoords = FindNearestCellCoords();
            foreach (Vector3 coord in nearestCoords)
            {
                Vector3 cellPos = transform.position + coord * CellSize;

                if (!IsCoordTaken(cellPos) && Mathf.Abs(coord.x * 2) <= Size.x && Mathf.Abs(coord.y * 2) <= Size.y && Mathf.Abs(coord.z * 2) <= Size.z)
                {
                    AsteroidCell cell = GetAvailableCell(playerPos);
                    if (cell != null)
                    {
                        cell.transform.position = cellPos;
                    }
                }
            }
        }
        else
        {
            List <Vector3> edgeCoords    = FindHorizontalEdgeCoords();
            Vector3        centerCellPos = edgeCoords[0] * CellSize + transform.position;
            int            cellIndex     = 0;
            foreach (Vector3 coord in edgeCoords)
            {
                Vector3 cellPos = transform.position + coord * CellSize;

                //check if the coord is along the edge of the field
                if (!IsCoordTaken(cellPos) && IsCoordOnEdge(coord))
                {
                    //Debug.Log(coord);
                    AsteroidCell cell = _cells[cellIndex];
                    if (cell != null && cellIndex <= 9)
                    {
                        cell.transform.position = cellPos;
                        cellIndex++;
                    }
                }
            }
        }

        //check how close player is to the border to calculate a value between 0 and 1
        //to set fog intensity, fog color, and sun flare size
        _gradient = 0;


        Vector3 playerDist = playerPos - transform.position;

        if (StaticUtility.IsInArea(playerPos, transform.position, new Vector3(Size.x * CellRadius - FogStart, Size.y * CellRadius - FogStart, Size.z * CellRadius - FogStart)))
        {
            _gradient = 1;
        }
        else
        {
            if (Mathf.Abs(playerDist.x) > Size.x * CellRadius - FogStart)
            {
                _gradient = Mathf.Clamp01((Size.x * CellRadius - Mathf.Abs(playerDist.x)) / FogStart);
            }
            else if (Mathf.Abs(playerDist.y) > Size.y * CellRadius - FogStart)
            {
                _gradient = Mathf.Clamp01((Size.y * CellRadius - Mathf.Abs(playerDist.y)) / FogStart);
            }
            else if (Mathf.Abs(playerDist.z) > Size.z * CellRadius - FogStart)
            {
                _gradient = Mathf.Clamp01((Size.z * CellRadius - Mathf.Abs(playerDist.z)) / FogStart);
            }
        }



        //set fog intensity
        RenderSettings.fogDensity = Mathf.Lerp(0.0002f, FogIntensity, _gradient);
        RenderSettings.fogColor   = Color.Lerp(new Color(0.01f, 0.015f, 0.02f, 1f), FogColor, _gradient);

        //set sun intensity
        foreach (Sun sun in GameManager.Inst.WorldManager.CurrentSystem.Suns)
        {
            if (sun.Flare != null)
            {
                sun.Flare.brightness = Mathf.Lerp(0.6f, 0, _gradient);
            }

            sun.Sunlight.intensity = Mathf.Lerp(1, SunIntensity, _gradient);
        }

        //set ambient
        RenderSettings.ambientLight = Color.Lerp(GameManager.Inst.WorldManager.CurrentSystem.AmbientColor, AmbientColor, _gradient);
    }
 public override bool checkProceduralPrecondition(AiController controller)
 {
     tempVector = StaticUtility.GetRandomRadialPos(transform, wanderRadius);
     return(true);
 }
Exemplo n.º 16
0
 /// <summary>
 /// Initialize base data from a scriptable object if one is available .
 /// </summary>
 private void InitializeBaseObjectData()
 {
     baseObjectInfo = baseData != null ? new BaseObjectData(StaticUtility.GenerateUniqueHashId(), baseData.objectName, baseData.description, baseData.spriteTexture)
         : new BaseObjectData(StaticUtility.GenerateUniqueHashId(), "", "", null); //should generate random base stats, maybe
 }
Exemplo n.º 17
0
    public override Damage ProcessDamage(Damage damage)
    {
        Damage processedDamage = new Damage();

        processedDamage.DamageType  = damage.DamageType;
        processedDamage.HitLocation = damage.HitLocation;


        float shieldFill = Amount / TotalCapacity;

        if (shieldFill > 0.2f)
        {
            if (ParentShip != GameManager.Inst.PlayerControl.PlayerShip)
            {
                //show shield flash
                this.MyRenderer         = this.GetComponent <MeshRenderer>();
                this.MyRenderer.enabled = true;
                _shieldFlashTimer       = 0;
            }
            else
            {
                _fadeAlpha = Mathf.Clamp01(_fadeAlpha + 0.1f);
            }

            //load shield hit mark
            GameObject hitMark = GameObject.Instantiate(Resources.Load("ShieldHitMark" + this.GetShieldHitEffectNumber())) as GameObject;
            hitMark.transform.position = damage.HitLocation;
            Quaternion lookRotation = Quaternion.LookRotation(damage.HitLocation - transform.position);
            hitMark.transform.rotation = lookRotation;
            hitMark.transform.parent   = transform;
        }

        //get multiplier
        float multiplier      = StaticUtility.GetShieldDamageMultiplier(this.Tech, damage.DamageType);
        float powerMultiplier = 1 / ParentShip.ShieldPowerAlloc;

        Amount = Mathf.Clamp(Amount - damage.ShieldAmount * multiplier * powerMultiplier, 0, TotalCapacity);
        //Debug.Log(multiplier + ", " + damage.ShieldAmount + ", " + Amount);

        float damageEval = 1;

        if (Amount > TotalCapacity * 0.1f)
        {
            if (damage.DamageType == DamageType.Shock)
            {
                damageEval = 0.6f;
            }
            else
            {
                damageEval = 0;
            }
        }
        else if (Amount > 0)
        {
            if (damage.DamageType == DamageType.Shock)
            {
                damageEval = 1;
            }
            else
            {
                damageEval = Mathf.Clamp01(1 - Amount / (TotalCapacity * 0.1f));
            }
        }
        else
        {
            damageEval = 1;
        }

        processedDamage.ShieldAmount = 0;
        processedDamage.HullAmount   = damageEval * damage.HullAmount;

        return(processedDamage);
    }
Exemplo n.º 18
0
    public override Damage ProcessDamage(Damage damage)
    {
        Damage processedDamage = new Damage();

        processedDamage.DamageType  = damage.DamageType;
        processedDamage.HitLocation = damage.HitLocation;


        /*
         * bool isFront = true;
         *
         * float hitAngle = Vector3.Angle((damage.HitLocation - transform.position), transform.forward);
         * if(hitAngle <= 90)
         * {
         *      shieldFill = FrontAmount / FrontCapacity;
         * }
         * else
         * {
         *      isFront = false;
         *      shieldFill = RearAmount / RearCapacity;
         * }
         */
        float shieldFill = 0;

        if (TotalCapacity > 0)
        {
            shieldFill = Amount / TotalCapacity;
        }

        if (shieldFill > 0.2f)
        {
            if (ParentShip != GameManager.Inst.PlayerControl.PlayerShip)
            {
                //show shield flash
                this.MyRenderer         = this.GetComponent <MeshRenderer>();
                this.MyRenderer.enabled = true;
                _shieldFlashTimer       = 0;
            }
            else
            {
                _fadeAlpha = Mathf.Clamp01(_fadeAlpha + 0.1f);
            }

            //load shield hit mark
            GameObject hitMark = GameObject.Instantiate(Resources.Load("ShieldHitMark" + this.GetShieldHitEffectNumber())) as GameObject;
            hitMark.transform.position = damage.HitLocation;
            Quaternion lookRotation = Quaternion.LookRotation(damage.HitLocation - transform.position);
            hitMark.transform.rotation = lookRotation;
            hitMark.transform.parent   = transform;
        }

        //get multiplier
        float multiplier      = StaticUtility.GetShieldDamageMultiplier(this.Tech, damage.DamageType);
        float powerMultiplier = 1 / ParentShip.ShieldPowerAlloc;

        Amount = Mathf.Clamp(Amount - damage.ShieldAmount * multiplier * powerMultiplier, 0, TotalCapacity);

        //float totalAmount = FrontAmount + RearAmount;
        //float frontPortion = FrontCapacity / TotalCapacity;
        //totalAmount = Mathf.Clamp(totalAmount - damage.ShieldAmount * multiplier, 0, TotalCapacity);
        //FrontAmount = totalAmount * frontPortion;
        //RearAmount = totalAmount * (1 - frontPortion);

        /*
         * if(isFront)
         * {
         *      FrontAmount = Mathf.Clamp(FrontAmount - damage.ShieldAmount * multiplier, 0, FrontCapacity);
         * }
         * else
         * {
         *      RearAmount = Mathf.Clamp(RearAmount - damage.ShieldAmount * multiplier, 0, RearCapacity);
         * }
         */

        float damageEval = 1;

        if (damage.DamageType == DamageType.Shock)
        {
            damageEval = 1f;
        }
        else
        {
            if (ParentShip != GameManager.Inst.PlayerControl.PlayerShip)
            {
                damageEval = Mathf.Clamp01(GameManager.Inst.Constants.ShieldProtectionCurve.Evaluate(shieldFill));
            }
            else
            {
                GameManager.Inst.CameraShaker.TriggerScreenShake(0.07f, 0.015f, false);
                damageEval = Mathf.Clamp01(GameManager.Inst.Constants.PlayerShieldProtectionCurve.Evaluate(shieldFill));
            }
        }

        processedDamage.ShieldAmount = 0;
        processedDamage.HullAmount   = damageEval * damage.HullAmount;

        return(processedDamage);
    }
Exemplo n.º 19
0
    protected void Turn()
    {
        if (MyShip.IsInPortal)
        {
            MyShip.RB.angularVelocity = Vector3.zero;
            return;
        }

        Vector3  dest      = (Vector3)Whiteboard.Parameters["Destination"];
        ShipBase aimTarget = (ShipBase)Whiteboard.Parameters["AimTarget"];

        Vector3 aimPoint = Vector3.zero;
        Vector3 aimDir   = MyShip.transform.forward;
        float   turnRate = 1.5f;

        if (aimTarget != null)
        {
            aimPoint = StaticUtility.FirstOrderIntercept(MyShip.transform.position, MyShip.RB.velocity,
                                                         30, aimTarget.transform.position, aimTarget.RB.velocity);
        }
        else
        {
            if (RB.velocity.magnitude > 3f)
            {
                aimPoint = (Vector3)Whiteboard.Parameters["InterceptDest"];
            }
        }


        Whiteboard.Parameters["AimPoint"] = aimPoint;
        //Debug.Log("aimpoint " + aimPoint + " " + MyShip.name + " dest " + dest);
        Vector3 distToDest = dest - MyShip.transform.position;

        if (aimPoint != Vector3.zero)
        {
            //Quaternion rotation = Quaternion.LookRotation(aimPoint - MyShip.transform.position);
            //transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.deltaTime * turnRate);
            //Debug.Log("AI Turn state 1 " + MyShip.name);
            AddLookTorque(aimPoint - MyShip.transform.position);

            if (Vector3.Angle(aimPoint - MyShip.transform.position, MyShip.transform.forward) < 20)
            {
                aimDir = aimPoint - MyShip.transform.position;
            }
        }
        else if (dest != Vector3.zero && distToDest.magnitude > 5)
        {
            //Quaternion rotation = Quaternion.LookRotation(dest - MyShip.transform.position);
            //transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.deltaTime * turnRate);
            //Debug.Log("AI Turn state 2 " + MyShip.name);
            AddLookTorque(distToDest);
        }
        else
        {
            Vector3 velocity = RB.velocity;
            if (RB.velocity.magnitude > 1)
            {
                //Quaternion rotation = Quaternion.LookRotation(velocity);
                //transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.deltaTime * 2f);
                //Debug.Log("AI Turn state 3 " + MyShip.name);
                AddLookTorque(velocity);
            }
            else
            {
                //Debug.Log("AI Turn state 4 " + MyShip.name);
                AddLookTorque(MyParty.SpawnedShipsLeader.transform.forward);
            }
        }

        //aim guns at target
        if (aimPoint != Vector3.zero)
        {
            foreach (WeaponJoint joint in MyShip.MyReference.WeaponJoints)
            {
                joint.TargetPos = aimPoint + _aimError;
            }
        }

        /*
         * Fighter fighter = (Fighter)MyShip;
         * fighter.LeftGun.transform.rotation = Quaternion.LookRotation(aimDir);
         * fighter.RightGun.transform.rotation = Quaternion.LookRotation(aimDir);
         */
    }
Exemplo n.º 20
0
    void Update()
    {
        if ((ControlMode == TurretControlMode.Automatic || ControlMode == TurretControlMode.Selected) && MountedWeapon != null &&
            MountedWeapon.RotationType == WeaponRotationType.Turret && ParentShip.DockedStationID == "" && !ParentShip.IsInPortal)
        {
            UpdateTarget();
            if (Target != null && !ParentShip.Engine.IsCruising)
            {
                MountedWeapon.Fire();
            }
        }

        if (MountedWeapon != null)
        {
            if (MountedWeapon.RotationType == WeaponRotationType.Turret && (ControlMode == TurretControlMode.Automatic || ControlMode == TurretControlMode.Selected))
            {
                if (Target != null)
                {
                    Vector3 targetVelocity = Vector3.zero;
                    if (transform.GetComponent <Rigidbody>() != null)
                    {
                        targetVelocity = transform.GetComponent <Rigidbody>().velocity;
                    }
                    TargetPos = StaticUtility.FirstOrderIntercept(ParentShip.transform.position, ParentShip.RB.velocity,
                                                                  50, Target.position, targetVelocity);
                }
                else if (MountedWeapon.TurretBase != null)
                {
                    //TargetPos = transform.position + transform.forward * 100;
                }
            }

            Vector3 lookDir = TargetPos - MountedWeapon.transform.position;

            if (MountedWeapon.RotationType == WeaponRotationType.Gimball)
            {
                Vector3 verticalLos = lookDir - (transform.forward * 100);
                float   angle       = Vector3.Angle(lookDir, transform.forward);
                if (angle > MountedWeapon.GimballMax * GimballLimitPercent)
                {
                    verticalLos = verticalLos.normalized * (Mathf.Tan(Mathf.Deg2Rad * MountedWeapon.GimballMax * GimballLimitPercent) * 100);
                    Vector3 newTarget = transform.position + transform.forward * 100 + verticalLos;
                    lookDir = newTarget - MountedWeapon.transform.position;
                }

                Quaternion rotation = Quaternion.LookRotation(lookDir, transform.up);
                MountedWeapon.Barrel.transform.rotation = Quaternion.Lerp(MountedWeapon.Barrel.transform.rotation, rotation, Time.deltaTime * 9);
            }
            else if (MountedWeapon.RotationType == WeaponRotationType.Turret)
            {
                Vector3    baseLookDir  = Vector3.ProjectOnPlane(lookDir, transform.up);
                Quaternion baseRotation = Quaternion.LookRotation(baseLookDir, transform.up);

                Vector3 barrelLookDir = Vector3.ProjectOnPlane(lookDir, MountedWeapon.TurretBase.transform.right);
                Vector3 verticalLos   = lookDir - (transform.up * 100);
                float   angle         = Vector3.Angle(lookDir, transform.up);
                if (angle > MountedWeapon.GimballMax)
                {
                    //verticalLos = verticalLos.normalized * (Mathf.Tan(Mathf.Deg2Rad * GimballMax * GimballLimitPercent) * 100);
                    //Vector3 newTarget = transform.position + transform.up * 100 + verticalLos;
                    //barrelLookDir = newTarget - MountedWeapon.transform.position;
                    Vector3 flatDir = Vector3.ProjectOnPlane(lookDir, MountedWeapon.TurretBase.transform.up);
                    barrelLookDir = Vector3.ProjectOnPlane(flatDir, MountedWeapon.TurretBase.transform.right);
                }
                else if (angle < MountedWeapon.GimballMin)
                {
                    Vector3 flatDir = Vector3.ProjectOnPlane(lookDir, MountedWeapon.TurretBase.transform.up);
                    barrelLookDir = Vector3.ProjectOnPlane(flatDir, MountedWeapon.TurretBase.transform.right);
                    barrelLookDir = barrelLookDir / Mathf.Cos(Mathf.Deg2Rad * (MountedWeapon.GimballMax - MountedWeapon.GimballMin));
                }

                Quaternion barrelRotation = Quaternion.LookRotation(barrelLookDir, Vector3.Cross(barrelLookDir, MountedWeapon.TurretBase.transform.right) * -1);

                MountedWeapon.TurretBase.transform.rotation = Quaternion.Lerp(MountedWeapon.TurretBase.transform.rotation, baseRotation, Time.deltaTime * 6);
                MountedWeapon.Barrel.transform.rotation     = Quaternion.Lerp(MountedWeapon.Barrel.transform.rotation, barrelRotation, Time.deltaTime * 6);
            }
            else
            {
            }
        }
    }
Exemplo n.º 21
0
    void FixedUpdate()
    {
        if (_stage == MissileStage.Launched)
        {
            //if(_age > 0.3f)
            if (_age > LaunchedStageDuration)
            {
                _stage = MissileStage.Chasing;
                LoadEngineFlame();
                Collider collider = transform.GetComponent <Collider>();
                if (collider != null)
                {
                    collider.enabled = true;
                }
                AudioSource audio = GetComponent <AudioSource>();
                if (audio != null)
                {
                    audio.Play();
                }
            }
        }
        else if (_stage == MissileStage.Chasing)
        {
            if (Target == null)
            {
                _force = Acceleration;                //5f;
                _rigidbody.AddForce(transform.forward * _force);
            }
            else
            {
                Vector3 targetPos = Target.transform.position;
                if (Target.CurrentCountermeasure != null)
                {
                    CounterMeasureFlares flares = Target.CurrentCountermeasure.GetComponentInChildren <CounterMeasureFlares>();
                    if (flares != null && flares.IsEffective)
                    {
                        targetPos += flares.MissileDeviation;
                    }
                }

                Vector3 aimPoint = StaticUtility.FirstOrderIntercept(transform.position, _rigidbody.velocity,
                                                                     _rigidbody.velocity.magnitude, targetPos, Target.RB.velocity);
                Vector3 los = aimPoint - transform.position;

                if (Vector3.Angle(los, transform.forward) < 10)
                {
                    _force = Acceleration;                    //5f
                    //here we need to reduce torque so it stops turning
                }
                else
                {
                    //AddLookTorque(los);
                    Vector3 lookDir = Vector3.RotateTowards(transform.forward, los, 1f * Time.fixedDeltaTime, 0f);
                    transform.rotation = Quaternion.LookRotation(lookDir);
                    _force             = Acceleration * 0.6f;        //3f;
                }

                _rigidbody.AddForce(transform.forward * _force);
            }



            Vector3 driftVelocity = _rigidbody.velocity - Vector3.Dot(_rigidbody.velocity, transform.forward) * transform.forward;
            _rigidbody.AddForce(-1 * driftVelocity.normalized * driftVelocity.magnitude * TurnRate);
        }

        //keep under max speed
        if (_rigidbody.velocity.magnitude > MaxSpeed)
        {
            _rigidbody.AddForce(-1 * _rigidbody.velocity * 1);
        }

        if (_stage == MissileStage.Launched)
        {
            _rigidbody.AddForce(-1 * _rigidbody.velocity * 2.5f);
        }


        _age += Time.fixedDeltaTime;

        if (_age > TTL)
        {
            Explode();
        }
    }
Exemplo n.º 22
0
    protected void Move()
    {
        if (!MyShip.IsInPortal)
        {
            _isEngineKilled = (bool)Whiteboard.Parameters["IsEngineKilled"];
            Vector3 dest = (Vector3)Whiteboard.Parameters["Destination"];

            IsEngineKilled = _isEngineKilled;
            IsThrusting    = (bool)Whiteboard.Parameters["IsThrusting"];

            bool isStopping = false;
            if (dest == Vector3.zero)
            {
                //try to stop
                isStopping = true;
            }
            Vector3 interceptDest = StaticUtility.FirstOrderIntercept(MyShip.transform.position, MyShip.RB.velocity, 0, dest, Vector3.zero);
            Whiteboard.Parameters["InterceptDest"] = interceptDest;
            Vector3 los = interceptDest - transform.position;



            if (isStopping)
            {
                los = RB.velocity * -1f;
            }
            else if (los.magnitude < 5f && RB.velocity.magnitude > 0.1f)
            {
                los = RB.velocity * -1f;
            }

            float force = 5;
            if (IsThrusting)
            {
                force = 14;
            }

            //adjust force based on how close is to destination
            force *= Mathf.Lerp(0.4f, 1f, Mathf.Clamp01(los.magnitude / 10));


            if (!_isEngineKilled || IsThrusting)
            {
                if (Vector3.Angle(MyShip.transform.forward, los) < 30 || los.magnitude < 10f || isStopping)
                {
                    RB.AddForce(los.normalized * force);
                }
            }

            if (IsThrusting)
            {
                if (MyShip.MyReference.ExhaustController != null)
                {
                    MyShip.MyReference.ExhaustController.setExhaustState(ExhaustState.Thruster);
                }
            }
            else
            {
                if (MyShip.MyReference.ExhaustController != null)
                {
                    if (_isEngineKilled)
                    {
                        MyShip.MyReference.ExhaustController.setExhaustState(ExhaustState.Idle);
                    }
                    else
                    {
                        MyShip.MyReference.ExhaustController.setExhaustState(ExhaustState.Normal);
                    }
                }
            }

            //update exhaust trail
            MyShip.MyReference.ExhaustController.UpdateExhaustTrail(RB.velocity.magnitude);

            if (_avoidanceForce != Vector3.zero)
            {
                //Debug.Log(_avoidanceForce);
            }

            if ((bool)Whiteboard.Parameters["IgnoreAvoidance"] == false)
            {
                RB.AddForce(_avoidanceForce);
            }

            float strafeForce = (float)Whiteboard.Parameters["StrafeForce"];
            if (strafeForce != 0)
            {
                RB.AddForce(MyShip.transform.right * strafeForce);
            }

            //drag
            Vector3 velocity = RB.velocity;
            float   maxSpeed = MyShip.Engine.MaxSpeed;
            //Debug.Log(velocity.magnitude);
            float speedLimit = (float)Whiteboard.Parameters["SpeedLimit"];
            if (speedLimit >= 0 && speedLimit < maxSpeed)
            {
                maxSpeed = speedLimit;
            }



            if (velocity.magnitude > maxSpeed)
            {
                RB.AddForce(-1 * velocity * 1);
            }
            else
            {
                RB.AddForce(-1 * velocity.normalized * 0.01f);
            }

            if (!_isEngineKilled)
            {
                Vector3 driftVelocity = velocity - Vector3.Dot(velocity, transform.forward) * transform.forward;
                RB.AddForce(-1 * driftVelocity.normalized * driftVelocity.magnitude * 0.5f);
            }
        }
        else
        {
            RB.velocity = Vector3.zero;
        }
    }
Exemplo n.º 23
0
        public async Task <IActionResult> AutoForecastPost(int dataHours, int periods, bool hourlySeasonality, bool dailySeasonality)
        {
            var viewModel = new AutoForecastViewModel();
            var manager   = new DirectoryManager(_appSettings, currentLocation);
            var assets    = DirectoryManager.ReadAssetsFromExcel(manager.AsstesLocation);

            //var symbol = assets.First();
            StaticUtility.RequestCounter = manager.GetRequestCount();//StaticUtility.AddRequestCount(manager.GetRequestCount());
            //var pythonRun = new Logic(_appSettings);
            var catchAsset = string.Empty;

            try
            {
                Parallel.ForEach(assets, symbol =>
                {
                    catchAsset       = symbol;
                    var pythonRun    = new Logic(_appSettings);
                    var coin         = new Logic(_appSettings, symbol, dataHours, currentLocation);
                    var pathToFolder = manager.GenerateForecastFolder(symbol, periods, DirSwitcher.Auto);
                    //coin.GenerateCsvFile(pathToFolder);
                    if (!coin.GenerateCsvFileAuto(pathToFolder))
                    {
                        StaticUtility.Log(symbol, Indicator.ZeroRezults, 0);
                        return;
                    }
                    pythonRun.PythonExecutor(pathToFolder, periods, hourlySeasonality, dailySeasonality);

                    var pathToOut        = Path.Combine(pathToFolder, manager.OutFile);
                    var pathToComponents = Path.Combine(pathToFolder, manager.OutComponents);
                    var pathToForecast   = Path.Combine(pathToFolder, manager.OutForecast);

                    var outCreated        = StaticUtility.WaitForFile(pathToOut, 20);
                    var componentsCreated = StaticUtility.WaitForFile(pathToComponents, 10);
                    var forecastCreated   = StaticUtility.WaitForFile(pathToForecast, 10);
                    if (!outCreated.Result || !forecastCreated.Result || !componentsCreated.Result)
                    {
                        return;
                    }
                    var table       = StaticUtility.BuildOutTableRows(pathToOut, periods);
                    var performance = coin.DefineTrend(table);
                    StaticUtility.Log(symbol, performance.Indicator, performance.Rate);
                    manager.SpecifyDirByTrend(performance.Indicator, pathToFolder);
                }
                                 );

                manager.UpdateRequests(StaticUtility.RequestCounter);
                var folder = manager.GetLastFolder(DirSwitcher.Auto);
                StaticUtility.WriteLogExcel(folder);
                var positiveDir       = Path.Combine(folder, manager.DirPositive);
                var neutralDir        = Path.Combine(folder, manager.DirNeutral);
                var negativeDir       = Path.Combine(folder, manager.DirNegative);
                var strongPositiveDir = Path.Combine(folder, manager.DirStrongPositive);
                var pathToExcelLog    = Path.Combine(folder, StaticUtility.LogName);
                if (DirectoryManager.IsFolderExist(positiveDir))
                {
                    viewModel.PositiveAssets = DirectoryManager.GetFolderNames(positiveDir);
                }

                if (DirectoryManager.IsFolderExist(neutralDir))
                {
                    viewModel.NeutralAssets = DirectoryManager.GetFolderNames(neutralDir);
                }

                if (DirectoryManager.IsFolderExist(negativeDir))
                {
                    viewModel.NegativeAssets = DirectoryManager.GetFolderNames(negativeDir);
                }

                if (DirectoryManager.IsFolderExist(strongPositiveDir))
                {
                    viewModel.StrongPositiveAssets = DirectoryManager.GetFolderNames(strongPositiveDir);
                }

                viewModel.RequestCount = StaticUtility.RequestCounter;
                viewModel.Report       = manager.ReadLog(pathToExcelLog);
            }
            catch (Exception e)
            {
                manager.UpdateRequests(StaticUtility.RequestCounter);
                StaticUtility.WriteLogExcel(manager.GetLastFolder(DirSwitcher.Auto));
                return(NotFound(new { message = e.Message + " Assset: " + catchAsset, requestCount = manager.CurrentCounts }));
            }

            return(Json(viewModel));
        }
Exemplo n.º 24
0
        public async Task <IActionResult> InstantForecast()
        {
            var        viewModel         = new InstantForecastModal();
            const int  periods           = 24;
            const int  dataHours         = 230;
            const bool hourlySeasonality = false;
            const bool dailySeasonality  = false;
            var        numFormat         = new CultureInfo("en-US", false).NumberFormat;

            numFormat.PercentDecimalDigits = 3;

            var symbol    = _appSettings.Value.InstantForecast;
            var coin      = new Logic(_appSettings, symbol, dataHours, currentLocation);
            var manager   = new DirectoryManager(_appSettings, currentLocation);
            var pythonRun = new Logic(_appSettings);

            StaticUtility.RequestCounter = (manager.GetRequestCount());
            try
            {
                var pathToFolder = manager.GenerateForecastFolder(symbol, periods, DirSwitcher.Instant);

                if (!coin.GenerateCsvFile(pathToFolder))
                {
                    throw new Exception("Something's wrong with a coin");
                }

                pythonRun.PythonExecutor(manager.GetLastFolder(DirSwitcher.Instant), periods, hourlySeasonality, dailySeasonality);

                var pathToOut        = Path.Combine(manager.GetLastFolder(DirSwitcher.Instant), manager.OutFile);
                var pathToComponents = Path.Combine(manager.GetLastFolder(DirSwitcher.Instant), manager.OutComponents);
                var pathToForecast   = Path.Combine(manager.GetLastFolder(DirSwitcher.Instant), manager.OutForecast);

                var pathToForecastForImg = Path.Combine(_appSettings.Value.ForecastDir, manager.DirForImages(DirSwitcher.Instant), manager.OutForecast);

                var outCreated = await StaticUtility.WaitForFile(pathToOut, 60);

                var componentsCreated = await StaticUtility.WaitForFile(pathToComponents, 10);

                var forecastCreated = await StaticUtility.WaitForFile(pathToForecast, 10);

                var tableInstant = new List <TableRow>();
                if (outCreated)
                {
                    tableInstant = StaticUtility.BuildOutTableRows(pathToOut, periods).ToList();
                }
                else
                {
                    manager.UpdateRequests(StaticUtility.RequestCounter);
                    return(NotFound(new { message = "out.csv not found", requestCount = StaticUtility.RequestCounter }));
                }
                if (forecastCreated)
                {
                    viewModel.ForecastPath = Path.DirectorySeparatorChar + pathToForecastForImg;
                }
                else
                {
                    manager.UpdateRequests(StaticUtility.RequestCounter);
                    return(NotFound(new { message = "forecast.png not found", requestCount = StaticUtility.RequestCounter }));
                }

                if (!componentsCreated)
                {
                    manager.UpdateRequests(StaticUtility.RequestCounter);
                    return(NotFound(new { message = "components.png not found", requestCount = StaticUtility.RequestCounter }));
                }
                manager.UpdateRequests(StaticUtility.RequestCounter);

                viewModel.AssetName = symbol;
                var performance = coin.DefineTrend(tableInstant);
                viewModel.Indicator = performance.Indicator;
                viewModel.Rate      = performance.Rate.ToString("P", numFormat);
            }
            catch (Exception e)
            {
                manager.UpdateRequests(StaticUtility.RequestCounter);
                return(NotFound(new { message = e.Message, requestCount = StaticUtility.RequestCounter }));
            }
            return(Json(viewModel));
        }
Exemplo n.º 25
0
        public async Task <IActionResult> ManualForecast(string symbol, int dataHours, int periods, bool hourlySeasonality, bool dailySeasonality)
        {
            var viewModel = new MainViewModel();
            var coin      = new Logic(_appSettings, symbol, dataHours, currentLocation);
            var manager   = new DirectoryManager(_appSettings, currentLocation);
            var pythonRun = new Logic(_appSettings);

            StaticUtility.RequestCounter = (manager.GetRequestCount());
            try
            {
                var pathToFolder = manager.GenerateForecastFolder(symbol, periods, DirSwitcher.Manual);
                if (!coin.GenerateCsvFile(pathToFolder))
                {
                    throw new Exception("Something's wrong with a coin");
                }

                pythonRun.PythonExecutor(manager.GetLastFolder(DirSwitcher.Manual), periods, hourlySeasonality, dailySeasonality);

                var pathToOut        = Path.Combine(manager.GetLastFolder(DirSwitcher.Manual), manager.OutFile);
                var pathToComponents = Path.Combine(manager.GetLastFolder(DirSwitcher.Manual), manager.OutComponents);
                var pathToForecast   = Path.Combine(manager.GetLastFolder(DirSwitcher.Manual), manager.OutForecast);

                var pathToComponentsForImg = Path.Combine(_appSettings.Value.ForecastDir, manager.DirForImages(DirSwitcher.Manual), manager.OutComponents);
                var pathToForecastForImg   = Path.Combine(_appSettings.Value.ForecastDir, manager.DirForImages(DirSwitcher.Manual), manager.OutForecast);

                var outCreated = await StaticUtility.WaitForFile(pathToOut, 60);

                var componentsCreated = await StaticUtility.WaitForFile(pathToComponents, 10);

                var forecastCreated = await StaticUtility.WaitForFile(pathToForecast, 10);

                if (outCreated)
                {
                    viewModel.Table = StaticUtility.BuildOutTableRows(pathToOut, periods);
                }
                else
                {
                    manager.UpdateRequests(StaticUtility.RequestCounter);
                    return(NotFound(new { message = "out.csv not found", requestCount = StaticUtility.RequestCounter }));
                }

                if (forecastCreated)
                {
                    viewModel.ForecastPath = Path.DirectorySeparatorChar + pathToForecastForImg;
                }
                else
                {
                    manager.UpdateRequests(StaticUtility.RequestCounter);
                    return(NotFound(new { message = "forecast.png not found", requestCount = StaticUtility.RequestCounter }));
                }

                if (componentsCreated)
                {
                    viewModel.ComponentsPath = Path.DirectorySeparatorChar + pathToComponentsForImg;
                }
                else
                {
                    manager.UpdateRequests(StaticUtility.RequestCounter);
                    return(NotFound(new { message = "components.png not found", requestCount = StaticUtility.RequestCounter }));
                }

                manager.UpdateRequests(StaticUtility.RequestCounter);
                viewModel.RequestsPerDay = StaticUtility.RequestCounter;//manager.CurrentCounts;
                viewModel.AssetName      = symbol;
                var performance = coin.DefineTrend(viewModel.Table);
                viewModel.Indicator = performance.Indicator;
            }
            catch (Exception e)
            {
                manager.UpdateRequests(StaticUtility.RequestCounter);
                return(NotFound(new { message = e.Message, requestCount = StaticUtility.RequestCounter }));
            }

            return(Json(viewModel));
        }
Exemplo n.º 26
0
    public override BTResult Process()
    {
        if (this.LastRunTime <= 0)
        {
            this.LastRunTime = Time.time;
        }
        float deltaTime = Time.time - this.LastRunTime;

        this.LastRunTime = Time.time;

        //Debug.Log("Processing Fighter Reverse Attack state " + State + " dir " + _evadeDir);
        Debug.DrawRay(MyAI.MyShip.transform.position, _evadeDir * 30, Color.blue);

        ShipBase target = (ShipBase)MyAI.Whiteboard.Parameters["TargetEnemy"];

        if (State == 0)
        {
            MyAI.Whiteboard.Parameters["AimTarget"] = target;
        }
        else
        {
            MyAI.Whiteboard.Parameters["AimTarget"] = null;
        }


        if (_timer >= _timeout)
        {
            if (State == 0)
            {
                if (target != null)
                {
                    if (_evadeDir == Vector3.zero)
                    {
                        _evadeDir = StaticUtility.FindEvadeDirWithTarget(MyAI.MyShip, target.transform.position, 0.3f) * -1;
                    }
                }
                else
                {
                    _evadeDir = MyAI.MyShip.transform.forward;
                }

                MyAI.Whiteboard.Parameters["IsEngineKilled"] = false;
                MyAI.Whiteboard.Parameters["IsThrusting"]    = true;
                MyAI.Whiteboard.Parameters["Destination"]    = MyAI.MyShip.transform.position + _evadeDir * 60f;
                MyAI.Whiteboard.Parameters["EvadeDir"]       = _evadeDir;

                State    = 1;
                _timeout = UnityEngine.Random.Range(3f, 4f);
                _timer   = 0;
            }
            else
            {
                return(Exit(BTResult.Fail));
            }
        }



        _timer += deltaTime;

        return(Running());
    }
Exemplo n.º 27
0
    public void StartFadingMaterial(Renderer renderer, bool isInstant, bool isBuilding, float speed)
    {
        if (!_alteredRenderers.Contains(renderer))
        {
            _alteredRenderers.Add(renderer);
            if (isBuilding)
            {
                //make a duplicate object to block light
                GameObject dupe = GameObject.Instantiate(renderer.gameObject, renderer.transform.parent) as GameObject;
                //remove children
                foreach (Transform child in dupe.transform)
                {
                    GameObject.Destroy(child.gameObject);
                }
                dupe.transform.position   = renderer.gameObject.transform.position;
                dupe.transform.localScale = renderer.transform.localScale;
                _dupeObjects.Add(renderer, dupe);

                dupe.GetComponent <Collider>().enabled           = false;
                dupe.GetComponent <BuildingComponent>().enabled  = false;
                dupe.GetComponent <Renderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.ShadowsOnly;
            }
        }

        bool needToChangeRender = true;

        if (_fadingMaterials.ContainsKey(renderer))
        {
            needToChangeRender = false;
        }

        if (!_fadeOutSpeed.ContainsKey(renderer))
        {
            _fadeOutSpeed.Add(renderer, speed);
        }
        else
        {
            _fadeOutSpeed[renderer] = speed;
        }

        //first save the renderer's current shared material
        if (!_savedMaterials.ContainsKey(renderer))
        {
            _savedMaterials.Add(renderer, renderer.sharedMaterials);
        }

        //create instance materials and save the reference for destruction later
        if (!_fadingMaterials.ContainsKey(renderer))
        {
            _fadingMaterials.Add(renderer, renderer.materials);
        }

        if (!_fadingDirections.ContainsKey(renderer))
        {
            _fadingDirections.Add(renderer, -1);
        }
        else
        {
            _fadingDirections[renderer] = -1;
        }

        if (needToChangeRender)
        {
            //for each instanced material, set shader to transparent
            foreach (Material m in _fadingMaterials[renderer])
            {
                StaticUtility.ChangeRenderMode(m, BlendMode.Fade);
                if (isInstant)
                {
                    m.color = new Color(m.color.r, m.color.g, m.color.b, 0f);
                }
                else
                {
                    m.color = new Color(m.color.r, m.color.g, m.color.b, 1f);
                }
            }
        }

        if (isInstant)
        {
            FixedUpdate();
        }
    }