Exemple #1
0
    public static void GenerateNames()
    {
        Names.Clear();

        var uniqueNames = Object.FindObjectsOfType <UniqueName>();

        foreach (var uniqueName in uniqueNames)
        {
            var trimmedName = uniqueName.name.TrimEnd();
            if (!Names.Contains(trimmedName))
            {
                Names.Add(trimmedName);
                continue;
            }

            string baseName = trimmedName;
            if (Regex.IsMatch(baseName, @".+ \(\d+\)$"))
            {
                baseName = baseName.Substring(0, baseName.LastIndexOf("(", StringComparison.Ordinal)).TrimEnd();
            }

            string newName = baseName;
            int    index   = 1;
            while (Names.Contains(newName))
            {
                newName = baseName + " (" + index + ")";
                index++;
            }

            Debug.LogWarning("Object name changed from " + uniqueName.name + " to " + newName, uniqueName);
            uniqueName.name = newName;
            Names.Add(newName);
        }
    }
Exemple #2
0
        protected override void doLog(rcLogCategory category, string msg)
        {
            m_Messages.Add(new LogMessage(category, msg));
            if (m_Messages.Count > MAX_MESSAGES)
            {
                m_Messages.RemoveAt(0);
            }


            m_Dirty = true;

            switch (category)
            {
            case rcLogCategory.RC_LOG_ERROR:
                Debug.LogError(msg);
                break;

            case rcLogCategory.RC_LOG_WARNING:
                Debug.LogWarning(msg);
                break;

            case rcLogCategory.RC_LOG_PROGRESS:
                Debug.Log(msg);
                break;
            }
        }
Exemple #3
0
    public string GetLine(int index, XElement item, CSVBuilder instance)
    {
        string buffer = "";

        foreach (var key in keys)
        {
            try {
                AutoCSVKeys.KeyDelegate spcKey;
                if (AutoCSVKeys.specialKeys.TryGetValue(key, out spcKey))
                {
                    buffer += spcKey(index, key, item.Attribute(key) != null ? item.Attribute(key).Value : "0", item, instance);
                }
                else
                {
                    buffer += (item.Attribute(key) != null ? item.Attribute(key).Value : "0") + ",";
                }
            } catch (Exception e) {
                Debug.LogError(string.Format("An Error Occured while getting values from mod.xml : {0}", key));
                Debug.LogWarning(e);
            }
        }
        buffer = buffer.Substring(0, buffer.Length - 1); // f****r

        buffer += "\n";
        return(buffer);
    }
 public static void LogWarning(object message)
 {
     if (Enable)
     {
         Debug.LogWarning(message);
     }
 }
 public static void LogWarning(object message, UnityEngine.Object context)
 {
     if (Enable)
     {
         Debug.LogWarning(message, context);
     }
 }
    public Process RunCommandAsync(string[] arguments, DataReceivedEventHandler outputDataReceivedHandler)
    {
        if (!isReady)
        {
            Debug.LogWarning("PXRLog ADB Tool not ready.");
            return(null);
        }

        string args = string.Join(" ", arguments);

        ProcessStartInfo startInfo = new ProcessStartInfo(adbPath, args);

        startInfo.WorkingDirectory       = androidSdkRoot;
        startInfo.CreateNoWindow         = true;
        startInfo.UseShellExecute        = false;
        startInfo.WindowStyle            = ProcessWindowStyle.Hidden;
        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError  = true;

        Process process = Process.Start(startInfo);

        if (outputDataReceivedHandler != null)
        {
            process.OutputDataReceived += new DataReceivedEventHandler(outputDataReceivedHandler);
        }

        process.BeginOutputReadLine();
        process.BeginErrorReadLine();

        return(process);
    }
Exemple #7
0
    public void ConsoleTest()
    {
        var sw = new Stopwatch();

        sw.Start();
        for (var i = 0; i < ConsoleTestQuantity; i++)
        {
            var sample = SampleLogs[Random.Range(0, SampleLogs.Length)];

            var mode = Random.Range(0, 3);

            switch (mode)
            {
            case 0:
                Debug.Log(sample);
                break;

            case 1:
                Debug.LogWarning(sample);
                break;

            case 2:
                Debug.LogError(sample);
                break;
            }
        }
        sw.Stop();

        Debug.Log("Posted {0} log messages in {1}s".Fmt(ConsoleTestQuantity, sw.Elapsed.TotalSeconds));
    }
