Example #1
0
 private static T DefaultXmlDeserializeImpl <T>(string s, XmlSerializer xmlser, Action <string, Exception> OnException = null)
 {
     using (TextReader tr = new StringReader(s))
     {
         using (var reader = XmlReader.Create(tr))
         {
             try
             {
                 if (xmlser.CanDeserialize(reader))
                 {
                     var val = (T)xmlser.Deserialize(reader);
                     return(val);
                 }
                 else
                 {
                     LogUtils.DoErrorLog($"CAN'T DESERIALIZE {typeof(T)}!\nText : {s}");
                     OnException?.Invoke(s, null);
                 }
             }
             catch (Exception e)
             {
                 LogUtils.DoErrorLog($"CAN'T DESERIALIZE {typeof(T)}!\nText : {s}\n{e.GetType().Name}: {e.Message}\n{e.StackTrace}");
                 OnException?.Invoke(s, e);
                 throw e;
             }
             return(default);
        public void ReadXml(System.Xml.XmlReader reader)

        {
            if (reader.IsEmptyElement)
            {
                reader.Read();
                return;
            }
            var valueSerializer = new XmlSerializer(typeof(TValue), "");

            LogUtils.DoErrorLog($"reader = {reader}; empty = {reader.IsEmptyElement}");
            reader.ReadStartElement();
            var counterUnknown = 0;

            while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
            {
                if (reader.NodeType != System.Xml.XmlNodeType.Element)
                {
                    reader.Read();
                    continue;
                }

                var value = (TValue)valueSerializer.Deserialize(reader);
                if (value.SaveName == null)
                {
                    value.SaveName = $"<UNNAMED_{counterUnknown++}>";
                }
                Add(value.SaveName, value);
            }

            reader.ReadEndElement();
        }
        public static AssetBundle LoadBundle(string filename)
        {
            try
            {
                return(AssetBundle.LoadFromMemory(LoadResourceData(filename)));
            }
            catch (Exception e)
            {
                LogUtils.DoErrorLog("The file could not be read:" + e.Message);
            }

            return(null);
        }
        public static Texture2D LoadTexture(string filename)
        {
            try
            {
                var texture = new Texture2D(1, 1, TextureFormat.RGBA32, false);
                texture.LoadImage(LoadResourceData(filename));
                return(texture);
            }
            catch (Exception e)
            {
                LogUtils.DoErrorLog("The file could not be read:" + e.Message);
            }

            return(null);
        }
        public static void DoLocaleDump()
        {
            string localeDump = "LOCALE DUMP:\r\n";

            try
            {
                var locale = KlyteLocaleManager.m_localeStringsDictionary(KlyteLocaleManager.m_localeManagerLocale(LocaleManager.instance));
                foreach (Locale.Key k in locale.Keys)
                {
                    localeDump += string.Format("{0}  =>  {1}\n", k.ToString(), locale[k]);
                }
            }
            catch (Exception e)
            {
                LogUtils.DoErrorLog("LOCALE DUMP FAIL: {0}", e.ToString());
            }
            Debug.LogWarning(localeDump);
        }
        public void ReadXml(System.Xml.XmlReader reader)

        {
            if (reader.IsEmptyElement)
            {
                reader.Read();
                return;
            }
            var valueSerializer = new XmlSerializer(typeof(EntryValueContainer <TKey, TValue>), "");

            reader.ReadStartElement();
            while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
            {
                if (reader.NodeType != System.Xml.XmlNodeType.Element)
                {
                    reader.Read();
                    continue;
                }
                try
                {
                    var value = (EntryValueContainer <TKey, TValue>)valueSerializer.Deserialize(reader);
                    if (value.Value is IKeyGetter <TKey> keyGetter)
                    {
                        value.Id = keyGetter.GetKeyString() ?? value.Id;
                    }

                    if (value.Id == null)
                    {
                        continue;
                    }
                    Add(value.Id, value.Value ?? null);
                }
                catch (Exception e)
                {
                    LogUtils.DoErrorLog($"Error deserializing {GetType()}:\n{e.StackTrace}");
                }
            }

            reader.ReadEndElement();
        }
        public static List <ushort> FindNearStops(Vector3 position, ItemClass.Service service, ItemClass.Service service2, VehicleInfo.VehicleType stopType, bool allowUnderground, float maxDistance,
                                                  out List <float> distanceSqrA, out List <Vector3> stopPositions, List <Quad2> boundaries = null)
        {
            var        bounds   = new Bounds(position, new Vector3(maxDistance * 2f, maxDistance * 2f, maxDistance * 2f));
            int        num      = Mathf.Max((int)(((bounds.min.x - 64f) / 64f) + 135f), 0);
            int        num2     = Mathf.Max((int)(((bounds.min.z - 64f) / 64f) + 135f), 0);
            int        num3     = Mathf.Min((int)(((bounds.max.x + 64f) / 64f) + 135f), 269);
            int        num4     = Mathf.Min((int)(((bounds.max.z + 64f) / 64f) + 135f), 269);
            NetManager instance = Singleton <NetManager> .instance;
            var        result   = new List <Tuple <ushort, float, Vector3> >();

            float maxDistSqr = maxDistance * maxDistance;

            for (int i = num2; i <= num4; i++)
            {
                for (int j = num; j <= num3; j++)
                {
                    int    idx    = (i * 270) + j;
                    ushort nodeId = 0;
                    int    num7   = 0;
                    try
                    {
                        nodeId = instance.m_nodeGrid[idx];
                        num7   = 0;
                        while (nodeId != 0)
                        {
                            NetInfo info = instance.m_nodes.m_buffer[nodeId].Info;
                            if (info != null &&
                                (info.m_class.m_service == service || info.m_class.m_service == service2) &&
                                (instance.m_nodes.m_buffer[nodeId].m_flags & (NetNode.Flags.Collapsed)) == NetNode.Flags.None &&
                                (instance.m_nodes.m_buffer[nodeId].m_flags & (NetNode.Flags.Created)) != NetNode.Flags.None &&
                                instance.m_nodes.m_buffer[nodeId].m_transportLine > 0 &&
                                (allowUnderground || !info.m_netAI.IsUnderground()) &&
                                (stopType == VehicleInfo.VehicleType.None || stopType == (TransportManager.instance.m_lines.m_buffer[instance.m_nodes.m_buffer[nodeId].m_transportLine]).Info.m_vehicleType) &&
                                (TransportManager.instance.m_lines.m_buffer[instance.m_nodes.m_buffer[nodeId].m_transportLine].m_flags & TransportLine.Flags.Complete) != TransportLine.Flags.None)
                            {
                                NetNode node    = instance.m_nodes.m_buffer[nodeId];
                                Vector3 nodePos = node.m_position;
                                if (boundaries != null && boundaries.Count != 0 && !boundaries.Any(x => x.Intersect(VectorUtils.XZ(nodePos))))
                                {
                                    goto GOTO_NEXT;
                                }
                                float delta = Mathf.Max(Mathf.Max(bounds.min.x - 64f - nodePos.x, bounds.min.z - 64f - nodePos.z), Mathf.Max(nodePos.x - bounds.max.x - 64f, nodePos.z - bounds.max.z - 64f));
                                if (delta < 0f && instance.m_nodes.m_buffer[nodeId].m_bounds.Intersects(bounds))
                                {
                                    float num14 = Vector3.SqrMagnitude(position - nodePos);
                                    if (num14 < maxDistSqr)
                                    {
                                        result.Add(Tuple.New(nodeId, num14, nodePos));
                                    }
                                }
                            }
GOTO_NEXT:
                            nodeId = instance.m_nodes.m_buffer[nodeId].m_nextGridNode;
                            if (++num7 >= 36864)
                            {
                                CODebugBase <LogChannel> .Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace);

                                break;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        LogUtils.DoErrorLog($"ERROR ON TRYING FindNearStops: (It = {num7}; Init = {idx}; Curr = {nodeId})==>  {e.Message}\n{e.StackTrace}");
                    }
                }
            }
            result        = result.OrderBy(x => x.First).ToList();
            distanceSqrA  = result.Select(x => x.Second).ToList();
            stopPositions = result.Select(x => x.Third).ToList();
            return(result.Select(x => x.First).ToList());
        }
        private void SetProperties(BindProperties propertiesToSet, Func <int, bool> callback)
        {
            m_mainPanel.autoLayout = true;
            if (propertiesToSet.help_isArticle)
            {
                if (!Directory.Exists(propertiesToSet.help_fullPathName))
                {
                    LogUtils.DoErrorLog($"Invalid tutorial path! {propertiesToSet.help_fullPathName}");
                    Close(-1);
                    return;
                }

                string fullText;
                if (File.Exists($"{propertiesToSet.help_fullPathName}{Path.DirectorySeparatorChar}texts_{KlyteLocaleManager.CurrentLanguageId}.txt"))
                {
                    fullText = File.ReadAllText($"{propertiesToSet.help_fullPathName}{Path.DirectorySeparatorChar}texts_{KlyteLocaleManager.CurrentLanguageId}.txt");
                }
                else if (File.Exists($"{propertiesToSet.help_fullPathName}{Path.DirectorySeparatorChar}texts.txt"))
                {
                    fullText = File.ReadAllText($"{propertiesToSet.help_fullPathName}{Path.DirectorySeparatorChar}texts.txt");
                }
                else
                {
                    LogUtils.DoErrorLog($"Corrupted tutorial path! File \"texts.txt\" not found at folder {propertiesToSet.help_fullPathName}.");
                    Close(-1);
                    return;
                }
                string[] tutorialEntries = Regex.Split(fullText, "<BR>", RegexOptions.Multiline | RegexOptions.ECMAScript);

                int      lastPage         = tutorialEntries.Length - 1;
                int      currentPage      = Math.Max(0, Math.Min(lastPage, propertiesToSet.help_currentPage));
                string   targetImg        = $"{propertiesToSet.help_fullPathName}{Path.DirectorySeparatorChar}{currentPage.ToString("D3")}.jpg";
                string   textureImagePath = File.Exists(targetImg) ? targetImg : null;
                string   path             = propertiesToSet.help_fullPathName;
                string   feature          = propertiesToSet.help_featureName;
                string[] formatEntries    = propertiesToSet.help_formatsEntries;
                LogUtils.DoLog($"IMG: {targetImg}");
                propertiesToSet = new BindProperties
                {
                    icon             = propertiesToSet.icon,
                    title            = string.Format(Locale.Get("K45_CMNS_HELP_FORMAT"), propertiesToSet.help_featureName, currentPage + 1, lastPage + 1),
                    message          = string.Format(tutorialEntries[currentPage], formatEntries),
                    imageTexturePath = textureImagePath,

                    showClose   = true,
                    showButton1 = currentPage != 0,
                    textButton1 = "<<<\n" + Locale.Get("K45_CMNS_PREV"),
                    showButton2 = true,
                    textButton2 = Locale.Get("EXCEPTION_OK"),
                    showButton3 = currentPage != lastPage,
                    textButton3 = ">>>\n" + Locale.Get("K45_CMNS_NEXT"),
                };
                callback = (x) =>
                {
                    if (x == 1)
                    {
                        ShowModalHelpAbsolutePath(path, feature, currentPage - 1, formatEntries);
                    }
                    if (x == 3)
                    {
                        ShowModalHelpAbsolutePath(path, feature, currentPage + 1, formatEntries);
                    }
                    return(true);
                };
            }

            m_currentCallback = callback;

            m_properties.FindBinding("title").property.value        = propertiesToSet.title;
            m_properties.FindBinding("icon").property.value         = propertiesToSet.icon ?? CommonProperties.ModIcon;
            m_properties.FindBinding("showClose").property.value    = propertiesToSet.showClose || !(propertiesToSet.showButton1 || propertiesToSet.showButton2 || propertiesToSet.showButton3 || propertiesToSet.showButton4);
            m_properties.FindBinding("message").property.value      = propertiesToSet.message;
            m_properties.FindBinding("messageAlign").property.value = propertiesToSet.messageAlign;
            m_properties.FindBinding("showButton1").property.value  = propertiesToSet.showButton1;
            m_properties.FindBinding("showButton2").property.value  = propertiesToSet.showButton2;
            m_properties.FindBinding("showButton3").property.value  = propertiesToSet.showButton3;
            m_properties.FindBinding("showButton4").property.value  = propertiesToSet.showButton4;
            m_properties.FindBinding("showButton5").property.value  = propertiesToSet.showButton5;
            m_properties.FindBinding("textButton1").property.value  = propertiesToSet.textButton1 ?? "";
            m_properties.FindBinding("textButton2").property.value  = propertiesToSet.textButton2 ?? "";
            m_properties.FindBinding("textButton3").property.value  = propertiesToSet.textButton3 ?? "";
            m_properties.FindBinding("textButton4").property.value  = propertiesToSet.textButton4 ?? "";
            m_properties.FindBinding("textButton5").property.value  = propertiesToSet.textButton5 ?? "";

            m_textField.isVisible = propertiesToSet.showTextField;
            m_textField.text      = propertiesToSet.defaultTextFieldContent ?? "";

            if (m_dropDown == null)
            {
                KlyteMonoUtils.CreateUIElement(out UIPanel DDpanel, m_mainPanel.transform);
                DDpanel.maximumSize            = new Vector2(m_boxText.minimumSize.x - 10, 40);
                DDpanel.anchor                 = UIAnchorStyle.CenterHorizontal;
                DDpanel.zOrder                 = m_textField.zOrder + 1;
                DDpanel.autoLayout             = true;
                m_dropDown                     = UIHelperExtension.CloneBasicDropDownNoLabel(new string[0], (x) => { }, DDpanel);
                m_dropDown.name                = DD_INPUT_ID;
                m_dropDown.minimumSize         = new Vector2(m_boxText.minimumSize.x - 10, 25);
                m_dropDown.size                = new Vector2(m_boxText.minimumSize.x - 10, 40);
                m_dropDown.autoSize            = false;
                m_dropDown.processMarkup       = true;
                m_dropDown.verticalAlignment   = UIVerticalAlignment.Middle;
                m_dropDown.horizontalAlignment = UIHorizontalAlignment.Left;
            }
            m_dropDown.parent.isVisible = propertiesToSet.showDropDown;
            m_dropDown.items            = propertiesToSet.dropDownOptions?.Split(BindProperties.DD_OPTIONS_SEPARATOR.ToCharArray()) ?? new string[0];
            m_dropDown.selectedIndex    = propertiesToSet.dropDownCurrentSelection;


            m_textureSprite.size = default;
            if (!propertiesToSet.imageTexturePath.IsNullOrWhiteSpace())
            {
                if (File.Exists(propertiesToSet.imageTexturePath))
                {
                    byte[] fileData = File.ReadAllBytes(propertiesToSet.imageTexturePath);
                    var    tex      = new Texture2D(2, 2);
                    if (tex.LoadImage(fileData))
                    {
                        m_textureSupContainer.isVisible = true;
                        m_textureSprite.texture         = tex;
                        m_textureSprite.size            = new Vector2(tex.width, tex.height);
                        if (m_textureSprite.height > 400)
                        {
                            float proportion = m_textureSprite.width / m_textureSprite.height;
                            m_textureSprite.height = 400;
                            m_textureSprite.width  = proportion * 400;
                        }
                        m_textureSupContainer.height = m_textureSprite.size.y;
                    }
                    else
                    {
                        LogUtils.DoWarnLog($"Failed loading image: {propertiesToSet.imageTexturePath}");
                        m_textureSupContainer.isVisible = false;
                    }
                }
            }
            else
            {
                m_textureSprite.texture         = null;
                m_textureSupContainer.isVisible = false;
            }

            float width;

            if (propertiesToSet.useFullWindowWidth || m_textureSprite.width > 800)
            {
                width = UIView.GetAView().fixedWidth - 100;
                if (width < m_textureSprite.width)
                {
                    float proportion = m_textureSprite.width / m_textureSprite.height;
                    m_textureSprite.width  = width;
                    m_textureSprite.height = width / proportion;
                }
            }
            else
            {
                width = 800;
            }
            m_mainPanel.width  = width;
            m_closeButton.area = new Vector4(width - 37, 3, 32, 32);
            width -= m_mainPanel.padding.horizontal;
            m_titleContainer.width      = width;
            m_boxText.width             = width;
            m_buttonSupContainer.width  = width;
            m_textureSupContainer.width = width;
            m_mainPanel.autoLayout      = !propertiesToSet.showDropDown;
        }