Exemple #1
0
        virtual public void Parse(string aSource, TextFormat defaultFormat, List <HtmlElement> elements, HtmlParseOptions parseOptions)
        {
            if (parseOptions == null)
            {
                parseOptions = _defaultOptions;
            }

            _elements           = elements;
            _textFormatStackTop = 0;
            _skipText           = 0;
            _ignoreWhiteSpace   = parseOptions.ignoreWhiteSpace;
            _format.CopyFrom(defaultFormat);
            _format.colorChanged = false;
            string text;

            XMLIterator.Begin(aSource, true);
            while (XMLIterator.NextTag())
            {
                if (_skipText == 0)
                {
                    text = XMLIterator.GetText(_ignoreWhiteSpace);
                    if (text.Length > 0)
                    {
                        AppendText(text);
                    }
                }

                switch (XMLIterator.tagName)
                {
                case "b":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();
                        _format.bold = true;
                    }
                    else
                    {
                        PopTextFormat();
                    }
                    break;

                case "i":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();
                        _format.italic = true;
                    }
                    else
                    {
                        PopTextFormat();
                    }
                    break;

                case "u":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();
                        _format.underline = true;
                    }
                    else
                    {
                        PopTextFormat();
                    }
                    break;

                case "sub":
                {
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();
                        _format.size         = Mathf.CeilToInt(_format.size * 0.58f);
                        _format.specialStyle = TextFormat.SpecialStyle.Subscript;
                    }
                    else
                    {
                        PopTextFormat();
                    }
                }
                break;

                case "sup":
                {
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();
                        _format.size         = Mathf.CeilToInt(_format.size * 0.58f);
                        _format.specialStyle = TextFormat.SpecialStyle.Superscript;
                    }
                    else
                    {
                        PopTextFormat();
                    }
                }
                break;

                case "font":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();

                        _format.size = XMLIterator.GetAttributeInt("size", _format.size);
                        string color = XMLIterator.GetAttribute("color");
                        if (color != null)
                        {
                            string[] parts = color.Split(',');
                            if (parts.Length == 1)
                            {
                                _format.color         = ToolSet.ConvertFromHtmlColor(color);
                                _format.gradientColor = null;
                                _format.colorChanged  = true;
                            }
                            else
                            {
                                if (_format.gradientColor == null)
                                {
                                    _format.gradientColor = new Color32[4];
                                }
                                _format.gradientColor[0] = ToolSet.ConvertFromHtmlColor(parts[0]);
                                _format.gradientColor[1] = ToolSet.ConvertFromHtmlColor(parts[1]);
                                if (parts.Length > 2)
                                {
                                    _format.gradientColor[2] = ToolSet.ConvertFromHtmlColor(parts[2]);
                                    if (parts.Length > 3)
                                    {
                                        _format.gradientColor[3] = ToolSet.ConvertFromHtmlColor(parts[3]);
                                    }
                                    else
                                    {
                                        _format.gradientColor[3] = _format.gradientColor[2];
                                    }
                                }
                                else
                                {
                                    _format.gradientColor[2] = _format.gradientColor[0];
                                    _format.gradientColor[3] = _format.gradientColor[1];
                                }
                            }
                        }
                    }
                    else if (XMLIterator.tagType == XMLTagType.End)
                    {
                        PopTextFormat();
                    }
                    break;

                case "br":
                    AppendText("\n");
                    break;

                case "img":
                    if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void)
                    {
                        HtmlElement element = HtmlElement.GetElement(HtmlElementType.Image);
                        element.FetchAttributes();
                        element.name         = element.GetString("name");
                        element.format.align = _format.align;
                        _elements.Add(element);
                    }
                    break;

                case "a":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();

                        _format.underline = _format.underline | parseOptions.linkUnderline;
                        if (!_format.colorChanged && parseOptions.linkColor.a != 0)
                        {
                            _format.color = parseOptions.linkColor;
                        }

                        HtmlElement element = HtmlElement.GetElement(HtmlElementType.Link);
                        element.FetchAttributes();
                        element.name         = element.GetString("name");
                        element.format.align = _format.align;
                        _elements.Add(element);
                    }
                    else if (XMLIterator.tagType == XMLTagType.End)
                    {
                        PopTextFormat();

                        HtmlElement element = HtmlElement.GetElement(HtmlElementType.LinkEnd);
                        _elements.Add(element);
                    }
                    break;

                case "input":
                {
                    HtmlElement element = HtmlElement.GetElement(HtmlElementType.Input);
                    element.FetchAttributes();
                    element.name = element.GetString("name");
                    element.format.CopyFrom(_format);
                    _elements.Add(element);
                }
                break;

                case "select":
                {
                    if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void)
                    {
                        HtmlElement element = HtmlElement.GetElement(HtmlElementType.Select);
                        element.FetchAttributes();
                        if (XMLIterator.tagType == XMLTagType.Start)
                        {
                            sHelperList1.Clear();
                            sHelperList2.Clear();
                            while (XMLIterator.NextTag())
                            {
                                if (XMLIterator.tagName == "select")
                                {
                                    break;
                                }

                                if (XMLIterator.tagName == "option")
                                {
                                    if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void)
                                    {
                                        sHelperList2.Add(XMLIterator.GetAttribute("value", string.Empty));
                                    }
                                    else
                                    {
                                        sHelperList1.Add(XMLIterator.GetText());
                                    }
                                }
                            }
                            element.Set("items", sHelperList1.ToArray());
                            element.Set("values", sHelperList2.ToArray());
                        }
                        element.name = element.GetString("name");
                        element.format.CopyFrom(_format);
                        _elements.Add(element);
                    }
                }
                break;

                case "p":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        PushTextFormat();
                        string align = XMLIterator.GetAttribute("align");
                        _format.align = FieldTypes.ParseAlign(align);

                        if (!IsNewLine())
                        {
                            AppendText("\n");
                        }
                    }
                    else if (XMLIterator.tagType == XMLTagType.End)
                    {
                        if (!IsNewLine())
                        {
                            AppendText("\n");
                        }

                        PopTextFormat();
                    }
                    break;

                case "ui":
                case "div":
                case "li":
                    if (!IsNewLine())
                    {
                        AppendText("\n");
                    }
                    break;

                case "html":
                case "body":
                    //full html
                    _ignoreWhiteSpace = true;
                    break;

                case "head":
                case "style":
                case "script":
                case "form":
                    if (XMLIterator.tagType == XMLTagType.Start)
                    {
                        _skipText++;
                    }
                    else if (XMLIterator.tagType == XMLTagType.End)
                    {
                        _skipText--;
                    }
                    break;
                }
            }

            if (_skipText == 0)
            {
                text = XMLIterator.GetText(_ignoreWhiteSpace);
                if (text.Length > 0)
                {
                    AppendText(text);
                }
            }

            _elements = null;
        }
 public void ToggleAndBurst()
 {
     rend.material = !coll.enabled ? onMaterial : offMaterial;
     coll.enabled  = !coll.enabled;
     pSystem.Emit(Mathf.CeilToInt(maxScaleAxis * 10));
 }