Exemple #8
0
    public static void Initialize(EventHandler <TweetEventArgs> onEventReceived = null, EventHandler <TweetEventArgs> onSourceDown = null, EventHandler <TweetEventArgs> onSourceUp = null)
    {
        if (initialized)
        {
            Debug.LogWarning("Trying to initialize when source is already initialized.");
            return;
        }

        source = TweetEventSource.CreateFilterStream();
        if (onEventReceived != null)
        {
            source.EventReceived += onEventReceived;
        }
        if (onEventReceived != null)
        {
            source.SourceDown += onSourceDown;
        }
        if (onEventReceived != null)
        {
            source.SourceUp += onSourceUp;
        }

        var config = source.AuthConfig;

        config.ConsumerKey    = CONSUMER_PUBLIC;
        config.ConsumerSecret = CONSUMER_PRIVATE;
        config.Token          = API_PUBLIC;
        config.TokenSecret    = API_PRIVATE;

        Debug.Log("Stream initialized");
        initialized = true;
    }
Exemple #9
0
 public CacheUIntString
 (
     Func <uint, uint> hashFunction,
     Func <uint, string> hashToString,
     uint initMin,
     uint initMax,
     uint initStep
 )
     : base(hashFunction, hashToString, Convert.ToInt32(initStep != 0 ? (initMax - initMin) / initStep : 0))
 {
     if (initStep != 0)
     {
         for (uint key = initMin; key <= initMax; key += initStep)
         {
             uint   hash = hashFunction(key);
             string str  = hashToString(hash);
             Assert.IsNotNull(str);
             if (_table.ContainsKey(hash) == false)
             {
                 _table.Add(hash, str);
             }
             else
             {
                 Debug.LogWarning($"Redundant key: { key }, where hash: { hash }");
             }
         }
     }
 }
Exemple #10
0
    public static void Pause()
    {
        if (!_tests.ContainsKey(_lastStaticTest))
        {
            Debug.LogWarning("TimeTest caused: TimeTest.Pause() call. There was no TimeTest.Start()");
            return;
        }

        _tests[_lastStaticTest].Timer.Stop();
    }
Exemple #11
0
    public static void Pause(string title)
    {
        if (!_tests.ContainsKey(title))
        {
            Debug.LogWarning("TimeTest caused: Test Paused but not Started — " + title);
            return;
        }

        _tests[title].Timer.Stop();
    }
Exemple #12
0
    public static void End()
    {
        if (!_tests.ContainsKey(_lastStaticTest))
        {
            Debug.LogWarning("TimeTest caused: TimeTest.End() call. There was no TimeTest.Start()");
            return;
        }

        _tests[_lastStaticTest].EndTest();
        _tests.Remove(_lastStaticTest);
    }
Exemple #13
0
    public static void End(string title)
    {
        if (!_tests.ContainsKey(title))
        {
            Debug.LogWarning("TimeTest caused: Test not found — " + title);
            return;
        }

        _tests[title].EndTest();
        _tests.Remove(title);
        _lastStaticTest = string.Empty;
    }
 public override SymbolDefinition AddDeclaration(SymbolDeclaration symbol)
 {
     if (symbol.scope == null)
     {
         symbol.scope = this;
     }
     if (declaration == null)
     {
         Debug.LogWarning("Missing declaration in SymbolDeclarationScope! Can't add " + symbol + "\nfor node: " + parseTreeNode);
         return(null);
     }
     return(declaration.definition.AddDeclaration(symbol));
 }
Exemple #15
0
 public static string GetProjectPath()
 {
     try {
         var projectBrowserType = Type.GetType("UnityEditor.ProjectBrowser,UnityEditor");
         var projectBrowser     = projectBrowserType.GetField("s_LastInteractedProjectBrowser", BindingFlags.Static | BindingFlags.Public).GetValue(null);
         var invokeMethod       = projectBrowserType.GetMethod("GetActiveFolderPath", BindingFlags.NonPublic | BindingFlags.Instance);
         return((string)invokeMethod.Invoke(projectBrowser, new object[] { }));
     } catch (Exception exception) {
         Debug.LogWarning("Error while trying to get current project path.");
         Debug.LogWarning(exception.Message);
         return(string.Empty);
     }
 }
Exemple #16
0
 public static XDocument ParseModXML(string path)
 {
     try {
         if (File.Exists(path))
         {
             XmlDocument modDocument = new XmlDocument();
             modDocument.Load(path);
             return(XDocument.Parse(modDocument.OuterXml));
         }
     } catch (Exception e) {
         Debug.LogWarning(e);
     }
     return(null);
 }
Exemple #17
0
        public void EndTest()
        {
            var ms         = Timer.ElapsedMilliseconds;
            var elapsedVal = _precise ? ms : ms / 1000f;
            var valMark    = _precise ? "ms" : "s";

            StringBuilder.Length = 0;
            StringBuilder.Append("<color=#5B87DA>")
            .Append(_testTitle)
            .Append("</color> Test: ")
            .Append(elapsedVal)
            .Append(valMark);

            Debug.LogWarning(StringBuilder);
        }
Exemple #18
0
    private static void Send(SprotoTypeBase rpc, long?session, int tag)
    {
        if (!bConnected || !Enabled)
        {
            return;
        }

        package pkg = new package();

        pkg.type = tag;

        if (session != null)
        {
            pkg.session = (long)session;
            sessionDict.Add((long)session, protocol[tag].Response.Value);
        }

        sendStream.Seek(0, SeekOrigin.Begin);
        int len = pkg.encode(sendStream);

        if (rpc != null)
        {
            len += rpc.encode(sendStream);
        }

        byte[] data = sendPack.pack(sendStream.Buffer, len);
        if (data.Length > MAX_PACK_LEN)
        {
            Debug.Log("data.Length > " + MAX_PACK_LEN + " => " + data.Length);
            return;
        }

        sendStream.Seek(0, SeekOrigin.Begin);
        sendStream.WriteByte((byte)(data.Length >> 8));
        sendStream.WriteByte((byte)data.Length);
        sendStream.Write(data, 0, data.Length);

        try {
            socket.Send(sendStream.Buffer, sendStream.Position, SocketFlags.None);
        }
        catch (Exception e) {
            Debug.Log("send Lost network" + ((SocketException)e).ErrorCode);
            Debug.Log("send Lost network" + ((SocketException)e).ToString());
            Debug.LogWarning(e.ToString());
        }
    }
Exemple #19
0
    public async void Connect(string url)
    {
        cancellationTokenSource = new CancellationTokenSource();
        cancellationToken       = cancellationTokenSource.Token;

        while (!cancellationToken.IsCancellationRequested)
        {
            using (webSocket = new ClientWebSocket())
            {
                webSocket.Options.SetRequestHeader("User-Agent", "Unity3D");

                try
                {
                    Debug.Log("<color=cyan>WebSocket connecting.</color>");
                    await webSocket.ConnectAsync(new Uri(url), cancellationToken);

                    Debug.Log("<color=cyan>WebSocket receiving.</color>");
                    await Receive();

                    Debug.Log("<color=cyan>WebSocket closed.</color>");
                }
                catch (OperationCanceledException)
                {
                    Debug.Log("<color=cyan>WebSocket shutting down.</color>");
                }
                catch (WebSocketException e)
                {
                    Debug.Log("<color=cyan>WebSocket connection lost.</color>");
                    Debug.LogWarning(e.Message);
                    Debug.LogWarning(e.WebSocketErrorCode);
                    Debug.LogWarning(e.ErrorCode);
                }
                catch (Exception ex)
                {
                    Debug.LogWarning(ex);
                    throw;
                }
            }

            Debug.Log("<color=cyan>Websocket reconnecting.</color>");
            await Task.Delay(1000);
        }
    }