Exemple #3
0
    private void OnGUI()
    {
        if (!ShowDebugHelper)
        {
            return;
        }

        if (GUILayout.Button("door", GUILayout.Height(_heightValue - 10), GUILayout.Width(_widthValue - 50)))
        {
            m_bUseOtherFun = !m_bUseOtherFun;
            if (!UIManager.Instance.UIRoot.activeSelf)
            {
                var e = new MainUiOperateEvent(0);
                EventDispatcher.Instance.DispatchEvent(e);
            }
        }

        GUI.depth = 10000;
        if (m_bUseOtherFun)
        {
            GUILayout.Space(30);
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("HideUI", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                if (UIManager.Instance.UIRoot != null)
                {
                    var ui = UIManager.Instance.UIRoot.transform.Find("TYPE_BASE");
                    if (ui != null)
                    {
                        ui.gameObject.SetActive(!ui.gameObject.activeSelf);
                    }

                    var ui2 = UIManager.Instance.UIRoot.transform.Find("HeadBoardRoot");
                    if (ui2 != null)
                    {
                        ui2.gameObject.SetActive(!ui2.gameObject.activeSelf);
                    }
                }
            }

            GUILayout.Space(30);
            if (GUILayout.Button("FPS unlimit ", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                Application.targetFrameRate = 0;
            }

            GUILayout.Space(30);
            if (GUILayout.Button("Clear Cache", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                ResourceManager.Instance.Reset();
                Resources.UnloadUnusedAssets();
                GC.Collect(0, GCCollectionMode.Forced);
            }

            // mGMCommond = GUI.TextField(new Rect(Screen.width - 200, _heightValue, 200, _heightValue), mGMCommond, 25);
            GUILayout.EndHorizontal();
            GUILayout.Space(30);


            GUILayout.BeginHorizontal();

            if (GUILayout.Button(string.Format("GM热键(`)"), GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                Console.Show();

//                 if (mGMCommond.Length > 0)
//                 {
//                     StartCoroutine(SendGmCOmmond());
//                 }
            }


            GUILayout.Space(30);
            if (GUILayout.Button(string.Format("开关特效"), GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                var bloom = GameLogic.Instance.MainCamera.GetComponent <DistortionAndBloom>();
                bloom.enabled = !bloom.enabled;

                //                 if (mGMCommond.Length > 0)
                //                 {
                //                     StartCoroutine(SendGmCOmmond());
                //                 }
            }

            GUILayout.Space(30);

            if (GUILayout.Button("LOW MEMORY", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                PlatformListener.Instance.OnLowMemory();
            }


            GUILayout.EndHorizontal();

            GUILayout.Space(30);
            GUILayout.BeginHorizontal();

            if (GUILayout.Button(string.Format("开关网络"), GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                if (NetManager.Instance.Connected)
                {
                    NetManager.Instance.Stop();
                }
                else
                {
                    NetManager.Instance.ReconnectToServer();
                }
            }

            GUILayout.Space(30);
            if (GUILayout.Button("Battery save test", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                if (DisplayAll)
                {
                    CullingMaskList.Clear();
                    for (var i = 0; i < Camera.allCameras.Length; ++i)
                    {
                        var cam = Camera.allCameras[i];
                        CullingMaskList.Add(cam.cullingMask);
                        cam.cullingMask = 0;
                    }
                }
                else
                {
                    for (var i = 0; i < Camera.allCameras.Length; ++i)
                    {
                        var cam = Camera.allCameras[i];
                        cam.cullingMask = CullingMaskList[i];
                    }
                }

                DisplayAll = !DisplayAll;
            }

            GUILayout.Space(30);

            if (GUILayout.Button("AddPush", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                PlatformHelper.SetLocalNotification("pushTest", "ceshi", 30);
            }

            GUILayout.EndHorizontal();

            GUILayout.Space(30);

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("OpenUrl", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                var url = UpdateHelper.CheckUrl(urls[urlIndex % 2]);
                Application.OpenURL(url);
                urlIndex++;
            }
            GUILayout.Space(30);

            if (GUILayout.Button("HDR", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                GameSetting.Instance.EnableHDR = !GameSetting.Instance.EnableHDR;
            }

            GUILayout.Space(30);

            if (GUILayout.Button("Hardware Scaler", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                if (mOriginWidth == 0)
                {
                    mOriginWidth  = Screen.currentResolution.width;
                    mOriginHeight = Screen.currentResolution.height;

//                     int designWidth = 1280;
//                     int designHeight = 800;
//
//                     float s1 = designWidth / (float)designHeight;
//                     float s2 = mOriginWidth / (float)mOriginHeight;
//
//                     if (s1 < s2)
//                     {
//                         designWidth = Mathf.FloorToInt(designHeight * s2);
//                     }
//                     else if (s1 > s2)
//                     {
//                         designHeight = Mathf.FloorToInt(designWidth / s2);
//                     }
//
//                     float contentScale = designWidth / (float)mOriginWidth;
//                     if (contentScale < 1f)
//                     {
//                         scaleWidth = designWidth;
//                         scaleHeight = designHeight;
//                         if (scaleWidth % 2 == 0)
//                         {
//                             scaleWidth += 1;
//                         }
//                         else
//                         {
//                             scaleWidth -= 1;
//                         }
//                     }
                }

                HardwareScalerLevel++;
                scaleWidth  = Mathf.CeilToInt(mOriginWidth * (1 - 1.0f / (HardwareScalerLevel + 1)));
                scaleHeight = Mathf.CeilToInt(mOriginHeight * (1 - 1.0f / (HardwareScalerLevel + 1)));

                if (HardwareScalerLevel == 6)
                {
                    HardwareScalerLevel = 0;
                }

                if (HardwareScalerLevel != 0)
                {
                    Screen.SetResolution(scaleWidth, scaleHeight, true);
                    Logger.Debug("HandwareScaler enable!");
                }
                else
                {
                    Screen.SetResolution(mOriginWidth, mOriginHeight, true);
                    Logger.Debug("HandwareScaler disable!");
                }
            }



            GUILayout.EndHorizontal();

            GUILayout.Space(30);

            GUILayout.BeginHorizontal();

            if (GUILayout.Button("SPEED UP", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                var console = gameObject.GetComponent <DevConsole.Console>();
                console.PrintInput("!!SpeedSet,300");
            }

            GUILayout.Space(30);

            if (GUILayout.Button("RestartApp", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                PlatformHelper.RestartApp();
            }

            GUILayout.Space(30);

            if (GUILayout.Button("ReconnectTest", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
            {
                // Game.Instance.EnterStartup();
                NetManager.Instance.PrepareForReconnect();
            }

            GUILayout.EndHorizontal();

            //
            //             if (GUILayout.Button("PlayerSound", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
//             {
//                 bool bEnable = SoundManager.m_EnableBGM;
//                 bEnable = !bEnable;
//                 SoundManager.m_EnableBGM = bEnable;
//                 SoundManager.m_EnableSFX = bEnable;
//             }
//
//             if (LoginData.m_bEnableTestAccount)
//             {
//                 if (GUILayout.Button("Disable TestAccount", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
//                 {
//                     LoginData.m_bEnableTestAccount = false;
//                 }
//
//                 LoginData.m_strTestAccount = GUI.TextField(new Rect(Screen.width - 200, 0, 200, _heightValue), LoginData.m_strTestAccount, 15);
//             }
//             else
//             {
//                 if (GUILayout.Button("Enable TestAccount", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
//                 {
//                     LoginData.m_bEnableTestAccount = true;
//                 }
//             }
//
//             if (GUILayout.Button("TerrainHeight", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
//             {
//                 Obj_MainPlayer objMain = Singleton<ObjManager>.GetInstance().MyPlayer;
//                 if (null != objMain)
//                 {
//                     if (null != GameManager.gameManager.ActiveScene &&
//                         null != GameManager.gameManager.ActiveScene.TerrainData)
//                     {
//                         float height = GameManager.gameManager.ActiveScene.TerrainData.GetTerrianHeight(objMain.Position);
//                         Logger.Debug("Terrain Heigt: " + height);
//                         return;
//                     }
//                 }
//
//                 Logger.Debug("Get Terrain Height Error");
//             }

//             m_strSetNameHeight = GUI.TextField(new Rect(Screen.width - 200, _heightValue, 200, _heightValue), m_strSetNameHeight, 15);
//             if (GUILayout.Button("ChangeNameHeight", GUILayout.Height(_heightValue), GUILayout.Width(_widthValue)))
//             {
//                 if (Singleton<ObjManager>.Instance.MyPlayer)
//                 {
//                     float fNewHeight;
//                     bool bResult = float.TryParse(m_strSetNameHeight, out fNewHeight);
//                     if (bResult)
//                     {
//                         Obj_Character target = Singleton<ObjManager>.Instance.MyPlayer.SelectTarget;
//                         if (null != target)
//                         {
//                             BillBoard billboard = target.HeadInfoBoard.GetComponent<BillBoard>();
//                             if (billboard != null)
//                             {
//                                 billboard.fDeltaHeight = fNewHeight;
//                             }
//                         }
//
//                         //m_IsSetNameHeight = false;
//                     }
//
//                 }
//             }
        }
    }
Exemple #4
0
 public static Vector2Int CeilToInt(Vector2 v)
     => new Vector2Int(Mathf.CeilToInt(v.x), Mathf.CeilToInt(v.y));
Exemple #5
0
        static void Prefix(SimGameState __instance, int timeLapse)
        {
            try {
                //DAILY
                System.Random rand = new System.Random();
                foreach (KeyValuePair <Faction, FactionDef> pair in __instance.FactionsDict)
                {
                    if (!Helper.IsExcluded(pair.Key) && Helper.IsAtWar(pair.Key))
                    {
                        List <TargetSystem> availableTargets = Fields.availableTargets[pair.Key];
                        if (availableTargets.Count > 0)
                        {
                            List <TargetSystem> targets = availableTargets.OrderByDescending(x => Helper.GetOffenceValue(x.system) + Helper.GetDefenceValue(x.system) + Helper.GetNeighborValue(x.factionNeighbours, pair.Key)).ToList();
                            int numberOfAttacks         = Mathf.Min(targets.Count, Mathf.CeilToInt(Fields.factionResources.Find(x => x.faction == pair.Key).offence / 100f));
                            for (int i = 0; i < numberOfAttacks; i++)
                            {
                                StarSystem system = __instance.StarSystems.Find(x => x.Name == targets[i].system.Name);
                                if (system != null)
                                {
                                    system = Helper.AttackSystem(system, __instance, pair.Key, rand);
                                }
                            }
                        }
                    }
                }


                //MONTHLY
                int num = (timeLapse <= 0) ? 1 : timeLapse;
                if ((__instance.DayRemainingInQuarter - num <= 0))
                {
                    foreach (KeyValuePair <string, string> changes in Fields.thisMonthChanges)
                    {
                        StarSystem changedSystem = __instance.StarSystems.Find(x => x.Name.Equals(changes.Key));
                        if (!Helper.GetFactionName(changedSystem.Owner, __instance.DataManager).Equals(changes.Value))
                        {
                            War war = Helper.getWar(changedSystem.Owner);
                            if (war != null)
                            {
                                if (war.attackers.ContainsKey(changedSystem.Owner))
                                {
                                    war.monthlyEvents.Add("<color=" + Fields.settings.attackercolor + ">" + Helper.GetFactionName(changedSystem.Owner, __instance.DataManager) + "</color>" + " took " + "<color=" + Fields.settings.planetcolor + ">" + changes.Key + "</color>" + " from " + "<color=" + Fields.settings.defendercolor + ">" + changes.Value + "</color>");
                                }
                                else
                                {
                                    war.monthlyEvents.Add("<color=" + Fields.settings.defendercolor + ">" + Helper.GetFactionName(changedSystem.Owner, __instance.DataManager) + "</color>" + " took " + "<color=" + Fields.settings.planetcolor + ">" + changes.Key + "</color>" + " from " + "<color=" + Fields.settings.attackercolor + ">" + changes.Value + "</color>");
                                }
                            }
                        }
                    }
                    foreach (War war in Fields.currentWars)
                    {
                        war.monthlyEvents.Add("\n");
                    }
                    Dictionary <Faction, FactionDef> factions = (Dictionary <Faction, FactionDef>)AccessTools.Field(typeof(SimGameState), "factions").GetValue(__instance);
                    foreach (KeyValuePair <Faction, FactionDef> pair in factions)
                    {
                        if (Helper.IsExcluded(pair.Key))
                        {
                            continue;
                        }
                        List <Faction> fac = null;
                        if (Fields.neighbourFactions.ContainsKey(pair.Key))
                        {
                            fac = Fields.neighbourFactions[pair.Key];
                        }
                        List <Faction> list = Helper.GetFactionsByString(Fields.settings.excludedFactionNames);
                        if (fac != null && list != null && list.Count > 0)
                        {
                            fac = fac.Except(list).ToList();
                            if (Fields.Allies[pair.Key].Count() > 0)
                            {
                                fac = fac.Except(Fields.Allies[pair.Key]).ToList();
                            }
                        }
                        if (!Helper.IsAtWar(pair.Key) && !Helper.IsExcluded(pair.Key) && fac != null && fac.Count > 0)
                        {
                            if (rand.Next(0, 101) > Fields.WarFatique[pair.Key])
                            {
                                Faction enemy;
                                do
                                {
                                    enemy = fac[rand.Next(fac.Count)];
                                } while (Helper.IsExcluded(enemy) || pair.Key == enemy);

                                bool joinedWar = false;
                                foreach (War war in Fields.currentWars)
                                {
                                    if (war.attackers.ContainsKey(enemy) && !Fields.removeWars.Contains(war.name))
                                    {
                                        war.defenders.Add(pair.Key, new WarProgression(new Dictionary <string, Faction>()));
                                        war.monthlyEvents.Add("<color=" + Fields.settings.defendercolor + ">" + Helper.GetFactionName(pair.Key, __instance.DataManager) + "</color>" + " joined the war.");
                                        joinedWar = true;
                                        break;
                                    }
                                    else if (war.defenders.ContainsKey(enemy) && !Fields.removeWars.Contains(war.name))
                                    {
                                        war.attackers.Add(pair.Key, new WarProgression(new Dictionary <string, Faction>()));
                                        war.monthlyEvents.Add("<color=" + Fields.settings.attackercolor + ">" + Helper.GetFactionName(pair.Key, __instance.DataManager) + "</color>" + " joined the war.");
                                        joinedWar = true;
                                        break;
                                    }
                                }
                                if (!joinedWar)
                                {
                                    string Name = Helper.GetFactionShortName(pair.Key, __instance.DataManager) + " VS " + Helper.GetFactionShortName(enemy, __instance.DataManager);
                                    Dictionary <Faction, WarProgression> attackers = new Dictionary <Faction, WarProgression>();
                                    attackers.Add(pair.Key, new WarProgression(new Dictionary <string, Faction>()));
                                    Dictionary <Faction, WarProgression> defenders = new Dictionary <Faction, WarProgression>();
                                    defenders.Add(enemy, new WarProgression(new Dictionary <string, Faction>()));
                                    War war = new War(Name, attackers, defenders);
                                    war.monthlyEvents.Add("<color=" + Fields.settings.attackercolor + ">" + Helper.GetFactionName(pair.Key, __instance.DataManager) + "</color>" + " declared war on " + "<color=" + Fields.settings.defendercolor + ">" + Helper.GetFactionName(enemy, __instance.DataManager) + "</color>" + ".\n");
                                    if (Fields.currentWars.Contains(war))
                                    {
                                        Logger.LogLine(war.name + "already exists");
                                    }
                                    Fields.currentWars.Add(war);
                                }
                            }
                            else
                            {
                                Fields.WarFatique[pair.Key] = Mathf.Max(0, Fields.WarFatique[pair.Key] -= Fields.settings.FatiqueRecoveredPerMonth);
                                Helper.Diplomacy(pair.Key, ref __instance, rand);
                            }
                        }
                        else if (Helper.IsAtWar(pair.Key))
                        {
                            Fields.WarFatique[pair.Key] = Mathf.Min(100, Fields.WarFatique[pair.Key] + Fields.settings.FatiqueLostPerMonth);
                            if (rand.Next(0, 101) < Fields.WarFatique[pair.Key])
                            {
                                War war = Helper.getWar(pair.Key);
                                if (war == null)
                                {
                                    Logger.LogLine(pair.Key + " has no war at end war calculations");
                                }
                                if (war.duration >= Fields.settings.minMonthDuration)
                                {
                                    if (war.duration < Fields.settings.maxMonthDuration || Fields.settings.maxMonthDuration == -1)
                                    {
                                        if (!(Fields.currentWars.Find(x => x.name.Equals(war.name)).attackers.Count <= 0) && !(Fields.currentWars.Find(x => x.name.Equals(war.name)).defenders.Count <= 0))
                                        {
                                            string color = "";
                                            if (Fields.currentWars.Find(x => x.name.Equals(war.name)).attackers.ContainsKey(pair.Key))
                                            {
                                                color = Fields.settings.attackercolor;
                                                Fields.currentWars.Find(x => x.name.Equals(war.name)).monthlyEvents.Add("\n<color=" + color + ">" + Helper.GetFactionName(pair.Key, __instance.DataManager) + "</color>" + " surrendered.");
                                                Dictionary <Faction, int> returnedPlanetsCount = new Dictionary <Faction, int>();
                                                foreach (KeyValuePair <string, Faction> taken in Fields.currentWars.Find(x => x.name.Equals(war.name)).attackers[pair.Key].takenPlanets)
                                                {
                                                    if (war.defenders.ContainsKey(taken.Value))
                                                    {
                                                        StarSystem         changedSystem = __instance.StarSystems.Find(x => x.Name.Equals(taken.Key));
                                                        PlanetControlState planetState   = Fields.stateOfWar.FirstOrDefault(x => x.system.Equals(changedSystem.Name));
                                                        FactionControl     oldControl    = planetState.factionList.FirstOrDefault(x => x.faction == pair.Key);
                                                        int percentage = oldControl.percentage;
                                                        oldControl.percentage = 0;
                                                        FactionControl ownerControl = planetState.factionList.FirstOrDefault(x => x.faction == taken.Value);
                                                        ownerControl.percentage += percentage;
                                                        changedSystem            = Helper.ChangeOwner(changedSystem, ownerControl, __instance, true, true);
                                                        changedSystem            = Helper.ChangeWarDescription(changedSystem, __instance);
                                                        if (!returnedPlanetsCount.ContainsKey(taken.Value))
                                                        {
                                                            returnedPlanetsCount.Add(taken.Value, 1);
                                                        }
                                                        else
                                                        {
                                                            returnedPlanetsCount[taken.Value]++;
                                                        }
                                                    }
                                                }
                                                foreach (KeyValuePair <Faction, int> returned in returnedPlanetsCount)
                                                {
                                                    Fields.currentWars.Find(x => x.name.Equals(war.name)).monthlyEvents.Add("<color=" + color + ">" + Helper.GetFactionName(pair.Key, __instance.DataManager) + "</color>" + " returned " + "<color=" + Fields.settings.planetcolor + ">" + returned.Value + "</color>" + " systems to " + "<color=" + Fields.settings.defendercolor + ">" + Helper.GetFactionName(returned.Key, __instance.DataManager) + "</color>");
                                                }
                                                Fields.currentWars.Find(x => x.name.Equals(war.name)).attackers.Remove(pair.Key);
                                            }
                                            else
                                            {
                                                color = Fields.settings.defendercolor;
                                                Fields.currentWars.Find(x => x.name.Equals(war.name)).monthlyEvents.Add("\n<color=" + color + ">" + Helper.GetFactionName(pair.Key, __instance.DataManager) + "</color>" + " surrendered.");
                                                Dictionary <Faction, int> returnedPlanetsCount = new Dictionary <Faction, int>();
                                                foreach (KeyValuePair <string, Faction> taken in Fields.currentWars.Find(x => x.name.Equals(war.name)).defenders[pair.Key].takenPlanets)
                                                {
                                                    if (war.attackers.ContainsKey(taken.Value))
                                                    {
                                                        StarSystem         changedSystem = __instance.StarSystems.Find(x => x.Name.Equals(taken.Key));
                                                        PlanetControlState planetState   = Fields.stateOfWar.FirstOrDefault(x => x.system.Equals(changedSystem.Name));
                                                        FactionControl     oldControl    = planetState.factionList.FirstOrDefault(x => x.faction == pair.Key);
                                                        int percentage = oldControl.percentage;
                                                        oldControl.percentage = 0;
                                                        FactionControl ownerControl = planetState.factionList.FirstOrDefault(x => x.faction == taken.Value);
                                                        ownerControl.percentage += percentage;
                                                        changedSystem            = Helper.ChangeOwner(changedSystem, ownerControl, __instance, true, true);
                                                        changedSystem            = Helper.ChangeWarDescription(changedSystem, __instance);
                                                        if (!returnedPlanetsCount.ContainsKey(taken.Value))
                                                        {
                                                            returnedPlanetsCount.Add(taken.Value, 1);
                                                        }
                                                        else
                                                        {
                                                            returnedPlanetsCount[taken.Value]++;
                                                        }
                                                    }
                                                }
                                                foreach (KeyValuePair <Faction, int> returned in returnedPlanetsCount)
                                                {
                                                    Fields.currentWars.Find(x => x.name.Equals(war.name)).monthlyEvents.Add("<color=" + color + ">" + Helper.GetFactionName(pair.Key, __instance.DataManager) + "</color>" + " returned " + "<color=" + Fields.settings.planetcolor + ">" + returned.Value + "</color>" + " systems to " + "<color=" + Fields.settings.attackercolor + ">" + Helper.GetFactionName(returned.Key, __instance.DataManager) + "</color>");
                                                }
                                                Fields.currentWars.Find(x => x.name.Equals(war.name)).defenders.Remove(pair.Key);
                                            }

                                            if (Fields.currentWars.Find(x => x.name.Equals(war.name)).attackers.Count <= 0)
                                            {
                                                Fields.currentWars.Find(x => x.name.Equals(war.name)).monthlyEvents.Add("\n<b>Attacking side lost the war.</b>");
                                                foreach (KeyValuePair <Faction, WarProgression> defender in Fields.currentWars.Find(x => x.name.Equals(war.name)).defenders)
                                                {
                                                    int count = Fields.currentWars.Find(x => x.name.Equals(war.name)).defenders[defender.Key].takenPlanets.Count;
                                                    Fields.currentWars.Find(x => x.name.Equals(war.name)).monthlyEvents.Add("<color=" + Fields.settings.defendercolor + ">" + Helper.GetFactionName(defender.Key, __instance.DataManager) + "</color>" + " took " + "<color=" + Fields.settings.planetcolor + ">" + count + "</color>" + " systems in the war.");
                                                }
                                                if (!Fields.removeWars.Contains(war.name))
                                                {
                                                    Fields.removeWars.Add(war.name);
                                                }
                                            }
                                            else if (Fields.currentWars.Find(x => x.name.Equals(war.name)).defenders.Count <= 0)
                                            {
                                                Fields.currentWars.Find(x => x.name.Equals(war.name)).monthlyEvents.Add("\n<b>Defending side lost the war.</b>");
                                                foreach (KeyValuePair <Faction, WarProgression> attackers in Fields.currentWars.Find(x => x.name.Equals(war.name)).attackers)
                                                {
                                                    int count = Fields.currentWars.Find(x => x.name.Equals(war.name)).attackers[attackers.Key].takenPlanets.Count;
                                                    Fields.currentWars.Find(x => x.name.Equals(war.name)).monthlyEvents.Add("<color=" + Fields.settings.attackercolor + ">" + Helper.GetFactionName(attackers.Key, __instance.DataManager) + "</color>" + " took " + "<color=" + Fields.settings.planetcolor + ">" + count + "</color>" + " systems in the war.");
                                                }
                                                if (!Fields.removeWars.Contains(war.name))
                                                {
                                                    Fields.removeWars.Add(war.name);
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Fields.currentWars.Find(x => x.name.Equals(war.name)).monthlyEvents.Add("\nThe War ended Undecided.");
                                        if (!Fields.removeWars.Contains(war.name))
                                        {
                                            Fields.removeWars.Add(war.name);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    foreach (KeyValuePair <Faction, FactionDef> pair in factions)
                    {
                        if (Fields.currentEnemies.ContainsKey(pair.Key))
                        {
                            Faction[] enemies = Fields.currentEnemies[pair.Key].ToArray();
                            ReflectionHelper.InvokePrivateMethode(pair.Value, "set_Enemies", new object[] { enemies });
                        }
                    }
                    SimGameInterruptManager interruptQueue = (SimGameInterruptManager)AccessTools.Field(typeof(SimGameState), "interruptQueue").GetValue(__instance);

                    foreach (War war in Fields.currentWars)
                    {
                        war.duration += 1;
                        if (!Fields.removeWars.Contains(war.name))
                        {
                            war.monthlyEvents.Add("<color=" + Fields.settings.attackercolor + ">" + "\nAttackers:" + "</color>");
                            foreach (Faction fac in war.attackers.Keys)
                            {
                                war.monthlyEvents.Add(Helper.GetFactionName(fac, __instance.DataManager) + " | Exhaustion: " + Math.Round(Fields.WarFatique[fac], 1).ToString("F1") + "%");
                            }
                            war.monthlyEvents.Add("<color=" + Fields.settings.defendercolor + ">" + "\nDefenders:" + "</color>");
                            foreach (Faction fac in war.defenders.Keys)
                            {
                                war.monthlyEvents.Add(Helper.GetFactionName(fac, __instance.DataManager) + " | Exhaustion: " + Math.Round(Fields.WarFatique[fac], 1).ToString("F1") + "%");
                            }
                        }
                        interruptQueue.QueueGenericPopup_NonImmediate(war.name, string.Join("\n", war.monthlyEvents.ToArray()) + "\n", true);
                        war.monthlyEvents.Clear();
                    }
                    if (Fields.DiplomacyLog.Count > 0)
                    {
                        interruptQueue.QueueGenericPopup_NonImmediate("Diplomacy", string.Join("\n", Fields.DiplomacyLog.ToArray()), true);
                    }
                    Fields.DiplomacyLog.Clear();
                    Fields.thisMonthChanges = new Dictionary <string, string>();
                    foreach (string war in Fields.removeWars)
                    {
                        Fields.currentWars.Remove(Fields.currentWars.Find(x => x.name.Equals(war)));
                    }
                    Fields.removeWars.Clear();
                    Helper.RefreshResources(__instance);
                    Helper.RefreshEnemies(__instance);
                    Helper.RefreshTargets(__instance);
                    __instance.StopPlayMode();
                }
            }
            catch (Exception e) {
                Logger.LogError(e);
            }
        }
        private static float GetNonTrashMass(ThingStuffPairWithQuality t, float trashThreshold, Func <ThingStuffPairWithQuality, float> getMinValue)
        {
            int num = Mathf.Clamp(Mathf.CeilToInt(trashThreshold / getMinValue(t)), 1, t.thing.stackLimit);

            return(t.GetStatValue(StatDefOf.Mass) * (float)num);
        }
    private void SetCellsAlongAxis(int axis)
    {
        // Normally a Layout Controller should only set horizontal values when invoked for the horizontal axis
        // and only vertical values when invoked for the vertical axis.
        // However, in this case we set both the horizontal and vertical position when invoked for the vertical axis.
        // Since we only set the horizontal position and not the size, it shouldn't affect children's layout,
        // and thus shouldn't break the rule that all horizontal layout must be calculated before all vertical layout.


        float width  = rectTransform.rect.size.x;
        float height = rectTransform.rect.size.y;

        int cellCountX = 1;
        int cellCountY = 1;

        if (cellSize.x + spacing.x <= 0)
        {
            cellCountX = int.MaxValue;
        }
        else
        {
            cellCountX = Mathf.Max(1, Mathf.FloorToInt((width - padding.horizontal + spacing.x + 0.001f) / (cellSize.x + spacing.x)));
        }

        if (cellSize.y + spacing.y <= 0)
        {
            cellCountY = int.MaxValue;
        }
        else
        {
            cellCountY = Mathf.Max(1, Mathf.FloorToInt((height - padding.vertical + spacing.y + 0.001f) / (cellSize.y + spacing.y)));
        }

        cellsPerMainAxis = cellCountX;
        actualCellCountX = Mathf.Clamp(cellCountX, 1, rectChildren.Count);
        actualCellCountY = Mathf.Clamp(cellCountY, 1, Mathf.CeilToInt(rectChildren.Count / (float)cellsPerMainAxis));

        Vector2 requiredSpace = new Vector2(
            actualCellCountX * cellSize.x + (actualCellCountX - 1) * spacing.x,
            actualCellCountY * cellSize.y + (actualCellCountY - 1) * spacing.y
            );
        Vector2 startOffset = new Vector2(
            GetStartOffset(0, requiredSpace.x),
            GetStartOffset(1, requiredSpace.y)
            );

        totalWidth  = 0;
        totalHeight = 0;
        Vector2 currentSpacing = Vector2.zero;

        for (int i = 0; i < rectChildren.Count; i++)
        {
            SetChildAlongAxis(rectChildren[i], 0, startOffset.x + totalWidth /*+ currentSpacing[0]*/, rectChildren[i].rect.size.x);
            SetChildAlongAxis(rectChildren[i], 1, startOffset.y + totalHeight /*+ currentSpacing[1]*/, rectChildren[i].rect.size.y);

            currentSpacing = spacing;

            totalWidth += rectChildren[i].rect.width + currentSpacing[0];

            if (rectChildren[i].rect.height > lastMaxHeight)
            {
                lastMaxHeight = rectChildren[i].rect.height;
            }

            if (i < rectChildren.Count - 1)
            {
                if (totalWidth + rectChildren[i + 1].rect.width + currentSpacing[0] > width)
                {
                    totalWidth    = 0;
                    totalHeight  += lastMaxHeight + currentSpacing[1];
                    lastMaxHeight = 0;
                }
            }
        }
    }
Exemple #8
0
        private void SetCellsAlongAxis(int axis)
        {
            // Normally a Layout Controller should only set horizontal values when invoked for the horizontal axis and only vertical values when invoked for the vertical axis.
            // However, in this case we set both the horizontal and vertical position when invoked for the vertical axis.
            // Since we only set the horizontal position and not the size, it shouldn't affect children's layout,
            // and thus shouldn't break the rule that all horizontal layout must be calculated before all vertical layout.

            if (axis == 0)
            {
                // Only set the sizes when invoked for horizontal axis, not the positions.
                for (int i = 0; i < rectChildren.Count; i++)
                {
                    RectTransform rect = rectChildren[i];
                    m_Tracker.Add(this, rect, DrivenTransformProperties.Anchors | DrivenTransformProperties.AnchoredPosition | DrivenTransformProperties.SizeDelta);
                    rect.anchorMin = Vector2.up;
                    rect.anchorMax = Vector2.up;
                    rect.sizeDelta = cellSize;
                }
                return;
            }

            float width  = rectTransform.rect.size.x;
            float height = rectTransform.rect.size.y;

            int cellCountX = 9;
            int cellCountY = 6;

            int cellsPerMainAxis, actualCellCountX, actualCellCountY;

            cellsPerMainAxis = cellCountX;
            actualCellCountX = Mathf.Clamp(cellCountX, 1, rectChildren.Count);
            actualCellCountY = Mathf.Clamp(cellCountY, 1, Mathf.CeilToInt(rectChildren.Count / (float)cellsPerMainAxis));

            Vector2 requiredSpace = new Vector2(
                actualCellCountX * cellSize.x + (actualCellCountX - 1) * spacing.x,
                actualCellCountY * cellSize.y + (actualCellCountY - 1) * spacing.y
                );
            Vector2 startOffset = new Vector2(
                GetStartOffset(0, requiredSpace.x),
                GetStartOffset(1, requiredSpace.y)
                );

            startOffset += border;

            for (int i = 0; i < rectChildren.Count; i++)
            {
                // Calculate the position based on the starting point and the size
                int positionX = i % 9;
                int positionY = i / 9;


                float offx = 0;
                float offy = 0;
                if (positionX > 2)
                {
                    offx += inner[0];
                }
                if (positionX > 5)
                {
                    offx += inner[0];
                }
                if (positionY > 2)
                {
                    offy += inner[1];
                }

                SetChildAlongAxis(rectChildren[i], 0, startOffset.x + (cellSize[0] + spacing[0]) * positionX + offx, cellSize[0]);
                SetChildAlongAxis(rectChildren[i], 1, startOffset.y + (cellSize[1] + spacing[1]) * positionY + offy, cellSize[1]);
            }
        }
Exemple #9
0
    static private int nextPowerOf2(int x)
    {
        var l = Mathf.CeilToInt(Mathf.Log(x) / Mathf.Log(2));

        return(Mathf.RoundToInt(Mathf.Pow(2, l)));
    }
 public void UpdatePlayerPosition(int x, GameObject standingCube)
 {
     if (x < playerPos)
     {
         GameObject temp = gridLine.Last.Value;
         gridLine.RemoveLast();
         GameObject first = gridLine.First.Value;
         temp.transform.position = new Vector3(first.transform.position.x - cubeWidth, temp.transform.position.y, 0);
         temp.GetComponent <BasicGroundBehavior>().ModifyPosition((int)first.transform.position.x - (int)cubeWidth, x - visibleGridSize / 2, 1);
         gridLine.AddFirst(temp);
         currentCube = currentCube.Previous;
     }
     else if (x > playerPos)
     {
         currentCube = currentCube.Next;
         GameObject temp = gridLine.First.Value;
         gridLine.RemoveFirst();
         GameObject last = gridLine.Last.Value;
         temp.transform.position = new Vector3(last.transform.position.x + cubeWidth, temp.transform.position.y, 0);
         temp.GetComponent <BasicGroundBehavior>().ModifyPosition((int)last.transform.position.x + (int)cubeWidth, x + Mathf.CeilToInt(visibleGridSize / 2) + 2, 1);
         gridLine.AddLast(temp);
     }
     RotateCubesTowardsPlayer();
     playerPos = x;
 }
Exemple #11
0
    public void OnClick()
    {
        AudioSource[] audioSources = GameObject.Find("SEController").GetComponents <AudioSource>();
        audioSources[0].Play();

        //Common
        string simpaleBattlePath = "";

        if (Application.systemLanguage != SystemLanguage.Japanese)
        {
            simpaleBattlePath = "Prefabs/SimpleBattle/BattleBoardEng";
        }
        else
        {
            simpaleBattlePath = "Prefabs/SimpleBattle/BattleBoard";
        }
        GameObject boardObj = Instantiate(Resources.Load(simpaleBattlePath)) as GameObject;

        boardObj.transform.SetParent(GameObject.Find("Map").transform);
        boardObj.transform.localScale = new Vector2(45, 55);
        boardObj.transform.FindChild("No").GetComponent <CloseSimpleBattle>().boardObj = boardObj;
        GameObject battleArea = boardObj.transform.FindChild("Base").transform.FindChild("BattleArea").gameObject;
        GameObject YesBtn     = boardObj.transform.FindChild("Yes").gameObject;
        GameObject NoBtn      = boardObj.transform.FindChild("No").gameObject;

        GetComponent <Button>().enabled = false;
        NoBtn.GetComponent <CloseSimpleBattle>().katanaBtnObj = gameObject;
        boardObj.name = "BattleBoard";

        //Time Stop
        GameObject timer = transform.parent.gameObject;

        timer.GetComponent <ShiroAttack>().rakujyoFlg  = true;
        NoBtn.GetComponent <CloseSimpleBattle>().timer = timer;

        //View Player
        int    jinkei         = PlayerPrefs.GetInt("jinkei");
        string soudaisyoLabel = "soudaisyo" + jinkei;
        int    soudaisyoId    = PlayerPrefs.GetInt(soudaisyoLabel);

        if (soudaisyoId != 0)
        {
            makeSimplePlayer(soudaisyoId, true, battleArea, 0, YesBtn);
        }
        for (int i = 1; i < 26; i++)
        {
            string mapId   = jinkei.ToString() + "map" + i.ToString();
            int    busyoId = PlayerPrefs.GetInt(mapId);
            if (busyoId != 0)
            {
                if (soudaisyoId != busyoId)
                {
                    makeSimplePlayer(busyoId, false, battleArea, i, YesBtn);
                }
            }
        }

        //Same Daimyo Check
        bool sameDaimyoOnFlg = false;

        foreach (GameObject playerObj in GameObject.FindGameObjectsWithTag("Player"))
        {
            int belongDaimyoId = playerObj.GetComponent <SimpleHP>().belongDaimyoId;
            foreach (GameObject playerObj2 in GameObject.FindGameObjectsWithTag("Player"))
            {
                if (playerObj2.GetComponent <SimpleHP>().belongDaimyoId == belongDaimyoId)
                {
                    playerObj.GetComponent <SimpleHP>().numSameDaimyo = playerObj.GetComponent <SimpleHP>().numSameDaimyo + 1;
                    if (playerObj.GetComponent <SimpleHP>().numSameDaimyo == 2)
                    {
                        sameDaimyoOnFlg = true;
                    }
                }
            }
        }

        //Power Up Effection
        if (myDaimyoBusyoFlg)
        {
            foreach (GameObject busyoObj in GameObject.FindGameObjectsWithTag("Player"))
            {
                int atk    = busyoObj.GetComponent <SimpleAttack>().baseAtk;
                int dfc    = busyoObj.GetComponent <SimpleHP>().baseDfc;
                int addAtk = Mathf.CeilToInt((float)atk * (float)addRatioForMyDaimyoBusyo) / 100;
                int addDfc = Mathf.CeilToInt((float)dfc * (float)addRatioForMyDaimyoBusyo) / 100;
                atk = atk + addAtk;
                dfc = dfc + addDfc;
                busyoObj.GetComponent <SimpleAttack>().atk = Mathf.FloorToInt(atk);
                busyoObj.GetComponent <SimpleHP>().dfc     = Mathf.FloorToInt(dfc);
            }
        }
        if (sameDaimyoOnFlg)
        {
            foreach (GameObject busyoObj in GameObject.FindGameObjectsWithTag("Player"))
            {
                int totalAtk      = busyoObj.GetComponent <SimpleAttack>().baseAtk;
                int totalDfc      = busyoObj.GetComponent <SimpleHP>().baseDfc;
                int atk           = busyoObj.GetComponent <SimpleAttack>().atk;
                int dfc           = busyoObj.GetComponent <SimpleHP>().dfc;
                int numSameDaimyo = busyoObj.GetComponent <SimpleHP>().numSameDaimyo;

                int addRatio = (numSameDaimyo - 1) * 5;
                busyoObj.GetComponent <SimpleAttack>().atk = atk + Mathf.FloorToInt(((float)totalAtk * (float)addRatio) / 100);
                busyoObj.GetComponent <SimpleHP>().dfc     = dfc + Mathf.FloorToInt(((float)totalDfc * (float)addRatio) / 100);
            }
        }



        /**View Enemy**/
        //makeSimpleEnemy(enemyBusyoId, battleArea, 0);
        int stageId = timer.GetComponent <ShiroAttack>().toStageId;

        char[]        delimiterChars = { ':' };
        List <string> chldBusyoList  = new List <string>();

        foreach (GameObject gunzeiObj in GameObject.FindGameObjectsWithTag("StageGunzei"))
        {
            int gunzeiToStageId = gunzeiObj.GetComponent <TabStageGunzei>().toStageId;

            if (stageId == gunzeiToStageId)
            {
                int prnt_busyoId = gunzeiObj.GetComponent <TabStageGunzei>().taisyoBusyoId;
                makeSimpleEnemy(prnt_busyoId, battleArea, 0, YesBtn);

                string chld_busyoId = gunzeiObj.GetComponent <TabStageGunzei>().busyoString;
                if (chld_busyoId != "")
                {
                    if (chld_busyoId.Contains(":"))
                    {
                        chldBusyoList.AddRange(new List <string>(chld_busyoId.Split(delimiterChars)));
                    }
                    else
                    {
                        chldBusyoList.Add(chld_busyoId);
                    }
                }
            }
        }
        for (int j = 0; j < chldBusyoList.Count; j++)
        {
            int chldBusyoId = int.Parse(chldBusyoList[j]);
            makeSimpleEnemy(chldBusyoId, battleArea, j, YesBtn);
        }

        //View
        Daimyo     daimyScript     = new Daimyo();
        int        myDaimyoId      = PlayerPrefs.GetInt("myDaimyo");
        string     myDaimyoName    = daimyScript.getName(myDaimyoId);
        string     enemyDaimyoName = daimyScript.getName(enemyDaimyoId);
        GameObject baseObj         = boardObj.transform.FindChild("Base").gameObject;

        if (Application.systemLanguage != SystemLanguage.Japanese)
        {
            baseObj.transform.FindChild("Player").transform.FindChild("Name").GetComponent <TextMesh>().text = myDaimyoName;
            baseObj.transform.FindChild("Enemy").transform.FindChild("Name").GetComponent <TextMesh>().text  = enemyDaimyoName;
        }
        else
        {
            baseObj.transform.FindChild("Player").transform.FindChild("Name").GetComponent <TextMesh>().text = myDaimyoName + "軍";
            baseObj.transform.FindChild("Enemy").transform.FindChild("Name").GetComponent <TextMesh>().text  = enemyDaimyoName + "軍";
        }
        simpleHPCounter playerHPScript = baseObj.transform.FindChild("Player").transform.FindChild("Hei").GetComponent <simpleHPCounter>();
        simpleHPCounter enemyHPScript  = baseObj.transform.FindChild("Enemy").transform.FindChild("Hei").GetComponent <simpleHPCounter>();

        playerHPScript.board        = boardObj;
        enemyHPScript.board         = boardObj;
        enemyHPScript.stageId       = stageId;
        playerHPScript.katanaBtnObj = gameObject;
        playerHPScript.timer        = timer;
        playerHPScript.stageId      = stageId;
    }
Exemple #12
0
        internal static void DecomposeHdrColor(
            Color linearColorHdr,
            out Color32 baseLinearColor,
            out float exposure)
        {
            baseLinearColor = Color32.op_Implicit(linearColorHdr);
            float maxColorComponent = ((Color) ref linearColorHdr).get_maxColorComponent();
            byte  num1 = 191;

            if ((double)maxColorComponent == 0.0 || (double)maxColorComponent <= 1.0 && (double)maxColorComponent >= 0.00392156885936856)
            {
                exposure          = 0.0f;
                baseLinearColor.r = (__Null)(int)(byte)Mathf.RoundToInt((float)(linearColorHdr.r * (double)byte.MaxValue));
                baseLinearColor.g = (__Null)(int)(byte)Mathf.RoundToInt((float)(linearColorHdr.g * (double)byte.MaxValue));
                baseLinearColor.b = (__Null)(int)(byte)Mathf.RoundToInt((float)(linearColorHdr.b * (double)byte.MaxValue));
            }
            else
            {
                float num2 = (float)num1 / maxColorComponent;
                exposure          = Mathf.Log((float)byte.MaxValue / num2) / Mathf.Log(2f);
                baseLinearColor.r = (__Null)(int)(byte)Mathf.Min((int)num1, (int)(byte)Mathf.CeilToInt(num2 * (float)linearColorHdr.r));
                baseLinearColor.g = (__Null)(int)(byte)Mathf.Min((int)num1, (int)(byte)Mathf.CeilToInt(num2 * (float)linearColorHdr.g));
                baseLinearColor.b = (__Null)(int)(byte)Mathf.Min((int)num1, (int)(byte)Mathf.CeilToInt(num2 * (float)linearColorHdr.b));
            }
        }
        private IEnumerator HandleSoldItem(PickupObject targetItem)
        {
            if (!targetItem)
            {
                m_currentlySellingAnItem = false; yield break;
            }
            while (m_currentlySellingAnItem)
            {
                yield return(null);
            }
            m_currentlySellingAnItem = true;
            targetItem.IsBeingSold   = true;
            float magnitude = (targetItem.sprite.WorldCenter - specRigidbody.UnitCenter).magnitude;

            if (!targetItem.sprite || magnitude > 1.8f)
            {
                targetItem.IsBeingSold   = false;
                m_currentlySellingAnItem = false;
                yield break;
            }
            IPlayerInteractable ixable = null;

            if (targetItem is PassiveItem)
            {
                PassiveItem passiveItem = targetItem as PassiveItem;
                passiveItem.GetRidOfMinimapIcon();
                ixable = (targetItem as PassiveItem);
            }
            else if (targetItem is Gun)
            {
                Gun gun = targetItem as Gun;
                gun.GetRidOfMinimapIcon();
                ixable = (targetItem as Gun);
            }
            else if (targetItem is PlayerItem)
            {
                PlayerItem playerItem = targetItem as PlayerItem;
                playerItem.GetRidOfMinimapIcon();
                ixable = (targetItem as PlayerItem);
            }
            if (ixable != null)
            {
                RoomHandler.unassignedInteractableObjects.Remove(ixable);
                GameManager.Instance.PrimaryPlayer.RemoveBrokenInteractable(ixable);
            }
            float          elapsed      = 0f;
            float          duration     = 0.5f;
            Vector3        startPos     = targetItem.transform.position;
            Vector3        finalOffset  = Vector3.zero;
            tk2dBaseSprite targetSprite = targetItem.GetComponentInChildren <tk2dBaseSprite>();

            if (targetSprite)
            {
                finalOffset = targetSprite.GetBounds().extents;
            }
            while (elapsed < duration)
            {
                elapsed += BraveTime.DeltaTime;
                if (!targetItem || !targetItem.transform)
                {
                    m_currentlySellingAnItem = false; yield break;
                }
                targetItem.transform.localScale = Vector3.Lerp(Vector3.one, new Vector3(0.01f, 0.01f, 1f), elapsed / duration);
                targetItem.transform.position   = Vector3.Lerp(startPos, startPos + new Vector3(finalOffset.x, 0f, 0f), elapsed / duration);
                yield return(null);
            }
            if (!targetItem || !targetItem.transform)
            {
                m_currentlySellingAnItem = false; yield break;
            }
            SellPitDweller.SendPlaymakerEvent("playerSoldSomething");
            int sellPrice = Mathf.Clamp(Mathf.CeilToInt(targetItem.PurchasePrice * SellValueModifier), 0, 200);

            if (targetItem.quality == PickupObject.ItemQuality.SPECIAL || targetItem.quality == PickupObject.ItemQuality.EXCLUDED)
            {
                sellPrice = 3;
            }
            LootEngine.SpawnCurrency(targetItem.sprite.WorldCenter, sellPrice, false);
            m_thingsSold++;
            if (targetItem.PickupObjectId == GlobalItemIds.MasteryToken_Castle || targetItem.PickupObjectId == GlobalItemIds.MasteryToken_Catacombs || targetItem.PickupObjectId == GlobalItemIds.MasteryToken_Gungeon || targetItem.PickupObjectId == GlobalItemIds.MasteryToken_Forge || targetItem.PickupObjectId == GlobalItemIds.MasteryToken_Mines)
            {
                m_masteryRoundsSold++;
            }
            if (targetItem is Gun && targetItem.GetComponentInParent <DebrisObject>())
            {
                Destroy(targetItem.transform.parent.gameObject);
            }
            else
            {
                Destroy(targetItem.gameObject);
            }
            if (m_thingsSold >= 3 && m_masteryRoundsSold > 0)
            {
                StartCoroutine(HandleSellPitOpening());
            }
            m_currentlySellingAnItem = false;
            yield break;
        }
Exemple #14
0
 public int GetScore()
 {
     return(Mathf.CeilToInt(score));
 }
Exemple #15
0
        public override void SetupBehavior()
        {
            base.SetupBehavior();

            poisonBuff = ScriptableObject.CreateInstance <BuffDef>();
            //poisonBuff.buffColor = new Color32(66, 28, 82, 255);
            poisonBuff.canStack   = false;
            poisonBuff.isDebuff   = true;
            poisonBuff.name       = "CCIThalliumPoison";
            poisonBuff.iconSprite = assetBundle.LoadAsset <Sprite>("Assets/ClassicItems/Icons/thallium_buff_icon.png");

            CustomBuff thalliumCustomBuff = new CustomBuff(poisonBuff);

            BuffAPI.Add(thalliumCustomBuff);

            DotController.DotDef thalliumDotDef = new DotController.DotDef
            {
                interval          = .5f,
                damageCoefficient = 1,
                damageColorIndex  = DamageColorIndex.DeathMark,
                associatedBuff    = poisonBuff
            };
            poisonDot = DotAPI.RegisterDotDef(thalliumDotDef, (dotController, dotStack) =>
            {
                CharacterBody attackerBody = dotStack.attackerObject.GetComponent <CharacterBody>();
                if (attackerBody)
                {
                    float damageMultiplier = dmgCoefficient + dmgStack * (GetCount(attackerBody) - 1);
                    float poisonDamage     = 0f;
                    if (dotController.victimBody)
                    {
                        poisonDamage += dotController.victimBody.damage;
                    }
                    dotStack.damage = poisonDamage * damageMultiplier;
                }
            });

            if (Compat_ItemStats.enabled)
            {
                Compat_ItemStats.CreateItemStatDef(itemDef,
                                                   (
                                                       (count, inv, master) => { return(Mathf.Min(procChance + stackChance * (count - 1), capChance)); },
                                                       (value, inv, master) => { return($"Poison Chance: {Pct(value, 0, 1)}"); }
                                                   ),
                                                   (
                                                       (count, inv, master) => { return(dmgCoefficient + (count - 1) * dmgStack); },
                                                       (value, inv, master) => { return($"Victim damage per second: {Pct(value, 0)}"); }
                                                   ),
                                                   (
                                                       (count, inv, master) => { return(duration); },
                                                       (value, inv, master) => { return($"Poison Duration: {value}"); }
                                                   ));
            }
            if (Compat_BetterUI.enabled)
            {
                Compat_BetterUI.AddEffect(itemDef, procChance, stackChance, Compat_BetterUI.ChanceFormatter, Compat_BetterUI.LinearStacking,
                                          (value, extraStackValue, procCoefficient) =>
                {
                    return(Mathf.CeilToInt((capChance - value * procCoefficient) / (extraStackValue * procCoefficient)) + 1);
                });
            }
        }
        /*
         *      Packed rects may exceed atlas size and require scaling
         *      When scaling want pixel perfect fit in atlas. Corners of rects should exactly align with pixel grid
         *      Padding should be subtracted from pixel perfect rect to create pixel perfect square
         */

        internal bool ScaleAtlasToFitMaxDim(Vector2 rootWH, List <Image> images, int maxDimension, int padding, int minImageSizeX, int minImageSizeY, int masterImageSizeX, int masterImageSizeY,
                                            ref int outW, ref int outH, out float padX, out float padY, out int newMinSizeX, out int newMinSizeY)
        {
            newMinSizeX = minImageSizeX;
            newMinSizeY = minImageSizeY;
            bool redoPacking = false;

            //AtlasPackingResult[] rs = null;

            // the atlas may be packed larger than the maxDimension. If so then the atlas needs to be scaled down to fit
            padX = (float)padding / (float)outW; //padding needs to be pixel perfect in size
            if (rootWH.x > maxDimension)
            {
                padX = (float)padding / (float)maxDimension;
                float scaleFactor = (float)maxDimension / (float)rootWH.x;
                if (LOG_LEVEL >= MB2_LogLevel.warn)
                {
                    Debug.LogWarning("Packing exceeded atlas width shrinking to " + scaleFactor);
                }
                for (int i = 0; i < images.Count; i++)
                {
                    Image im = images[i];
                    if (im.w * scaleFactor < masterImageSizeX)
                    { //check if small images will be rounded too small. If so need to redo packing forcing a larger min size
                        if (LOG_LEVEL >= MB2_LogLevel.debug)
                        {
                            Debug.Log("Small images are being scaled to zero. Will need to redo packing with larger minTexSizeX.");
                        }
                        redoPacking = true;
                        newMinSizeX = Mathf.CeilToInt(minImageSizeX / scaleFactor);
                    }
                    int right = (int)((im.x + im.w) * scaleFactor);
                    im.x = (int)(scaleFactor * im.x);
                    im.w = right - im.x;
                }
                outW = maxDimension;
            }

            padY = (float)padding / (float)outH;
            if (rootWH.y > maxDimension)
            {
                //float minSizeY = ((float)minImageSizeY + 1) / maxDimension;
                padY = (float)padding / (float)maxDimension;
                float scaleFactor = (float)maxDimension / (float)rootWH.y;
                if (LOG_LEVEL >= MB2_LogLevel.warn)
                {
                    Debug.LogWarning("Packing exceeded atlas height shrinking to " + scaleFactor);
                }
                for (int i = 0; i < images.Count; i++)
                {
                    Image im = images[i];
                    if (im.h * scaleFactor < masterImageSizeY)
                    { //check if small images will be rounded too small. If so need to redo packing forcing a larger min size
                        if (LOG_LEVEL >= MB2_LogLevel.debug)
                        {
                            Debug.Log("Small images are being scaled to zero. Will need to redo packing with larger minTexSizeY.");
                        }
                        redoPacking = true;
                        newMinSizeY = Mathf.CeilToInt(minImageSizeY / scaleFactor);
                    }
                    int bottom = (int)((im.y + im.h) * scaleFactor);
                    im.y = (int)(scaleFactor * im.y);
                    im.h = bottom - im.y;
                }
                outH = maxDimension;
            }
            return(redoPacking);
        }
Exemple #17
0
    void  UpdateWheelGraphics(Vector3 relativeVelocity)
    {
        wheelCount = -1;

        foreach (Wheel w in wheels)
        {
            wheelCount++;
            WheelCollider wheel = w.collider;
            WheelHit      wh    = new WheelHit();

            // First we get the velocity at the point where the wheel meets the ground, if the wheel is touching the ground
            if (wheel.GetGroundHit(out wh))
            {
                w.wheelGraphic.localPosition = wheel.transform.up * (wheelRadius + wheel.transform.InverseTransformPoint(wh.point).y);
                w.wheelVelo   = rigidbody.GetPointVelocity(wh.point);
                w.groundSpeed = w.wheelGraphic.InverseTransformDirection(w.wheelVelo);

                // Code to handle skidmark drawing. Not covered in the tutorial
                if (skidmarks)
                {
                    if (skidmarkTime[wheelCount] < 0.02f && w.lastSkidmark != -1)
                    {
                        skidmarkTime[wheelCount] += Time.deltaTime;
                    }
                    else
                    {
                        float dt = skidmarkTime[wheelCount] == 0.0f ? Time.deltaTime : skidmarkTime[wheelCount];
                        skidmarkTime[wheelCount] = 0.0f;

                        float handbrakeSkidding = handbrake && w.driveWheel ? w.wheelVelo.magnitude * 0.3f : 0;
                        float skidGroundSpeed   = Mathf.Abs(w.groundSpeed.x) - 15;
                        if (skidGroundSpeed > 0 || handbrakeSkidding > 0)
                        {
                            Vector3 staticVel = transform.TransformDirection(skidSmoke.localVelocity) + skidSmoke.worldVelocity;
                            if (w.lastSkidmark != -1)
                            {
                                float emission             = UnityEngine.Random.Range(skidSmoke.minEmission, skidSmoke.maxEmission);
                                float lastParticleCount    = w.lastEmitTime * emission;
                                float currentParticleCount = Time.time * emission;
                                int   noOfParticles        = Mathf.CeilToInt(currentParticleCount) - Mathf.CeilToInt(lastParticleCount);
                                int   lastParticle         = Mathf.CeilToInt(lastParticleCount);

                                for (int i = 0; i <= noOfParticles; i++)
                                {
                                    float particleTime = Mathf.InverseLerp(lastParticleCount, currentParticleCount, lastParticle + i);
                                    skidSmoke.Emit(Vector3.Lerp(w.lastEmitPosition, wh.point, particleTime) + new Vector3(Random.Range(-0.1f, 0.1f), Random.Range(-0.1f, 0.1f), Random.Range(-0.1f, 0.1f)), staticVel + (w.wheelVelo * 0.05f), Random.Range(skidSmoke.minSize, skidSmoke.maxSize) * Mathf.Clamp(skidGroundSpeed * 0.1f, 0.5f, 1), Random.Range(skidSmoke.minEnergy, skidSmoke.maxEnergy), Color.white);
                                }
                            }
                            else
                            {
                                skidSmoke.Emit(wh.point + new Vector3(Random.Range(-0.1f, 0.1f), Random.Range(-0.1f, 0.1f), Random.Range(-0.1f, 0.1f)), staticVel + (w.wheelVelo * 0.05f), Random.Range(skidSmoke.minSize, skidSmoke.maxSize) * Mathf.Clamp(skidGroundSpeed * 0.1f, 0.5f, 1), Random.Range(skidSmoke.minEnergy, skidSmoke.maxEnergy), Color.white);
                            }

                            w.lastEmitPosition = wh.point;
                            w.lastEmitTime     = Time.time;

                            w.lastSkidmark = skidmarks.AddSkidMark(wh.point + rigidbody.velocity * dt, wh.normal, (skidGroundSpeed * 0.1f + handbrakeSkidding) * Mathf.Clamp01(wh.force / wheel.suspensionSpring.spring), w.lastSkidmark);
//						sound.Skid(true, Mathf.Clamp01(skidGroundSpeed * 0.1f));
                        }
                        else
                        {
                            w.lastSkidmark = -1;
//						sound.Skid(false, 0);
                        }
                    }
                }
            }
            else
            {
                // If the wheel is not touching the ground we set the position of the wheel graphics to
                // the wheel's transform position + the range of the suspension.
                w.wheelGraphic.position = wheel.transform.position + (-wheel.transform.up * suspensionRange);
                if (w.steerWheel)
                {
                    w.wheelVelo *= 0.9f;
                }
                else
                {
                    w.wheelVelo *= 0.9f * (1 - throttle);
                }

                if (skidmarks)
                {
                    w.lastSkidmark = -1;
//				sound.Skid(false, 0);
                }
            }
            // If the wheel is a steer wheel we apply two rotations:
            // *Rotation around the Steer Column (visualizes the steer direction)
            // *Rotation that visualizes the speed
            if (w.steerWheel)
            {
                Vector3 ea = w.wheelGraphic.parent.localEulerAngles;
                ea.y = steer * maximumTurn;
                w.wheelGraphic.parent.localEulerAngles = ea;
                w.tireGraphic.Rotate(Vector3.right * (w.groundSpeed.z / wheelRadius) * Time.deltaTime * Mathf.Rad2Deg);
            }
            else if (!handbrake && w.driveWheel)
            {
                // If the wheel is a drive wheel it only gets the rotation that visualizes speed.
                // If we are hand braking we don't rotate it.
                w.tireGraphic.Rotate(Vector3.right * (w.groundSpeed.z / wheelRadius) * Time.deltaTime * Mathf.Rad2Deg);
            }
        }
    }
        //------------------ Algorithm for fitting everything into one atlas and scaling down
        //
        // for images being added calc area, maxW, maxH. A perfectly packed atlas will match area exactly. atlas must be at least maxH and maxW in size.
        // Sort images from big to small using either height, width or area comparer
        // Explore space to find a resonably efficient packing. Grow the atlas gradually until a fit is found
        // Scale atlas to fit
        //
        AtlasPackingResult _GetRectsSingleAtlas(List <Vector2> imgWidthHeights, int maxDimension, int padding, int minImageSizeX, int minImageSizeY, int masterImageSizeX, int masterImageSizeY, int recursionDepth)
        {
            if (LOG_LEVEL >= MB2_LogLevel.debug)
            {
                Debug.Log(String.Format("_GetRects numImages={0}, maxDimension={1}, padding={2}, minImageSizeX={3}, minImageSizeY={4}, masterImageSizeX={5}, masterImageSizeY={6}, recursionDepth={7}",
                                        imgWidthHeights.Count, maxDimension, padding, minImageSizeX, minImageSizeY, masterImageSizeX, masterImageSizeY, recursionDepth));
            }
            if (recursionDepth > 10)
            {
                if (LOG_LEVEL >= MB2_LogLevel.error)
                {
                    Debug.LogError("Maximum recursion depth reached. Couldn't find packing for these textures.");
                }
                return(null);
            }
            float area = 0;
            int   maxW = 0;
            int   maxH = 0;

            Image[] imgsToAdd = new Image[imgWidthHeights.Count];
            for (int i = 0; i < imgsToAdd.Length; i++)
            {
                int   iw = (int)imgWidthHeights[i].x;
                int   ih = (int)imgWidthHeights[i].y;
                Image im = imgsToAdd[i] = new Image(i, iw, ih, padding, minImageSizeX, minImageSizeY);
                area += im.w * im.h;
                maxW  = Mathf.Max(maxW, im.w);
                maxH  = Mathf.Max(maxH, im.h);
            }

            if ((float)maxH / (float)maxW > 2)
            {
                if (LOG_LEVEL >= MB2_LogLevel.debug)
                {
                    MB2_Log.LogDebug("Using height Comparer");
                }
                Array.Sort(imgsToAdd, new ImageHeightComparer());
            }
            else if ((float)maxH / (float)maxW < .5)
            {
                if (LOG_LEVEL >= MB2_LogLevel.debug)
                {
                    MB2_Log.LogDebug("Using width Comparer");
                }
                Array.Sort(imgsToAdd, new ImageWidthComparer());
            }
            else
            {
                if (LOG_LEVEL >= MB2_LogLevel.debug)
                {
                    MB2_Log.LogDebug("Using area Comparer");
                }
                Array.Sort(imgsToAdd, new ImageAreaComparer());
            }

            //explore the space to find a resonably efficient packing
            int sqrtArea = (int)Mathf.Sqrt(area);
            int idealAtlasW;
            int idealAtlasH;

            if (atlasMustBePowerOfTwo)
            {
                idealAtlasW = idealAtlasH = RoundToNearestPositivePowerOfTwo(sqrtArea);
                if (maxW > idealAtlasW)
                {
                    idealAtlasW = CeilToNearestPowerOfTwo(idealAtlasW);
                }
                if (maxH > idealAtlasH)
                {
                    idealAtlasH = CeilToNearestPowerOfTwo(idealAtlasH);
                }
            }
            else
            {
                idealAtlasW = sqrtArea;
                idealAtlasH = sqrtArea;
                if (maxW > sqrtArea)
                {
                    idealAtlasW = maxW;
                    idealAtlasH = Mathf.Max(Mathf.CeilToInt(area / maxW), maxH);
                }
                if (maxH > sqrtArea)
                {
                    idealAtlasW = Mathf.Max(Mathf.CeilToInt(area / maxH), maxW);
                    idealAtlasH = maxH;
                }
            }

            if (idealAtlasW == 0)
            {
                idealAtlasW = 4;
            }
            if (idealAtlasH == 0)
            {
                idealAtlasH = 4;
            }
            int stepW = (int)(idealAtlasW * .15f);
            int stepH = (int)(idealAtlasH * .15f);

            if (stepW == 0)
            {
                stepW = 1;
            }
            if (stepH == 0)
            {
                stepH = 1;
            }
            int numWIterations = 2;
            int steppedWidth   = idealAtlasW;
            int steppedHeight  = idealAtlasH;

            while (numWIterations >= 1 && steppedHeight < sqrtArea * 1000)
            {
                bool successW = false;
                numWIterations = 0;
                steppedWidth   = idealAtlasW;
                while (!successW && steppedWidth < sqrtArea * 1000)
                {
                    ProbeResult pr = new ProbeResult();
                    if (LOG_LEVEL >= MB2_LogLevel.trace)
                    {
                        Debug.Log("Probing h=" + steppedHeight + " w=" + steppedWidth);
                    }
                    if (ProbeSingleAtlas(imgsToAdd, steppedWidth, steppedHeight, area, maxDimension, pr))
                    {
                        successW = true;
                        if (bestRoot == null)
                        {
                            bestRoot = pr;
                        }
                        else if (pr.GetScore(atlasMustBePowerOfTwo) > bestRoot.GetScore(atlasMustBePowerOfTwo))
                        {
                            bestRoot = pr;
                        }
                    }
                    else
                    {
                        numWIterations++;
                        steppedWidth = StepWidthHeight(steppedWidth, stepW, maxDimension);
                        if (LOG_LEVEL >= MB2_LogLevel.trace)
                        {
                            MB2_Log.LogDebug("increasing Width h=" + steppedHeight + " w=" + steppedWidth);
                        }
                    }
                }
                steppedHeight = StepWidthHeight(steppedHeight, stepH, maxDimension);
                if (LOG_LEVEL >= MB2_LogLevel.debug)
                {
                    MB2_Log.LogDebug("increasing Height h=" + steppedHeight + " w=" + steppedWidth);
                }
            }
            if (bestRoot == null)
            {
                return(null);
            }

            int outW = 0;
            int outH = 0;

            if (atlasMustBePowerOfTwo)
            {
                outW = Mathf.Min(CeilToNearestPowerOfTwo(bestRoot.w), maxDimension);
                outH = Mathf.Min(CeilToNearestPowerOfTwo(bestRoot.h), maxDimension);
                if (outH < outW / 2)
                {
                    outH = outW / 2;                                  //smaller dim can't be less than half larger
                }
                if (outW < outH / 2)
                {
                    outW = outH / 2;
                }
            }
            else
            {
                outW = Mathf.Min(bestRoot.w, maxDimension);
                outH = Mathf.Min(bestRoot.h, maxDimension);
            }

            bestRoot.outW = outW;
            bestRoot.outH = outH;
            if (LOG_LEVEL >= MB2_LogLevel.debug)
            {
                Debug.Log("Best fit found: atlasW=" + outW + " atlasH" + outH + " w=" + bestRoot.w + " h=" + bestRoot.h + " efficiency=" + bestRoot.efficiency + " squareness=" + bestRoot.squareness + " fits in max dimension=" + bestRoot.largerOrEqualToMaxDim);
            }

            //Debug.Assert(images.Count != imgsToAdd.Length, "Result images not the same lentgh as source"));

            //the atlas can be larger than the max dimension scale it if this is the case
            //int newMinSizeX = minImageSizeX;
            //int	newMinSizeY = minImageSizeY;


            List <Image> images = new List <Image>();

            flattenTree(bestRoot.root, images);
            images.Sort(new ImgIDComparer());
            // the atlas may be packed larger than the maxDimension. If so then the atlas needs to be scaled down to fit
            Vector2 rootWH = new Vector2(bestRoot.w, bestRoot.h);
            float   padX, padY;
            int     newMinSizeX, newMinSizeY;

            if (!ScaleAtlasToFitMaxDim(rootWH, images, maxDimension, padding, minImageSizeX, minImageSizeY, masterImageSizeX, masterImageSizeY,
                                       ref outW, ref outH, out padX, out padY, out newMinSizeX, out newMinSizeY))
            {
                AtlasPackingResult res = new AtlasPackingResult();
                res.rects      = new Rect[images.Count];
                res.srcImgIdxs = new int[images.Count];
                res.atlasX     = outW;
                res.atlasY     = outH;
                res.usedW      = -1;
                res.usedH      = -1;
                for (int i = 0; i < images.Count; i++)
                {
                    Image im = images[i];
                    Rect  r  = res.rects[i] = new Rect((float)im.x / (float)outW + padX,
                                                       (float)im.y / (float)outH + padY,
                                                       (float)im.w / (float)outW - padX * 2f,
                                                       (float)im.h / (float)outH - padY * 2f);
                    res.srcImgIdxs[i] = im.imgId;
                    if (LOG_LEVEL >= MB2_LogLevel.debug)
                    {
                        MB2_Log.LogDebug("Image: " + i + " imgID=" + im.imgId + " x=" + r.x * outW +
                                         " y=" + r.y * outH + " w=" + r.width * outW +
                                         " h=" + r.height * outH + " padding=" + padding);
                    }
                }
                return(res);
            }
            else
            {
                if (LOG_LEVEL >= MB2_LogLevel.debug)
                {
                    Debug.Log("==================== REDOING PACKING ================");
                }
                //root = null;
                return(_GetRectsSingleAtlas(imgWidthHeights, maxDimension, padding, newMinSizeX, newMinSizeY, masterImageSizeX, masterImageSizeY, recursionDepth + 1));
            }


            //if (LOG_LEVEL >= MB2_LogLevel.debug) MB2_Log.LogDebug(String.Format("Done GetRects atlasW={0} atlasH={1}", bestRoot.w, bestRoot.h));

            //return res;
        }
Exemple #19
0
        public void FrameUpdate(PipelineCamera cam, ref PipelineCommandData data)
        {
            if (!Decal.decalDatas.isCreated)
            {
                return;
            }
            CommandBuffer buffer = data.buffer;

            handle.Complete();
            if (cullJob.count > decalBuffer.count)
            {
                int oldCount = decalBuffer.count;
                decalBuffer.Dispose();
                decalBuffer = new ComputeBuffer((int)max(oldCount * 1.5f, cullJob.count), sizeof(DecalStrct));
            }
            if (!minMaxBoundMat)
            {
                minMaxBoundMat = new Material(data.resources.shaders.minMaxDepthBounding);
            }
            int pixelWidth  = cam.cam.pixelWidth;
            int pixelHeight = cam.cam.pixelHeight;

            if (enableSorting)
            {
                decalBuffer.SetDataPtr(sortJob.sortedDecalDatas.unsafePtr, 0, cullJob.count);
            }
            else
            {
                decalBuffer.SetData(decalCullResults, 0, 0, cullJob.count);
            }
            buffer.GetTemporaryRT(_DownSampledDepth0, pixelWidth / 2, pixelHeight / 2, 0, FilterMode.Point, RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear, 1, false, RenderTextureMemoryless.None, false);
            buffer.GetTemporaryRT(_DownSampledDepth1, pixelWidth / 4, pixelHeight / 4, 0, FilterMode.Point, RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear, 1, false, RenderTextureMemoryless.None, false);
            buffer.GetTemporaryRT(_DownSampledDepth2, pixelWidth / 8, pixelHeight / 8, 0, FilterMode.Point, RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear, 1, false, RenderTextureMemoryless.None, false);
            buffer.GetTemporaryRT(_DownSampledDepth3, pixelWidth / 16, pixelHeight / 16, 0, FilterMode.Point, RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear, 1, false, RenderTextureMemoryless.None, false);
            buffer.BlitSRT(_DownSampledDepth0, minMaxBoundMat, 0);
            buffer.SetGlobalTexture(ShaderIDs._TargetDepthTexture, _DownSampledDepth0);
            buffer.BlitSRT(_DownSampledDepth1, minMaxBoundMat, 1);
            buffer.SetGlobalTexture(ShaderIDs._TargetDepthTexture, _DownSampledDepth1);
            buffer.BlitSRT(_DownSampledDepth2, minMaxBoundMat, 1);
            buffer.SetGlobalTexture(ShaderIDs._TargetDepthTexture, _DownSampledDepth2);
            buffer.BlitSRT(_DownSampledDepth3, minMaxBoundMat, 1);
            int2 tileSize = int2(pixelWidth / 16, pixelHeight / 16);
            RenderTextureDescriptor lightTileDisc = new RenderTextureDescriptor
            {
                autoGenerateMips  = false,
                bindMS            = false,
                colorFormat       = RenderTextureFormat.RInt,
                depthBufferBits   = 0,
                dimension         = TextureDimension.Tex3D,
                enableRandomWrite = true,
                width             = tileSize.x,
                height            = tileSize.y,
                msaaSamples       = 1,
                volumeDepth       = CBDRSharedData.MAXLIGHTPERTILE
            };

            buffer.GetTemporaryRT(ShaderIDs._DecalTile, lightTileDisc);
            tileSizeArray[0] = tileSize.x;
            tileSizeArray[1] = tileSize.y;
            buffer.SetComputeVectorParam(cbdrShader, ShaderIDs._CameraPos, cam.cam.transform.position);
            buffer.SetComputeIntParams(cbdrShader, ShaderIDs._TileSize, tileSizeArray);
            buffer.SetGlobalVector(ShaderIDs._TileSize, new Vector4(tileSize.x - 0.5f, tileSize.y - 0.5f));
            buffer.SetComputeVectorParam(cbdrShader, ShaderIDs._CameraForward, cam.cam.transform.forward);
            buffer.SetComputeTextureParam(cbdrShader, CBDRSharedData.DecalCull, ShaderIDs._DepthBoundTexture, new RenderTargetIdentifier(_DownSampledDepth3));
            buffer.SetComputeTextureParam(cbdrShader, CBDRSharedData.DecalCull, ShaderIDs._DecalTile, new RenderTargetIdentifier(ShaderIDs._DecalTile));
            buffer.SetComputeBufferParam(cbdrShader, CBDRSharedData.DecalCull, ShaderIDs._AllDecals, decalBuffer);
            buffer.SetComputeIntParam(cbdrShader, ShaderIDs._DecalCount, cullJob.count);
            buffer.SetGlobalBuffer(ShaderIDs._AllDecals, decalBuffer);
            buffer.DispatchCompute(cbdrShader, CBDRSharedData.DecalCull, Mathf.CeilToInt(tileSize.x / 8f), Mathf.CeilToInt(tileSize.y / 8f), 1);
            buffer.ReleaseTemporaryRT(_DownSampledDepth0);
            buffer.ReleaseTemporaryRT(_DownSampledDepth1);
            buffer.ReleaseTemporaryRT(_DownSampledDepth2);
            buffer.ReleaseTemporaryRT(_DownSampledDepth3);
            RenderPipeline.ReleaseRTAfterFrame(ShaderIDs._DecalTile);
            decalCullResults.Dispose();
            if (enableSorting)
            {
                decalCompareResults.Dispose();
            }
        }
Exemple #20
0
        public static TileSheet GenerateWallTextureSheet(List <WallTextureData> textureList, Dictionary <string, SpriteData> patches, PaletteData paletteData, int padding)
        {
            var widest  = 0;
            var tallest = 0;

            foreach (var t in textureList)
            {
                if (t.Width > widest)
                {
                    widest = t.Width;
                }
                if (t.Height > tallest)
                {
                    tallest = t.Height;
                }
            }

            var largest = widest > tallest ? widest : tallest;

            var rowCount = Mathf.CeilToInt(Mathf.Sqrt(textureList.Count));

            if (rowCount % 2 != 0)
            {
                rowCount++;
            }

            var w = rowCount * largest;
            var h = rowCount * largest;

            w += rowCount * padding * 2;
            h += rowCount * padding * 2;

            var spriteSheet = new TileSheet();

            spriteSheet.Rows       = rowCount;
            spriteSheet.Columns    = rowCount;
            spriteSheet.TileWidth  = largest;
            spriteSheet.TileHeight = largest;
            spriteSheet.Padding    = padding;
            spriteSheet.Texture    = new Texture2D(w, h);

            int index = 0;

            foreach (var t in textureList)
            {
                var tex = GenerateWallTexture(t, patches, paletteData);

                var destX = (largest + padding * 2) * (index % rowCount) + padding;
                var destY = (largest + padding * 2) * (index / rowCount) + padding;

                //Debug.Log(t.Name);
                var source = tex.GetPixels();
                spriteSheet.Texture.SetPixels(destX, destY, tex.width, tex.height, source);

                // Padding
                for (var i = 1; i <= padding; i++)
                {
                    for (var x = 0; x < tex.width; x++)
                    {
                        spriteSheet.Texture.SetPixel(destX + x, destY - i, tex.GetPixel(x, 0));
                        spriteSheet.Texture.SetPixel(destX + x, (destY + (tex.height - 1)) + i, tex.GetPixel(x, tex.height - 1));
                    }

                    for (var y = 0; y < tex.height; y++)
                    {
                        spriteSheet.Texture.SetPixel(destX - i, (destY) + y, tex.GetPixel(0, y));
                        spriteSheet.Texture.SetPixel((destX + (tex.width - 1)) + i, (destY) + y, tex.GetPixel(tex.width - 1, y));
                    }
                }

                for (var x = 0; x < padding; x++)
                {
                    for (var y = 0; y < padding; y++)
                    {
                        spriteSheet.Texture.SetPixel((destX - padding) + x, (destY - 2) + y, tex.GetPixel(0, 0));
                        spriteSheet.Texture.SetPixel((destX + tex.width) + x, (destY - 2) + y, tex.GetPixel(tex.width - 1, 0));
                        spriteSheet.Texture.SetPixel((destX + tex.width) + x, (destY + tex.height) + y, tex.GetPixel(tex.width - 1, tex.height - 1));
                        spriteSheet.Texture.SetPixel((destX - padding) + x, (destY + tex.height) + y, tex.GetPixel(0, tex.height - 1));
                    }
                }


                spriteSheet.LookupTable.Add(t.Name, new TileSheetSprite()
                {
                    TileNum = index,
                    Width   = tex.width,
                    Height  = tex.height
                });

                index++;
            }

            spriteSheet.Texture.Apply();

            return(spriteSheet);
        }
        public void SimulationStep(ushort lineID)
        {
            TransportInfo info = this.Info;

            if (this.Complete)
            {
                int num = 0;
                if (this.m_vehicles != 0)
                {
                    VehicleManager instance = Singleton <VehicleManager> .instance;
                    ushort         num2     = this.m_vehicles;
                    int            num3     = 0;
                    while (num2 != 0)
                    {
                        ushort nextLineVehicle = instance.m_vehicles.m_buffer [(int)num2].m_nextLineVehicle;
                        num++;
                        num2 = nextLineVehicle;
                        if (++num3 > 65536)
                        {
                            CODebugBase <LogChannel> .Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace);

                            break;
                        }
                    }
                }
                bool flag;
                if (Singleton <SimulationManager> .instance.m_isNightTime)
                {
                    flag = ((this.m_flags & TransportLine.Flags.DisabledNight) == TransportLine.Flags.None);
                }
                else
                {
                    flag = ((this.m_flags & TransportLine.Flags.DisabledDay) == TransportLine.Flags.None);
                }
                uint  num4 = 0u;
                float num5 = 0f;
                if (this.m_stops != 0)
                {
                    NetManager instance2 = Singleton <NetManager> .instance;
                    ushort     stops     = this.m_stops;
                    ushort     num6      = stops;
                    int        num7      = 0;
                    while (num6 != 0)
                    {
                        ushort num8 = 0;
                        if (flag)
                        {
                            NetNode[] expr_107_cp_0 = instance2.m_nodes.m_buffer;
                            ushort    expr_107_cp_1 = num6;
                            expr_107_cp_0 [(int)expr_107_cp_1].m_flags = (expr_107_cp_0 [(int)expr_107_cp_1].m_flags & ~NetNode.Flags.Disabled);
                        }
                        else
                        {
                            NetNode[] expr_12D_cp_0 = instance2.m_nodes.m_buffer;
                            ushort    expr_12D_cp_1 = num6;
                            expr_12D_cp_0 [(int)expr_12D_cp_1].m_flags = (expr_12D_cp_0 [(int)expr_12D_cp_1].m_flags | NetNode.Flags.Disabled);
                        }
                        for (int i = 0; i < 8; i++)
                        {
                            ushort segment = instance2.m_nodes.m_buffer [(int)num6].GetSegment(i);
                            if (segment != 0 && instance2.m_segments.m_buffer [(int)segment].m_startNode == num6)
                            {
                                num5 += instance2.m_segments.m_buffer [(int)segment].m_averageLength;
                                num8  = instance2.m_segments.m_buffer [(int)segment].m_endNode;
                                break;
                            }
                        }
                        num4 += 1u;
                        num6  = num8;
                        if (num6 == stops)
                        {
                            break;
                        }
                        if (++num7 >= 32768)
                        {
                            CODebugBase <LogChannel> .Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace);

                            break;
                        }
                    }
                }
                int num9 = num * info.m_maintenanceCostPerVehicle / 100;
                if (num9 != 0)
                {
                    Singleton <EconomyManager> .instance.FetchResource(EconomyManager.Resource.Maintenance, num9, info.m_class);
                }
                int budget = Singleton <EconomyManager> .instance.GetBudget(info.m_class);

                int num10;
                if (flag)
                {
                    num10 = Mathf.CeilToInt((float)budget * num5 / (info.m_defaultVehicleDistance * 100f));
                }
                else
                {
                    num10 = 0;
                }
                if (num4 != 0u && num < num10)
                {
                    TransferManager.TransferReason vehicleReason = info.m_vehicleReason;
                    int index = Singleton <SimulationManager> .instance.m_randomizer.Int32(num4);

                    ushort stop = this.GetStop(index);
                    if (vehicleReason != TransferManager.TransferReason.None && stop != 0)
                    {
                        TransferManager.TransferOffer offer = default(TransferManager.TransferOffer);
                        offer.Priority      = num10 - num + 1;
                        offer.TransportLine = lineID;
                        offer.Position      = Singleton <NetManager> .instance.m_nodes.m_buffer [(int)stop].m_position;
                        offer.Amount        = 1;
                        offer.Active        = false;
                        Singleton <TransferManager> .instance.AddIncomingOffer(vehicleReason, offer);
                    }
                }
                else
                {
                    if (num > num10)
                    {
                        int index2 = Singleton <SimulationManager> .instance.m_randomizer.Int32((uint)num);

                        ushort vehicle = this.GetVehicle(index2);
                        if (vehicle != 0)
                        {
                            VehicleManager instance3 = Singleton <VehicleManager> .instance;
                            VehicleInfo    info2     = instance3.m_vehicles.m_buffer [(int)vehicle].Info;
                            info2.m_vehicleAI.SetTransportLine(vehicle, ref instance3.m_vehicles.m_buffer [(int)vehicle], 0);
                        }
                    }
                }
            }
            if ((Singleton <SimulationManager> .instance.m_currentFrameIndex & 4095u) >= 3840u)
            {
                this.m_passengers.Update();
                Singleton <TransportManager> .instance.m_passengers [(int)info.m_transportType].Add(ref this.m_passengers);
                this.m_passengers.Reset();
            }
        }
Exemple #22
0
        public static TileSheet GenerateTileSheet(List <SpriteData> spritesList, PaletteData paletteData, int padding)
        {
            var widest  = 0;
            var tallest = 0;

            foreach (var s in spritesList)
            {
                if (s.Width > widest)
                {
                    widest = s.Width;
                }
                if (s.Height > tallest)
                {
                    tallest = s.Height;
                }
            }

            // Calculate number of rows and columns. We need this to be an even number for the shader to work
            var rowCount = Mathf.CeilToInt(Mathf.Sqrt(spritesList.Count));

            if (rowCount % 2 != 0)
            {
                rowCount++;
            }

            var w = rowCount * widest;
            var h = rowCount * tallest;

            w += rowCount * padding * 2;
            h += rowCount * padding * 2;

            var spriteSheet = new TileSheet();

            spriteSheet.Texture    = new Texture2D(w, h);
            spriteSheet.Rows       = rowCount;
            spriteSheet.Columns    = rowCount;
            spriteSheet.TileWidth  = widest;
            spriteSheet.TileHeight = tallest;
            spriteSheet.Padding    = padding;

            int index = 0;

            foreach (var s in spritesList)
            {
                var tex = GenerateSprite(s, paletteData);

                var destX = (widest + padding * 2) * (index % rowCount) + padding;
                var destY = (tallest + padding * 2) * (index / rowCount) + padding;

                var source = tex.GetPixels();
                spriteSheet.Texture.SetPixels(destX, destY, tex.width, tex.height, source);

                // Padding
                for (var i = 1; i <= padding; i++)
                {
                    for (var x = 0; x < tex.width; x++)
                    {
                        spriteSheet.Texture.SetPixel(destX + x, destY - i, tex.GetPixel(x, 0));
                        spriteSheet.Texture.SetPixel(destX + x, (destY + (tex.height - 1)) + i, tex.GetPixel(x, tex.height - 1));
                    }

                    for (var y = 0; y < tex.height; y++)
                    {
                        spriteSheet.Texture.SetPixel(destX - i, (destY) + y, tex.GetPixel(0, y));
                        spriteSheet.Texture.SetPixel((destX + (tex.width - 1)) + i, (destY) + y, tex.GetPixel(tex.width - 1, y));
                    }
                }

                for (var x = 0; x < padding; x++)
                {
                    for (var y = 0; y < padding; y++)
                    {
                        spriteSheet.Texture.SetPixel((destX - padding) + x, (destY - 2) + y, tex.GetPixel(0, 0));
                        spriteSheet.Texture.SetPixel((destX + tex.width) + x, (destY - 2) + y, tex.GetPixel(tex.width - 1, 0));
                        spriteSheet.Texture.SetPixel((destX + tex.width) + x, (destY + tex.height) + y, tex.GetPixel(tex.width - 1, tex.height - 1));
                        spriteSheet.Texture.SetPixel((destX - padding) + x, (destY + tex.height) + y, tex.GetPixel(0, tex.height - 1));
                    }
                }

                spriteSheet.LookupTable.Add(s.Name, new TileSheetSprite()
                {
                    TileNum = index,
                    Width   = tex.width,
                    Height  = tex.height
                });

                index++;
            }

            spriteSheet.Texture.Apply();

            return(spriteSheet);
        }
Exemple #23
0
        private void DoLayout(string[] defaultText, bool isNumeric, NumericMode numericMode = NumericMode.Natural)
        {
            if (Components.Count > 0)
            {
                Components.Clear();
            }

            columns = maxItemsPerRow == -1 ? defaultText.Length : Mathf.Min(defaultText.Length, maxItemsPerRow);
            float totalWidth   = Size.x / columns;
            float hSpace       = totalWidth * horizontalSpace;
            float contentWidth = columns == 1 ? totalWidth : totalWidth - hSpace;

            rows = maxItemsPerRow == -1 ? 1 : Mathf.CeilToInt(defaultText.Length / maxItemsPerRow);
            float totalHeight   = Size.y / rows;
            float vSpace        = totalHeight * verticalSpace;
            float contentheight = rows == 1 ? totalHeight : totalHeight - vSpace;

            TextBoxes = new TextBox[defaultText.Length];
            Vector2 size = new Vector2(contentWidth, contentheight);

            int row    = 0;
            int column = 0;

            for (int i = 0; i < defaultText.Length; i++)
            {
                float x;
                if (column == 0)
                {
                    x = 0;
                }
                else if (column < columns)
                {
                    x = totalWidth * column + hSpace / 2;
                }
                else
                {
                    x = Size.x - size.x;
                }

                float y;
                if (row == 0)
                {
                    y = 0;
                }
                else if (row < rows)
                {
                    y = totalHeight * row + vSpace / 2;
                }
                else
                {
                    y = Size.y - size.y;
                }

                TextBoxes[i]                 = DaggerfallUI.AddTextBoxWithFocus(new Rect(new Vector2(x, y), size), defaultText[i], this);
                TextBoxes[i].Numeric         = isNumeric;
                TextBoxes[i].NumericMode     = numericMode;
                TextBoxes[i].UseFocus        = true;
                TextBoxes[i].Outline.Enabled = enableOutline;
                if (OnAddTextBoxCallback != null)
                {
                    OnAddTextBoxCallback(TextBoxes[i]);
                }

                if (++column == columns)
                {
                    row++;
                    column = 0;
                }
            }
        }
Exemple #24
0
        /**
         * Generates the particle based physical representation of the rope. This is the initialization method for the rope object
         * and should not be called directly once the object has been created.
         */
        protected override IEnumerator Initialize()
        {
            initialized           = false;
            initializing          = true;
            interParticleDistance = -1;

            RemoveFromSolver(null);

            if (ropePath == null)
            {
                Debug.LogError("Cannot initialize rope. There's no ropePath present. Please provide a spline to define the shape of the rope");
                yield break;
            }

            ropePath.RecalculateSplineLenght(0.00001f, 7);
            closed     = ropePath.closed;
            restLength = ropePath.Length;

            usedParticles  = Mathf.CeilToInt(restLength / thickness * resolution) + (closed ? 0 : 1);
            totalParticles = usedParticles;

            active              = new bool[totalParticles];
            positions           = new Vector3[totalParticles];
            orientations        = new Quaternion[totalParticles];
            velocities          = new Vector3[totalParticles];
            angularVelocities   = new Vector3[totalParticles];
            invMasses           = new float[totalParticles];
            invRotationalMasses = new float[totalParticles];
            principalRadii      = new Vector3[totalParticles];
            phases              = new int[totalParticles];
            restPositions       = new Vector4[totalParticles];
            restOrientations    = new Quaternion[totalParticles];
            colors              = new Color[totalParticles];

            int numSegments = usedParticles - (closed ? 0 : 1);

            if (numSegments > 0)
            {
                interParticleDistance = restLength / (float)numSegments;
            }
            else
            {
                interParticleDistance = 0;
            }

            float radius = interParticleDistance * resolution;

            for (int i = 0; i < usedParticles; i++)
            {
                active[i]              = true;
                invMasses[i]           = 1.0f / DEFAULT_PARTICLE_MASS;
                invRotationalMasses[i] = 1.0f / DEFAULT_PARTICLE_ROTATIONAL_MASS;
                float mu = ropePath.GetMuAtLenght(interParticleDistance * i);
                positions[i]      = transform.InverseTransformPoint(ropePath.transform.TransformPoint(ropePath.GetPositionAt(mu)));
                principalRadii[i] = Vector3.one * radius;
                phases[i]         = Oni.MakePhase(1, selfCollisions ? Oni.ParticlePhase.SelfCollide : 0);
                colors[i]         = Color.white;

                if (i % 100 == 0)
                {
                    yield return(new CoroutineJob.ProgressInfo("ObiRod: generating particles...", i / (float)usedParticles));
                }
            }

            StretchShearConstraints.Clear();
            ObiStretchShearConstraintBatch stretchBatch = new ObiStretchShearConstraintBatch(false, false, MIN_YOUNG_MODULUS, MAX_YOUNG_MODULUS);

            StretchShearConstraints.AddBatch(stretchBatch);

            // rotation minimizing frame:
            CurveFrame frame = new CurveFrame();

            frame.Reset();

            for (int i = 0; i < numSegments; i++)
            {
                int next = (i + 1) % (ropePath.closed ? usedParticles : usedParticles + 1);

                float   mu     = ropePath.GetMuAtLenght(interParticleDistance * i);
                Vector3 normal = transform.InverseTransformVector(ropePath.transform.TransformVector(ropePath.GetNormalAt(mu)));

                frame.Transport(positions[i], (positions[next] - positions[i]).normalized, 0);

                orientations[i]     = Quaternion.LookRotation(frame.tangent, normal);
                restOrientations[i] = orientations[i];

                // Also set the orientation of the next particle. If it is not the last one, we will overwrite it.
                // This makes sure that open rods provide an orientation for their last particle (or rather, a phantom segment past the last particle).

                orientations[next]     = orientations[i];
                restOrientations[next] = orientations[i];

                stretchBatch.AddConstraint(i, next, interParticleDistance, Vector3.one);

                if (i % 500 == 0)
                {
                    yield return(new CoroutineJob.ProgressInfo("ObiRod: generating structural constraints...", i / (float)numSegments));
                }
            }

            BendTwistConstraints.Clear();
            ObiBendTwistConstraintBatch twistBatch = new ObiBendTwistConstraintBatch(false, false, MIN_YOUNG_MODULUS, MAX_YOUNG_MODULUS);

            BendTwistConstraints.AddBatch(twistBatch);

            // the last bend constraint couples the last segment and a phantom segment past the last particle.
            for (int i = 0; i < numSegments; i++)
            {
                int next = (i + 1) % (ropePath.closed ? usedParticles : usedParticles + 1);

                Quaternion darboux = keepInitialShape ? ObiUtils.RestDarboux(orientations[i], orientations[next]) : Quaternion.identity;
                twistBatch.AddConstraint(i, next, darboux, Vector3.one);

                if (i % 500 == 0)
                {
                    yield return(new CoroutineJob.ProgressInfo("ObiRod: generating structural constraints...", i / (float)numSegments));
                }
            }

            ChainConstraints.Clear();
            ObiChainConstraintBatch chainBatch = new ObiChainConstraintBatch(false, false, MIN_YOUNG_MODULUS, MAX_YOUNG_MODULUS);

            ChainConstraints.AddBatch(chainBatch);

            int[] indices = new int[usedParticles + (closed ? 1 : 0)];

            for (int i = 0; i < usedParticles; ++i)
            {
                indices[i] = i;
            }

            // Add the first particle as the last index of the chain, if closed.
            if (closed)
            {
                indices[usedParticles] = 0;
            }

            chainBatch.AddConstraint(indices, interParticleDistance, 1, 1);


            // Initialize tether constraints:
            TetherConstraints.Clear();

            // Initialize pin constraints:
            PinConstraints.Clear();
            ObiPinConstraintBatch pinBatch = new ObiPinConstraintBatch(false, false, MIN_YOUNG_MODULUS, MAX_YOUNG_MODULUS);

            PinConstraints.AddBatch(pinBatch);

            initializing = false;
            initialized  = true;

            RegenerateRestPositions();
        }
Exemple #25
0
    // Update is called once per frame
    void Update()
    {
        //Resources.Load();

        if (GlobalControl.Instance.time > 0 && canTime == true)
        {
            int count = (int)(GlobalControl.Instance.time / timerSO.round);
            timeText.text = count.ToString();

            float amount = (GlobalControl.Instance.time / timerSO.round) - count;

            clockHand.transform.rotation = Quaternion.Euler(0, 0, amount * 360);

            //timeImage.fillAmount = (GlobalControl.Instance.time / timerSO.round) - count;

            float oldTime = GlobalControl.Instance.time;

            if (GlobalControl.Instance.time - Time.deltaTime < 0)
            {
                GlobalControl.Instance.time = -0.5f;
            }
            else
            {
                GlobalControl.Instance.time -= Time.deltaTime;
                if (Mathf.CeilToInt(oldTime) != Mathf.CeilToInt(GlobalControl.Instance.time) && Mathf.CeilToInt(GlobalControl.Instance.time) % timerSO.round == 0)
                {
                    //Debug.Log("here");
                    Tick();
                }
            }
        }
    }
 public static void updateText()
 {
     if (PlayerNPCDialogueUI.dialogue == null)
     {
         return;
     }
     if (PlayerNPCDialogueUI.dialogueAnimating)
     {
         if (PlayerNPCDialogueUI.dialoguePause > 0f)
         {
             PlayerNPCDialogueUI.dialoguePause -= Time.deltaTime;
         }
         else
         {
             PlayerNPCDialogueUI.dialogueTime += Time.deltaTime;
         }
         int num = Mathf.Min(PlayerNPCDialogueUI.dialogueCharacters.Length, Mathf.CeilToInt(PlayerNPCDialogueUI.dialogueTime * 30f) + PlayerNPCDialogueUI.dialogueOffset);
         if (PlayerNPCDialogueUI.dialogueIndex != num)
         {
             while (PlayerNPCDialogueUI.dialogueIndex < PlayerNPCDialogueUI.dialogueCharacters.Length && PlayerNPCDialogueUI.dialogueIndex < num)
             {
                 char c = PlayerNPCDialogueUI.dialogueCharacters[PlayerNPCDialogueUI.dialogueIndex];
                 if (c == '<')
                 {
                     int num2;
                     int num3;
                     if (PlayerNPCDialogueUI.dialogueAppend.Length > 0)
                     {
                         num += PlayerNPCDialogueUI.dialogueAppend.Length;
                         PlayerNPCDialogueUI.dialogueIndex  += PlayerNPCDialogueUI.dialogueAppend.Length;
                         PlayerNPCDialogueUI.dialogueOffset += PlayerNPCDialogueUI.dialogueAppend.Length;
                         PlayerNPCDialogueUI.dialogueBuilder.Append(PlayerNPCDialogueUI.dialogueAppend);
                         PlayerNPCDialogueUI.dialogueAppend = string.Empty;
                     }
                     else if (PlayerNPCDialogueUI.findKeyword(PlayerNPCDialogueUI.dialogueCharacters, PlayerNPCDialogueUI.dialogueIndex, PlayerNPCDialogueUI.KEYWORD_PAUSE))
                     {
                         PlayerNPCDialogueUI.dialoguePause += 0.5f;
                         num = PlayerNPCDialogueUI.dialogueIndex + PlayerNPCDialogueUI.KEYWORD_PAUSE.Length;
                         PlayerNPCDialogueUI.dialogueIndex   = num;
                         PlayerNPCDialogueUI.dialogueOffset += PlayerNPCDialogueUI.KEYWORD_PAUSE.Length - 1;
                     }
                     else if (PlayerNPCDialogueUI.findTags(PlayerNPCDialogueUI.dialogueCharacters, PlayerNPCDialogueUI.dialogueIndex, out num2, out num3))
                     {
                         int num4 = num3 - num2 + 1;
                         num += num4;
                         PlayerNPCDialogueUI.dialogueIndex  += num4;
                         PlayerNPCDialogueUI.dialogueOffset += num4;
                         PlayerNPCDialogueUI.dialogueBuilder.Append(PlayerNPCDialogueUI.dialogueText.Substring(num2, num4));
                         if (PlayerNPCDialogueUI.findTags(PlayerNPCDialogueUI.dialogueCharacters, num3 + 1, out num2, out num3))
                         {
                             num4 = num3 - num2 + 1;
                             PlayerNPCDialogueUI.dialogueAppend = PlayerNPCDialogueUI.dialogueText.Substring(num2, num4);
                         }
                     }
                 }
                 else
                 {
                     PlayerNPCDialogueUI.dialogueBuilder.Append(c);
                     PlayerNPCDialogueUI.dialogueIndex++;
                 }
             }
             PlayerNPCDialogueUI.messageLabel.text = PlayerNPCDialogueUI.dialogueBuilder.ToString() + PlayerNPCDialogueUI.dialogueAppend;
             if (PlayerNPCDialogueUI.dialogueIndex == PlayerNPCDialogueUI.dialogueCharacters.Length)
             {
                 PlayerNPCDialogueUI.finishPage();
             }
         }
     }
     else
     {
         PlayerNPCDialogueUI.responseTime += Time.deltaTime;
         int num5 = Mathf.Min(PlayerNPCDialogueUI.responses.Count, Mathf.FloorToInt(PlayerNPCDialogueUI.responseTime * 10f));
         if (PlayerNPCDialogueUI.responseIndex != num5)
         {
             while (PlayerNPCDialogueUI.responseIndex < num5)
             {
                 PlayerNPCDialogueUI.responseBox.children[PlayerNPCDialogueUI.responseIndex].isVisible = true;
                 PlayerNPCDialogueUI.responseBox.area = new Rect(0f, 0f, 5f, (float)(num5 * 30));
                 PlayerNPCDialogueUI.responseIndex++;
             }
         }
     }
 }
Exemple #27
0
    private void ShowHealthBar()
    {
        if (enemy == null)
        {
            foreach (GameObject go in barManaged)
            {
                Destroy(go);
            }
            barManaged.Clear();

            return;
        }

        int healthPerc = Mathf.CeilToInt((health / maxHealth) * 10);

        if (barManaged.Count != healthPerc)
        {
            foreach (GameObject go in barManaged)
            {
                Destroy(go);
            }
            barManaged.Clear();

            Vector3 pos = enemy.transform.position + new Vector3(1, 0);

            for (int i = 0; i < healthPerc; i++)
            {
                GameObject bar = null;

                if (i > 5)
                {
                    bar = (GameObject)Instantiate(greenBar,
                                                  pos + new Vector3(i * 0.2f, 0),
                                                  Quaternion.identity);
                }
                else if (i > 2)
                {
                    bar = (GameObject)Instantiate(yellowBar,
                                                  pos + new Vector3(i * 0.2f, 0),
                                                  Quaternion.identity);
                }
                else
                {
                    bar = (GameObject)Instantiate(redBar,
                                                  pos + new Vector3(i * 0.2f, 0),
                                                  Quaternion.identity);
                }

                bar.GetComponent <SpriteRenderer>().sortingOrder = 10;
                barManaged.Add(bar);
            }
        }

        if (playerBarManager == null)
        {
            playerBarManager = (GameObject)Instantiate(yellowBar,
                                                       new Vector3(0, 1.161f, 0),
                                                       Quaternion.Euler(new Vector3(0, 0, 90)));
            playerBarManager.GetComponent <SpriteRenderer>().sortingOrder = 10;
        }
        else
        {
            playerBarManager.transform.localScale = new Vector3(1, 15 * Mathf.Max(playerHealth / playerMaxHealth, 0.0f), 1);
        }

        if (enemy != null && !gameEnd && movingList.Count == 0)
        {
            playerHealth -= (enemy.GetComponent <Monster>().Damage *Time.deltaTime);
        }

        if (playerHealth <= 0)
        {
            gameEnd = true;
        }
    }
Exemple #28
0
 protected override void OnChargingProgress(float t)
 {
     status = $"{Mathf.CeilToInt(t * 100)}%";
 }
    private void Explosion()
    {
        StartCoroutine(ProjectileSound(explosionSFX, 0));
        Vector3 explosionPosition = transform.position;

        Collider[] colliders = Physics.OverlapSphere(explosionPosition, explosionRadius);
        foreach (Collider hit in colliders)
        {
            Rigidbody rb = hit.GetComponent <Rigidbody>();

            if (!hit.transform.tag.Equals("SMGGrenade") && !hit.transform.tag.Equals("CombineBall") && !hit.transform.tag.Equals("Grenade"))
            {
                if (rb != null)
                {
                    rb.AddExplosionForce(explosionPower, explosionPosition, explosionRadius, explosionRadius);

                    if (hit.transform.gameObject.GetComponent <EntityHealth>() != null)
                    {
                        GameObject entity = hit.transform.gameObject;
                        EntityExplosionDamage(entity);
                    }

                    if (hit.transform.parent != null)
                    {
                        if (hit.transform.parent.transform.gameObject.GetComponent <EntityHealth>() != null)
                        {
                            GameObject entity = hit.transform.parent.transform.gameObject;
                            EntityExplosionDamage(entity);
                        }
                    }

                    if (hit.tag.Equals("Player"))
                    {
                        GameObject player          = hit.transform.gameObject;
                        int        damage          = Mathf.CeilToInt(CalculateDamage(player.transform.position));
                        int        damageThreshold = Mathf.CeilToInt(player.GetComponent <PlayerHealth>().damageThreshold);
                        if (damage > damageThreshold)
                        {
                            if (PlayerHealth.playerSuit != 0)
                            {
                                if (damage - damageThreshold <= PlayerHealth.playerSuit)
                                {
                                    PlayerHealth.playerSuit = PlayerHealth.playerSuit - (damage - damageThreshold);
                                }
                                else if (damage - damageThreshold > PlayerHealth.playerSuit)
                                {
                                    int remainder = ((damage - damageThreshold) - PlayerHealth.playerSuit);
                                    PlayerHealth.playerSuit   = 0;
                                    PlayerHealth.playerHealth = PlayerHealth.playerHealth - remainder;
                                }
                            }
                            else if (PlayerHealth.playerHealth != 0)
                            {
                                if (damage - damageThreshold <= PlayerHealth.playerHealth)
                                {
                                    PlayerHealth.playerHealth = PlayerHealth.playerHealth - (damage - damageThreshold);
                                }
                                else if (damage - damageThreshold > PlayerHealth.playerHealth)
                                {
                                    print("Death");
                                }
                            }
                        }
                    }
                }
            }
        }
        explosionPrefab.transform.parent = null;
        explosionPrefab.Play();
        if (!isCombineBall)
        {
            Destroy(explosionPrefab.gameObject, explosionPrefab.main.duration);
        }
        WeaponScript.rocketFired = false;
    }
Exemple #30
0
        private void Groups()
        {
            GUILayout.Space(4);

            _groupsScroll = GUILayout.BeginScrollView(_groupsScroll);

            var index = 0;

            for (int i = 0; i < _groupsTextGrid.Length; i++)
            {
                GUILayout.BeginHorizontal();

                for (int j = 0; j < _groupsPerRow; j++)
                {
                    if (GUILayout.Button(_groupsTextGrid[index], _groupGridButtons))
                    {
                        TalksPage(_groupsTextGrid[index].text);
                    }

                    index++;

                    if (index == _groupsTextGrid.Length)
                    {
                        i = _groupsTextGrid.Length;

                        break;
                    }
                }

                GUILayout.EndHorizontal();
            }

            if (_deleteGroup)
            {
                var selectedGroup = 0;

                for (int i = 0; i < Mathf.CeilToInt((float)_groupsTextGrid.Length / 2); i++)
                {
                    for (int j = 0; j < 2; j++)
                    {
                        if (_groupsTextGrid.Length > selectedGroup)
                        {
                            _deleteToggles[selectedGroup] = GUI.Toggle(new Rect(15 + j * (Screen.width / 2 - 16), i * 110 + 10, 20, 20), _deleteToggles[selectedGroup], "");
                        }

                        selectedGroup++;
                    }
                }

                if (_deleteToggles.Any(x => x))
                {
                    if (GUI.Button(new Rect(0, Screen.height - 123, Screen.width, 20), $"Delete ({_deleteToggles.Count(x => x)})"))
                    {
                        //Context.Delete(UTalkEditorWindow.Position, "Group", "Selected", "groups", DeleteGroup);

                        //void DeleteGroup()
                        {
                            UTalkEditorWindow.RecordToUndo("Delete group");

                            for (int i = 0; i < _deleteToggles.Count; i++)
                            {
                                if (_deleteToggles[i])
                                {
                                    _dataContainer.DeleteGroup(_groupsTextGrid[i].text, _dataContainer.Language);
                                }
                            }

                            SetGroups();
                            _deleteGroup = false;
                        }

                        return;
                    }
                }
            }


            GUILayout.EndScrollView();
        }