Exemple #20
0
    public static void Connect(params string[] tracker)
    {
        if (tracker == null || tracker.Length == 0)
        {
            tracker = new[] { "#indie", "#indiedev", "#gamedev", "indie game dev", "game dev", "indie dev" };
        }
        if (!initialized || (connected && source.Active))
        {
            Debug.LogWarning("Trying to connect when source is not initialized or is already connected.");
            return;
        }

        try {
            source.Start(new StreamingAPIParameters {
                Track = tracker
            });
            connected = true;
            Debug.Log("Stream connected");
        } catch (Exception ex) {
            Debug.LogError($@"Error reading config: If you're running this for the first time, please make sure you have your version of Twitter.config at application's working directory - {ex.Message}");
            Debug.LogException(ex);
        }
    }
    protected void InitTypes()
    {
        m_setTypes = new HashSet <string>();
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();

        foreach (var assembly in assemblies)
        {
            try
            {
                if (assembly is System.Reflection.Emit.AssemblyBuilder)
                {
                    continue;
                }

                var takeAllTypes  = SD_Assembly.IsScriptAssemblyName(assembly.GetName().Name);
                var assemblyTypes = takeAllTypes ? assembly.GetTypes() : assembly.GetExportedTypes();
                foreach (var type in assemblyTypes)
                {
                    var name  = type.Name;
                    var index = name.IndexOf('`');
                    if (index >= 0)
                    {
                        name = name.Remove(index);
                    }
                    m_setTypes.Add(name);
                    if (type.IsSubclassOf(typeof(Attribute)) && name.EndsWith("Attribute", StringComparison.Ordinal))
                    {
                        m_setTypes.Add(type.Name.Substring(0, type.Name.Length - "Attribute".Length));
                    }
                }
            }
            catch (ReflectionTypeLoadException)
            {
                Debug.LogWarning("Error reading types from assembly " + assembly.FullName);
            }
        }
    }
    public void OnPreprocessBuild(BuildReport report)
    {
        Debug.Log(
            $"[PlotBuildTools] OnPreprocessBuild for target {report.summary.platform} at path {report.summary.outputPath}");

        #region Set Build Properties LastBuildTime - Reference: https: //answers.unity.com/questions/1425758/how-can-i-find-all-instances-of-a-scriptable-objec.html
        //FindAssets uses tags check documentation for more info
        string[] guids = AssetDatabase.FindAssets($"t:{typeof(PlotBuildSettings)}");
        if (guids.Length > 1)
        {
            Debug.LogErrorFormat("[PlotBuildTools] Found more than 1 Build Properties: {0}. Using first one!",
                                 guids.Length);
        }

        if (guids.Length > 0)
        {
            string            path          = AssetDatabase.GUIDToAssetPath(guids[0]);
            PlotBuildSettings buildSettings = AssetDatabase.LoadAssetAtPath <PlotBuildSettings>(path);
            buildSettings.LastBuildTime = DateTime.Now.ToString("yyyy/MM/dd (HH:mm)"); // case sensitive
            buildSettings.EditorRefreshScriptingBackend(report.summary.platform);
            buildSettings.RepositoryVersion = PlotBuildSettings.GetHgVersion();
#if UNITY_CLOUD_BUILD
            buildSettings.RepositoryVersion += "-cloud";
#endif
            EditorUtility.SetDirty(buildSettings);
            Debug.LogFormat("[PlotBuildTools] Updated settings LastBuildDate to \"{0}\". Settings Path: {1}",
                            buildSettings.LastBuildTime, path);

            System.IO.File.WriteAllText(@"Build\Version.txt", "version = '" + buildSettings.LastBuildTime + "'");
        }
        else
        {
            // TODO: AUTO-CREATE ONE!
            Debug.LogWarning("[PlotBuildTools] Couldn't find Build Settings, please create one!");
        }
        #endregion
    }
Exemple #23
0
    private static string GetBundleFromAsset(int index, string key, string assetName, XElement item, CSVBuilder instance)
    {
        string bundleName = "0";

        string[][] assetNames  = instance.packData.assetNames;
        string[]   bundleNames = instance.packData.assetBundleNames;

        // TODO: Improve asset auto assignment search algorithms
        // 1. reduce search string to essential parts such as filename or first part of directory.
        // 2. cache found filenames to avoid same filename traps.
        // 3. research about shitty case of search algorithms (similar names, fucky situations (like url parsing you f****r))
        for (int i = 0; i < bundleNames.Length; i++)
        {
            foreach (string name in assetNames[i])
            {
                string fuckingshit = name.Substring(name.LastIndexOf('/')); // yeah fuckoff you f*****g c**t
                if (fuckingshit.Contains(assetName))
                {
                    bundleName = bundleNames[i];
                }
            }
        }

        //Debug.Log(string.Format("{0}: {1}", key, bundleName));
        if (bundleName == "0")
        {
            try {
                int    dashIndex = key.LastIndexOf('-') < 0 ? key.Length : key.LastIndexOf('-');
                string bundleKey = key.Substring(0, dashIndex) + "-bundle";
                bundleName = item.Attribute(bundleKey) != null?item.Attribute(bundleKey).Value : "0";
            } catch (Exception e) {
                Debug.LogWarning("Could not catch shits.");
            }
        }

        return(string.Format("{0},{1},", bundleName, assetName));
    }
    /// <summary>
    /// 通知响应回调方法,消息到达
    /// </summary>
    /// <param name="subject">消息Id</param>
    /// <param name="msg">传递给处理方法的参数(服务器传回来的数据)</param>
    public static void Notify(ProtoID subject, Protocol msg)
    {
        List <WeakAction>          weakHandlers   = null;
        List <NetworkEventHandler> strongHandlers = null;

        //if (subject.BodyType == typeof(LuaProtoBody) && LuaMessageCallback != null)
        //{
        //    LuaMessageCallback(msg);
        //    return;
        //}

        if (s_weakNetworkMsgMap.TryGetValue(subject, out weakHandlers))
        {
            for (int i = weakHandlers.Count - 1; i >= 0; i--)
            {
                if (!weakHandlers[i].Invoke(msg))
                {
                    weakHandlers.RemoveAt(i);
                }
            }
        }
        else if (s_strongNetworkMsgMap.TryGetValue(subject, out strongHandlers))
        {
            for (int i = strongHandlers.Count - 1; i >= 0; i--)
            {
                if (strongHandlers[i] != null)
                {
                    strongHandlers[i](msg);
                }
            }
        }
        else
        {
            Debug.LogWarning(string.Format("消息{0}未注册事件处理方法", subject.ID));
        }
    }
Exemple #25
0
        void UpdateShader(Identifier nodeId)
        {
            var node = m_Graph.GetNodeFromTempId(nodeId) as AbstractMaterialNode;

            if (node == null)
            {
                return;
            }
            var renderData = Get(m_RenderDatas, nodeId);

            if (renderData == null || renderData.shaderData == null)
            {
                return;
            }
            var shaderData = renderData.shaderData;

            if (!(node is IMasterNode) && !node.hasPreview)
            {
                shaderData.shaderString = null;
            }
            else
            {
                var masterNode = node as IMasterNode;
                if (masterNode != null)
                {
                    List <PropertyCollector.TextureInfo> configuredTextures;
                    shaderData.shaderString = masterNode.GetShader(GenerationMode.Preview, node.name, out configuredTextures);
                }
                else
                {
                    shaderData.shaderString = m_Graph.GetPreviewShader(node).shader;
                }
            }

            var debugOutputPath = DefaultShaderIncludes.GetDebugOutputPath();

            if (debugOutputPath != null)
            {
                File.WriteAllText(debugOutputPath + "/GeneratedShader.shader", (shaderData.shaderString ?? "null").Replace("UnityEngine.MaterialGraph", "Generated"));
            }

            if (string.IsNullOrEmpty(shaderData.shaderString))
            {
                if (shaderData.shader != null)
                {
                    ShaderUtil.ClearShaderErrors(shaderData.shader);
                    Object.DestroyImmediate(shaderData.shader, true);
                    shaderData.shader = null;
                }
                return;
            }

            if (shaderData.shader == null)
            {
                shaderData.shader           = ShaderUtil.CreateShaderAsset(shaderData.shaderString);
                shaderData.shader.hideFlags = HideFlags.HideAndDontSave;
            }
            else
            {
                ShaderUtil.ClearShaderErrors(shaderData.shader);
                ShaderUtil.UpdateShaderAsset(shaderData.shader, shaderData.shaderString);
            }

            // Debug output
            if (MaterialGraphAsset.ShaderHasError(shaderData.shader))
            {
                var errors = MaterialGraphAsset.GetShaderErrors(shaderData.shader);
                foreach (var error in errors)
                {
                    Debug.LogFormat("Compilation error in {3} at line {1} (on {2}):\n{0}", error.message, error.line, error.platform, "graph");
                }
                shaderData.hasError = true;
                if (debugOutputPath != null)
                {
                    var message = "RecreateShader: " + node.GetVariableNameForNode() + Environment.NewLine + shaderData.shaderString;
                    Debug.LogWarning(message);
                }
                ShaderUtil.ClearShaderErrors(shaderData.shader);
                Object.DestroyImmediate(shaderData.shader, true);
                shaderData.shader = null;
            }
            else
            {
                shaderData.hasError = false;
            }
        }
Exemple #26
0
        void UpdateShaders()
        {
            if (m_DirtyShaders.Any())
            {
                PropagateNodeSet(m_DirtyShaders);

                var masterNodes    = new List <INode>();
                var colorNodes     = new List <INode>();
                var wireframeNodes = new List <INode>();
                foreach (var index in m_DirtyShaders)
                {
                    var node = m_Graph.GetNodeFromTempId(m_Identifiers[index]) as AbstractMaterialNode;
                    if (node == null)
                    {
                        continue;
                    }
                    var masterNode = node as IMasterNode;
                    if (masterNode != null)
                    {
                        masterNodes.Add(node);
                    }
                    else if (node.previewMode == PreviewMode.Wireframe)
                    {
                        wireframeNodes.Add(node);
                    }
                    else
                    {
                        colorNodes.Add(node);
                    }
                }
                var count = Math.Min(colorNodes.Count, 1) + masterNodes.Count;

                try
                {
                    var i = 0;
                    EditorUtility.DisplayProgressBar("Shader Graph", string.Format("Compiling preview shaders ({0}/{1})", i, count), 0f);
                    foreach (var node in masterNodes)
                    {
                        UpdateShader(node.tempId);
                        i++;
                        EditorUtility.DisplayProgressBar("Shader Graph", string.Format("Compiling preview shaders ({0}/{1})", i, count), 0f);
                    }
                    if (colorNodes.Count > 0)
                    {
                        var results = m_Graph.GetUberColorShader();
                        m_OutputIdName = results.outputIdProperty.referenceName;
                        ShaderUtil.UpdateShaderAsset(m_ColorShader, results.shader);
                        var debugOutputPath = DefaultShaderIncludes.GetDebugOutputPath();
                        if (debugOutputPath != null)
                        {
                            File.WriteAllText(debugOutputPath + "/ColorShader.shader", (results.shader ?? "null").Replace("UnityEngine.MaterialGraph", "Generated"));
                        }
                        bool uberShaderHasError = false;
                        if (MaterialGraphAsset.ShaderHasError(m_ColorShader))
                        {
                            var errors  = MaterialGraphAsset.GetShaderErrors(m_ColorShader);
                            var message = new ShaderStringBuilder();
                            message.AppendLine(@"Preview shader for graph has {0} error{1}:", errors.Length, errors.Length != 1 ? "s" : "");
                            foreach (var error in errors)
                            {
                                INode node;
                                try
                                {
                                    node = results.sourceMap.FindNode(error.line);
                                    message.AppendLine("Shader compilation error in {3} at line {1} (on {2}):\n{0}", error.message, error.line, error.platform, node != null ? string.Format("node {0} ({1})", node.name, node.guid) : "graph");
                                    message.AppendLine(error.messageDetails);
                                    message.AppendNewLine();
                                }
                                catch
                                {
                                    message.AppendLine("Shader compilation error in {3} at line {1} (on {2}):\n{0}", error.message, error.line, error.platform, "graph");
                                }
                            }
                            Debug.LogWarning(message.ToString());
                            ShaderUtil.ClearShaderErrors(m_ColorShader);
                            ShaderUtil.UpdateShaderAsset(m_ColorShader, k_EmptyShader);
                            uberShaderHasError = true;
                        }

                        foreach (var node in colorNodes)
                        {
                            var renderData = GetRenderData(node.tempId);
                            if (renderData == null)
                            {
                                continue;
                            }
                            var shaderData = renderData.shaderData;
                            shaderData.shader   = m_ColorShader;
                            shaderData.hasError = uberShaderHasError;
                        }
                        i++;
                        EditorUtility.DisplayProgressBar("Shader Graph", string.Format("Compiling preview shaders ({0}/{1})", i, count), 0f);
                    }
                }
                finally
                {
                    EditorUtility.ClearProgressBar();
                }

                // Union dirty shaders into dirty previews
                m_DirtyPreviews.UnionWith(m_DirtyShaders);
                m_DirtyShaders.Clear();
            }
        }
Exemple #27
0
		void Parse(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) {
			if(!string.IsNullOrEmpty(str)) {
				str = str.Trim(WHITESPACE);
				if(strict) {
					if(str[0] != '[' && str[0] != '{') {
						type = Type.NULL;
						Debug.LogWarning("Improper (strict) JSON formatting.  First character must be [ or {");
						return;
					}
				}
				if(str.Length > 0) {
					if(string.Compare(str, "true", true) == 0) {
						type = Type.BOOL;
						b = true;
					} else if(string.Compare(str, "false", true) == 0) {
						type = Type.BOOL;
						b = false;
					} else if(string.Compare(str, "null", true) == 0) {
						type = Type.NULL;
	#if USEFLOAT
					} else if(str == INFINITY) {
						type = Type.NUMBER;
						n = float.PositiveInfinity;
					} else if(str == NEGINFINITY) {
						type = Type.NUMBER;
						n = float.NegativeInfinity;
					} else if(str == NaN) {
						type = Type.NUMBER;
						n = float.NaN;
	#else
					} else if(str == INFINITY) {
						type = Type.NUMBER;
						n = double.PositiveInfinity;
					} else if(str == NEGINFINITY) {
						type = Type.NUMBER;
						n = double.NegativeInfinity;
					} else if(str == NaN) {
						type = Type.NUMBER;
						n = double.NaN;
	#endif
					} else if(str[0] == '"') {
						type = Type.STRING;
						this.str = str.Substring(1, str.Length - 2);
					} else {
						int tokenTmp = 1;
						/*
						 * Checking for the following formatting (www.json.org)
						 * object - {"field1":value,"field2":value}
						 * array - [value,value,value]
						 * value - string	- "string"
						 *		 - number	- 0.0
						 *		 - bool		- true -or- false
						 *		 - null		- null
						 */
						int offset = 0;
						switch(str[offset]) {
							case '{':
								type = Type.OBJECT;
								keys = new List<string>();
								list = new List<JSONObject>();
								break;
							case '[':
								type = Type.ARRAY;
								list = new List<JSONObject>();
								break;
							default:
								try {
	#if USEFLOAT
									n = System.Convert.ToSingle(str);
	#else
									n = System.Convert.ToDouble(str);				 
	#endif
									type = Type.NUMBER;
								} catch(System.FormatException) {
									type = Type.NULL;
									Debug.LogWarning("improper JSON formatting:" + str);
								}
								return;
						}
						string propName = "";
						bool openQuote = false;
						bool inProp = false;
						int depth = 0;
						while(++offset < str.Length) {
							if(System.Array.IndexOf(WHITESPACE, str[offset]) > -1)
								continue;
							if(str[offset] == '\\') {
								offset += 1;
								continue;
							}
							if(str[offset] == '"') {
								if(openQuote) {
									if(!inProp && depth == 0 && type == Type.OBJECT)
										propName = str.Substring(tokenTmp + 1, offset - tokenTmp - 1);
									openQuote = false;
								} else {
									if(depth == 0 && type == Type.OBJECT)
										tokenTmp = offset;
									openQuote = true;
								}
							}
							if(openQuote)
								continue;
							if(type == Type.OBJECT && depth == 0) {
								if(str[offset] == ':') {
									tokenTmp = offset + 1;
									inProp = true;
								}
							}

							if(str[offset] == '[' || str[offset] == '{') {
								depth++;
							} else if(str[offset] == ']' || str[offset] == '}') {
								depth--;
							}
							//if  (encounter a ',' at top level)  || a closing ]/}
							if((str[offset] == ',' && depth == 0) || depth < 0) {
								inProp = false;
								string inner = str.Substring(tokenTmp, offset - tokenTmp).Trim(WHITESPACE);
								if(inner.Length > 0) {
									if(type == Type.OBJECT)
										keys.Add(propName);
									if(maxDepth != -1)															//maxDepth of -1 is the end of the line
										list.Add(Create(inner, (maxDepth < -1) ? -2 : maxDepth - 1));
									else if(storeExcessLevels)
										list.Add(CreateBakedObject(inner));

								}
								tokenTmp = offset + 1;
							}
						}
					}
				} else type = Type.NULL;
			} else type = Type.NULL;	//If the string is missing, this is a null
			//Profiler.EndSample();
		}
        internal static string GenerateResponseFile(ScriptAssembly assembly, string tempBuildDirectory)
        {
            var assemblyOutputPath = PrepareFileName(AssetPath.Combine(tempBuildDirectory, assembly.Filename));

            var arguments = new List <string>
            {
                "/target:library",
                "/nowarn:0169",
                "/out:" + assemblyOutputPath
            };

            if (assembly.CompilerOptions.AllowUnsafeCode)
            {
                arguments.Add("/unsafe");
            }

            if (assembly.CompilerOptions.UseDeterministicCompilation)
            {
                arguments.Add("/deterministic");
            }

            arguments.Add("/debug:portable");

            if (assembly.CompilerOptions.CodeOptimization == CodeOptimization.Release)
            {
                arguments.Add("/optimize+");
            }
            else
            {
                arguments.Add("/optimize-");
            }

            FillCompilerOptions(arguments, assembly.BuildTarget);

            string[] scriptAssemblyReferences = new string[assembly.ScriptAssemblyReferences.Length];
            for (var index = 0; index < assembly.ScriptAssemblyReferences.Length; index++)
            {
                var reference = assembly.ScriptAssemblyReferences[index];
                scriptAssemblyReferences[index] = "/reference:" +
                                                  PrepareFileName(AssetPath.Combine(assembly.OutputDirectory,
                                                                                    reference.Filename));
            }
            Array.Sort(scriptAssemblyReferences, StringComparer.Ordinal);
            arguments.AddRange(scriptAssemblyReferences);

            Array.Sort(assembly.References, StringComparer.Ordinal);
            foreach (var reference in assembly.References)
            {
                arguments.Add("/reference:" + PrepareFileName(reference));
            }

            var defines = assembly.Defines.Distinct().ToArray();

            Array.Sort(defines, StringComparer.Ordinal);
            foreach (var define in defines)
            {
                arguments.Add("/define:" + define);
            }

            Array.Sort(assembly.Files, StringComparer.Ordinal);
            foreach (var source in assembly.Files)
            {
                var f = PrepareFileName(source);
                f = Paths.UnifyDirectorySeparator(f);
                arguments.Add(f);
            }

            var responseFileProvider       = assembly.Language?.CreateResponseFileProvider();
            var responseFilesList          = responseFileProvider?.Get(assembly.OriginPath) ?? new List <string>();
            HashSet <string> responseFiles = new HashSet <string>(responseFilesList);

            string obsoleteResponseFile = responseFiles.SingleOrDefault(
                x => CompilerSpecificResponseFiles.MicrosoftCSharpCompilerObsolete.Contains(AssetPath.GetFileName(x)));

            if (!string.IsNullOrEmpty(obsoleteResponseFile))
            {
                Debug.LogWarning($"Using obsolete custom response file '{AssetPath.GetFileName(obsoleteResponseFile)}'. Please use '{CompilerSpecificResponseFiles.MicrosoftCSharpCompiler}' instead.");
            }

            foreach (var file in responseFiles)
            {
                AddResponseFileToArguments(arguments, file, assembly.CompilerOptions.ApiCompatibilityLevel);
            }

            var responseFile = CommandLineFormatter.GenerateResponseFile(arguments);

            return(responseFile);
        }
        /// <summary>
        /// 对比更新下载
        /// </summary>
        IEnumerator OnUpdateResource()
        {
            if (Global.app.GetAppMode() == AppMode.Developing)
            {
                OnResourceInited();
                yield break;
            }
            string dataPath = Util.DataPath;
            string url      = Global.WebUrl;
            string message  = string.Empty;
            string random   = DateTime.Now.ToString("yyyymmddhhmmss");
            string listUrl  = url + "files.txt?v=" + random;

            Debug.LogWarning("LoadUpdate---->>>" + listUrl);

            WWW www = new WWW(listUrl); yield return(www);

            if (www.error != null)
            {
                OnUpdateFailed(string.Empty);
                yield break;
            }
            if (!Directory.Exists(dataPath))
            {
                Directory.CreateDirectory(dataPath);
            }
            File.WriteAllBytes(dataPath + "files.txt", www.bytes);
            string filesText = www.text;

            string[] files = filesText.Split('\n');

            for (int i = 0; i < files.Length; i++)
            {
                if (string.IsNullOrEmpty(files[i]))
                {
                    continue;
                }
                string[] keyValue  = files[i].Split('|');
                string   f         = keyValue[0];
                string   localfile = (dataPath + f).Trim();
                string   path      = Path.GetDirectoryName(localfile);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string fileUrl   = url + f + "?v=" + random;
                bool   canUpdate = !File.Exists(localfile);
                if (!canUpdate)
                {
                    string remoteMd5 = keyValue[1].Trim();
                    string localMd5  = Util.md5file(localfile);
                    canUpdate = !remoteMd5.Equals(localMd5);
                    if (canUpdate)
                    {
                        File.Delete(localfile);
                    }
                }
                if (canUpdate)
                {
                    Debug.Log(fileUrl);
                    OnDownloadFile(fileUrl, localfile);
                    while (!(IsDownComplete(localfile)))
                    {
                        yield return(new WaitForEndOfFrame());
                    }
                }
            }
            yield return(new WaitForEndOfFrame());

            OnResourceInited();
        }
        private void StartDetectionInternal(System.Action <string> callback)
        {
            if (isRunning)
            {
                Debug.LogWarning(FinalLogPrefix + "already running!", this);
                return;
            }

            if (!enabled)
            {
                Debug.LogWarning(FinalLogPrefix + "disabled but StartDetection still called from somewhere (see stack trace for this message)!", this);
                return;
            }

#if UNITY_EDITOR
            if (!UnityEditor.EditorPrefs.GetBool("ACTDIDEnabledGlobal", false))
            {
                Debug.LogWarning(FinalLogPrefix + "is not enabled in Anti-Cheat Toolkit Settings!\nPlease, check readme.pdf for details.", this);
                DisposeInternal();
                return;
            }
#if !ACTK_DEBUG_NORMAL
            if (Application.isEditor)
            {
                Debug.LogWarning(FinalLogPrefix + "does not work in editor (check readme.pdf for details).", this);
                DisposeInternal();
                return;
            }
#else
            Debug.LogWarning(FinalLogPrefix + "works in debug mode. There WILL BE false positives in editor, it's fine!", this);
#endif
#endif
            if ((CheatDetected != null || callback != null) && detectionEventHasListener)
            {
                Debug.LogWarning(FinalLogPrefix + "has properly configured Detection Event in the inspector, but still get started with Action callback. Both Action and Detection Event will be called on detection. Are you sure you wish to do this?", this);
            }

            if (CheatDetected == null && callback == null && !detectionEventHasListener)
            {
                Debug.LogWarning(FinalLogPrefix + "was started without any callbacks. Please configure Detection Event in the inspector, or pass the callback Action to the StartDetection method.", this);
                enabled = false;
                return;
            }

            CheatDetected += callback;
            started        = true;
            isRunning      = true;

            if (allowedAssemblies == null)
            {
                LoadAndParseAllowedAssemblies();
            }

            if (signaturesAreNotGenuine)
            {
                OnCheatingDetected("signatures");
                return;
            }

            string cause;

            if (!FindInjectionInCurrentAssemblies(out cause))
            {
                // listening for new assemblies
                AppDomain.CurrentDomain.AssemblyLoad += OnNewAssemblyLoaded;
            }
            else
            {
                OnCheatingDetected(cause);
            }
        }