/// <summary>Parses user data file.</summary> public static bool TryParseJSONFile <T>(byte[] fileData, out T jsonObject) { // early out if (fileData == null || fileData.Length == 0) { jsonObject = default(T); return(false); } // attempt to parse data try { string dataString = Encoding.UTF8.GetString(fileData); jsonObject = JsonConvert.DeserializeObject <T>(dataString); return(true); } catch (Exception e) { string warningInfo = ("[mod.io] Failed to parse user data from file."); Debug.LogWarning(warningInfo + Utility.GenerateExceptionDebugString(e)); jsonObject = default(T); return(false); } }
public static void Dispose(ref T[] disposing) { #if DEV_MODE && PI_ASSERTATIONS Debug.Assert(!typeof(IDrawer).IsAssignableFrom(typeof(T)), "Use DrawerArrayPool instead"); Debug.Assert(typeof(T) != Types.UnityObject || !LinkedMemberHierarchy.AnyHierarchyTargetsArrayEquals(disposing as UnityEngine.Object[])); #endif int length = disposing.Length; //don't pool zero-length arrays since we'll be using ZeroSizeArray field for those purposes if (length > 0) { PolymorphicPool <T[]> pool; #if DEV_MODE && WARN_IF_POOLING_EXTERNALLY_CREATED_ITEMS if (!created.TryGetValue(length, out pool) || !pool.Contains(disposing)) { Debug.LogWarning("ArrayPool<" + StringUtils.ToString(typeof(T)) + ">.Dispose was called for array that was not created by ArrayPool. This could lead to bugs:\ndisposing: " + StringUtils.ToString(disposing)); } else { pool.Remove(disposing); } #endif if (!pools.TryGetValue(length, out pool)) { pool = new PolymorphicPool <T[]>(1, 25); pools[length] = pool; } pool.Pool(ref disposing); } disposing = null; }
// called by Unity private static void OnPostprocessAllAssets(String[] mportedAssets, String[] deletedAssets, String[] movedAssets, String[] movedFromAssetPaths) { if (!EditorPrefs.GetBool(ActEditorGlobalStuff.PREFS_INJECTION_GLOBAL)) { return; } if (!InjectionDetectorTargetCompatibleCheck()) { return; } if (deletedAssets.Length > 0) { foreach (string deletedAsset in deletedAssets) { if (deletedAsset.IndexOf(ActEditorGlobalStuff.INJECTION_DATA_FILE) > -1 && !EditorApplication.isCompiling) { #if (DEBUG || DEBUG_VERBOSE || DEBUG_PARANIOD) Debug.LogWarning("Looks like Injection Detector data file was accidentally removed! Re-creating...\nIf you wish to remove " + ActEditorGlobalStuff.INJECTION_DATA_FILE + " file, just disable Injection Detecotr in the ACT Options window."); #endif InjectionAssembliesScan(); } } } }
public static void Purge() { string result = GitCommand.RunGitCommand(@"clean -d -x -f"); Debug.LogWarning("Purging Repo: \n" + result); AssetDatabase.Refresh(); }
// --------------------------------------------------------------- // Android build post-processing // --------------------------------------------------------------- private List <BuildHashes> GetAndroidBuildHashes(BuildReport report, FileFilter[] fileFilters, SHA1Wrapper sha1) { var result = new List <BuildHashes>(); foreach (var reportFile in report.files) { var path = reportFile.path; var extension = Path.GetExtension(path); if (!string.IsNullOrEmpty(extension)) { extension = extension.ToLower(CultureInfo.InvariantCulture); } if (extension == ".apk" || extension == ".aab") { var hash = GetAndroidArchiveHashes(path, fileFilters, sha1); result.Add(hash); } } if (result.Count == 0) { Debug.LogWarning(EditorTools.ConstructError("Couldn't find compiled APK or AAB build.\n" + "This is fine if you use Export Project feature. In other case:")); } return(result); }
public static void ToSVGFiles() { var batFile = @"C:\GameProjects\Prototypes\Assets\BATs\SVGToFiles.bat"; if (!File.Exists(batFile)) { Debug.LogError("SVGLayerToSperatedFiles batFile pointing towards nothing"); return; } var path = AssetDatabase.GetAssetPath(Selection.activeObject); var dirPath = Path.GetDirectoryName(path); var svgPath = dirPath + "/" + Selection.activeObject.name + ".svg"; var env = System.Environment.CurrentDirectory; var fullSVGPath = Path.Combine(env, svgPath); var targetPath = Path.Combine(env, dirPath); var cmd = " \"" + fullSVGPath + "\""; cmd += " --destdir \"" + targetPath + "/\""; Debug.LogWarning(cmd); ExecuteCommand(cmd); }
/// <summary> /// Resolve all initial constraints /// </summary> /// <param name="cells">The grid`s cells</param> private void ApplyInitialConstraints(ref Cell[,] cells) { Debug.LogWarning("Resolve initial constraints"); StartGoalConstraint(ref cells); BorderOutsideConstraint(ref cells); }
public void Log() { switch (_level) { case LogLevel.Trace: Debug.Log(_message); break; case LogLevel.Debug: Debug.Log(_message); break; case LogLevel.Info: Debug.Log(_message); break; case LogLevel.Warn: Debug.LogWarning(_message); break; case LogLevel.Error: Debug.LogError(_message); break; default: throw new ArgumentOutOfRangeException(); } }
private void CheckFile() { if (CheckLength() == false) { Debug.LogException(new Exception("CheckFile===>CheckLength Error Url->" + Url)); Retry(); return; } LoadingProgress.Instance.SetDownloadText(I18NManager.Get("Download_CheckFiles")); Loom.RunAsync(() => { Stopwatch sw = Stopwatch.StartNew(); bool md5Fixed = CheckMd5(); Loom.QueueOnMainThread(() => { Debug.LogWarning("===CheckFile CheckMd5耗时:" + sw.ElapsedMilliseconds + "ms Url->" + Url); if (md5Fixed) { _onComplete?.Invoke(this); } else { Debug.LogException(new Exception("CheckFile===>md5Fixed Error Url->" + Url)); Retry(); } }); }); }
public static bool TryParse(string rawLog, out InkCompilerLog log) { var match = _errorRegex.Match(rawLog); if (match.Success) { Ink.ErrorType errorType = Ink.ErrorType.Author; string filename = null; int lineNo = -1; string message = null; var errorTypeCapture = match.Groups["errorType"]; if (errorTypeCapture != null) { var errorTypeStr = errorTypeCapture.Value; if (errorTypeStr == "AUTHOR" || errorTypeStr == "TODO") { errorType = Ink.ErrorType.Author; } else if (errorTypeStr == "WARNING") { errorType = Ink.ErrorType.Warning; } else if (errorTypeStr == "ERROR") { errorType = Ink.ErrorType.Error; } else { Debug.LogWarning("Could not parse error type from " + errorTypeStr); } } var filenameCapture = match.Groups["filename"]; if (filenameCapture != null) { filename = filenameCapture.Value; } var lineNoCapture = match.Groups["lineNo"]; if (lineNoCapture != null) { lineNo = int.Parse(lineNoCapture.Value); } var messageCapture = match.Groups["message"]; if (messageCapture != null) { message = messageCapture.Value.Trim(); } log = new InkCompilerLog(errorType, message, filename, lineNo); return(true); } else { Debug.LogWarning("Could not parse InkFileLog from log: " + rawLog); log = null; return(false); } }
/// <summary> /// Wave-function-collapse algorithm /// TODO: Multithreading? /// </summary> /// <param name="cells">The grid`s cells</param> /// <param name="seed">RNG seed</param> public void GenerateLevelWFC(ref Cell[,] cells, int seed) { // Set RNG seed Random.InitState(seed); // Instantiate cells heap OrderedCells = new Heap <Cell>(cells.GetLength(0) * cells.GetLength(1)); for (int i = 0; i < cells.GetLength(0); i++) { for (int j = 0; j < cells.GetLength(1); j++) { OrderedCells.Add(cells[i, j]); } } var stopwatch = new Stopwatch(); stopwatch.Start(); Debug.LogWarning("Start Wave-function-collapse algorithm"); ApplyInitialConstraints(ref cells); while (true) { //Debug.Log("Starting another iteration! Removing next module."); // Remove finished cells from heap while (OrderedCells.Count > 0) { var cell = OrderedCells.GetFirst(); if (cell.SolvedScore == 1) { OrderedCells.RemoveFirst(); } else { break; } } // Remove random module from cell if (OrderedCells.Count > 0) { var cell = OrderedCells.GetFirst(); cell.RemoveModule(cell.possibleModulesIndices[Random.Range(0, cell.possibleModulesIndices.Count)]); } else { // Finished break; } } stopwatch.Stop(); Debug.LogWarning( $"Wave-function-collapse algorithm finished in {stopwatch.Elapsed.TotalMilliseconds}ms (Seed: {seed})"); }
public SfbFileSystemEntry CreateNewFileAndAddEntry(string path) { if (entries.ContainsKey(path)) { Debug.LogWarning("File already exists"); return(null); } SfbFileSystemEntry entry = new SfbFileSystemEntry(path, false, SfbFileSystemEntryType.File); #if !UNITY_WEBGL && !UNITY_WEBPLAYER if (!IsFake) { try { File.Create(path); } catch (Exception e) { Debug.LogException(e); Debug.LogError("Could not create file"); return(null); } } #endif AddEntry(entry); return(entry); }
// called by Unity private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { if (!EditorPrefs.GetBool(ACTkEditorGlobalStuff.PrefsInjectionEnabled)) { return; } if (!IsInjectionDetectorTargetCompatible()) { InjectionDetectorTargetCompatibleCheck(); return; } if (deletedAssets.Length > 0) { foreach (var deletedAsset in deletedAssets) { if (deletedAsset.IndexOf(ACTkEditorGlobalStuff.InjectionDataFile, StringComparison.Ordinal) > -1 && !EditorApplication.isCompiling) { #if (ACTK_DEBUG || ACTK_DEBUG_VERBOSE || ACTK_DEBUG_PARANIOD) Debug.LogWarning("Looks like Injection Detector data file was accidentally removed! Re-creating...\nIf you wish to remove " + ACTkEditorGlobalStuff.INJECTION_DATA_FILE + " file, just disable Injection Detecotr in the ACTk Settings window."); #endif InjectionAssembliesScan(); } } } }
/// <summary> /// Writes warning to console. Works only when Debugger is Enabled. /// </summary> /// <param name="message">Warning to write.</param> /// <param name="context">Context.</param> public static void LogWarning(string message, Object context = null) { if (LogLevelEnabled(LogLevel.Warning)) { Debug.LogWarning(message, context); } }
static void WriteLocalizedValue(string valueName, StreamWriter stream, Locale locale, LocalizedString localizedString, PlistDocument plistDocument) { if (localizedString.IsEmpty) { return; } var tableCollection = LocalizationEditorSettings.GetStringTableCollection(localizedString.TableReference); var table = tableCollection?.GetTable(locale.Identifier) as StringTable; var entry = table?.GetEntryFromReference(localizedString.TableEntryReference); if (entry == null || string.IsNullOrWhiteSpace(entry.LocalizedValue)) { // Use fallback? var fallBack = FallbackLocaleHelper.GetLocaleFallback(locale); if (fallBack != null) { WriteLocalizedValue(valueName, stream, fallBack, localizedString, plistDocument); return; } Debug.LogWarning($"{valueName}: Could not find a localized value for {locale} from {localizedString}"); return; } Debug.Assert(!entry.IsSmart, $"Localized App Values ({valueName}) do not support Smart Strings - {localizedString}"); stream.WriteLine($"\"{valueName}\" = \"{entry.LocalizedValue}\";"); plistDocument.root.SetString(valueName, string.Empty); }
private void PerformAwake() { workingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (new DirectoryInfo(workingDirectory).Name == "plugins") { Debug.LogWarning(LOG + "HjUpdaterAPI has been installed outside of a folder container. Re-installation..."); Directory.CreateDirectory(Path.Combine(workingDirectory, MODFOLDERCONTAINER)); File.Move(Path.Combine(workingDirectory, Assembly.GetExecutingAssembly().Location), Path.Combine(workingDirectory, MODFOLDERCONTAINER, "HjUpdaterAPI.dll")); bool depE = File.Exists(Path.Combine(workingDirectory, "Newtonsoft.Json.dll")); if (depE) { File.Move(Path.Combine(workingDirectory, "Newtonsoft.Json.dll"), Path.Combine(workingDirectory, MODFOLDERCONTAINER, "Newtonsoft.Json.dll")); workingDirectory = Path.Combine(workingDirectory, MODFOLDERCONTAINER); } else { Debug.LogError(LOG + "Missing dependency Newtonsoft.Json.dll ! Please add this file to your BepinEx/plugin/" + MODFOLDERCONTAINER + " folder. This dll was included inside the archive of HjUpdaterAPI. Until the problem is resolved, no updates checks nor auto-updates will be performed."); this.enabled = false; } } if (!Directory.Exists(Path.Combine(workingDirectory, BACKUPFOLDER))) { Directory.CreateDirectory(Path.Combine(workingDirectory, BACKUPFOLDER)); } }
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { StringBuilder sb = new StringBuilder(); sb.Append(source); sb.Append(" [tid="); sb.Append(Thread.CurrentThread.ManagedThreadId); sb.Append("]: "); sb.Append(message); var txt = sb.ToString(); if (eventType < TraceEventType.Warning) { Debug.LogWarning(txt); // Unity Editor Tests treat error messages as test failure return; } if (eventType < TraceEventType.Information) { Debug.LogWarning(txt); return; } Debug.Log(txt); }
void TickConnected(uint time) { // detect common events & ping HandleTimeout(time); HandleDeadLink(); HandlePing(time); HandleChoked(); kcp.Update(time); // any message received? if (ReceiveNext(out ArraySegment <byte> message)) { // handshake message? if (Utils.SegmentsEqual(message, Hello)) { Debug.Log("KCP: received handshake"); state = KcpState.Authenticated; OnAuthenticated?.Invoke(); } // otherwise it's random data from the internet, not // from a legitimate player. disconnect. else { Debug.LogWarning("KCP: received random data before handshake. Disconnecting the connection."); Disconnect(); } } }
/// <summary> /// Performs a redo operation /// </summary> public void Redo() { try { m_RedoGoingOn = true; if (m_RedoStack.Count == 0) { throw new InvalidOperationException("Nothing in the redo stack"); } object oUndoData = m_RedoStack.Pop(); Type undoDataType = oUndoData.GetType(); // If the stored operation was a transaction, perform the redo as a transaction too. if (typeof(UndoRedoTransaction).Equals(undoDataType)) { StartTransaction(oUndoData as UndoRedoTransaction); } undoDataType.InvokeMember("Execute", BindingFlags.InvokeMethod, null, oUndoData, null); } catch (Exception ex) { Logger.LogWarning(ex.Message); } finally { m_RedoGoingOn = false; EndTransaction(m_CurTran); FireRedoStackStatusChanged(); } }
// ---------[ IPlatformIO Interface ]--------- // --- File I/O --- /// <summary>Reads a file.</summary> public virtual bool ReadFile(string path, out byte[] data) { Debug.Assert(!string.IsNullOrEmpty(path)); if (!File.Exists(path)) { data = null; return(false); } try { data = File.ReadAllBytes(path); return(true); } catch (Exception e) { string warningInfo = ("[mod.io] Failed to read file.\nFile: " + path + "\n\n"); Debug.LogWarning(warningInfo + Utility.GenerateExceptionDebugString(e)); data = null; return(false); } }
public static void HardReset() { string result = GitCommand.RunGitCommand(@"reset --hard"); Debug.LogWarning("Hard Resetting: \n" + result); AssetDatabase.Refresh(); }
public static void Process() { if (Actions.Count == 0) { return; } for (var i = Actions.Count - 1; i >= 0; i--) { Record(Actions[i].Recordable, Actions[i].Reason); try { Debug.Log("[MSS] [Editor] [Actions] Do: " + Actions[i].Reason); Actions[i].Action.Invoke(); } catch { Debug.LogWarning("[MSS] [Editor] [Actions] Something wrong with action: " + Actions[i].Reason); } Debug.Log("[MSS] [Editor] [Actions] Done."); Actions.RemoveAt(i); } }
internal static void CleanUpLogsDirectory() { if (string.IsNullOrEmpty(CharonLogsDirectory) || Directory.Exists(CharonLogsDirectory) == false) { return; } foreach (var logFile in Directory.GetFiles(CharonLogsDirectory)) { if (DateTime.UtcNow - File.GetLastWriteTimeUtc(logFile) > TimeSpan.FromDays(2)) { try { if (Settings.Current.Verbose) { Debug.Log(string.Format("Deleting old log file at '{0}'.", logFile)); } File.Delete(logFile); } catch (Exception deleteError) { if (Settings.Current.Verbose) { Debug.LogWarning(string.Format("Failed to delete log file at '{0}'.", logFile)); Debug.LogWarning(deleteError); } } } } }
public static void LogStuckDependers() { if (awaitingDependers.Any()) { var message = awaitingDependers.Count + " awaiting dependers: \n"; foreach (var depender in awaitingDependers) { HashSet <object> missingDependencies = new HashSet <object>(); foreach (var requiredDependency in depender.deserializationDependencies) { var weakRequiredDependency = WeakenSerializationDependencyReference(requiredDependency); if (!availableDependencies.Contains(weakRequiredDependency)) { missingDependencies.Add(requiredDependency); break; } } message += $"{depender} is missing {missingDependencies.ToCommaSeparatedString()}\n"; } Debug.LogWarning(message); } else { Debug.Log("No stuck awaiting depender."); } }
/// <summary> /// Attempts to resolve the type using a the <see cref="System.Type.AssemblyQualifiedName"/> or <see cref="Type.GUID"/> as <see cref="string"/>. /// </summary> /// <param name="typeRef">The <see cref="Type.GUID"/> or <see cref="System.Type.AssemblyQualifiedName"/> as <see cref="string"/>.</param> /// <param name="resolvedType">The resolved <see cref="Type"/>.</param> /// <returns>True if the <see cref="resolvedType"/> was successfully obtained from or added to the <see cref="TypeCache"/>, otherwise false.</returns> public static bool TryResolveType(string typeRef, out Type resolvedType) { resolvedType = null; if (string.IsNullOrEmpty(typeRef)) { return(false); } if (Guid.TryParse(typeRef, out var guid)) { return(TryResolveType(guid, out resolvedType)); } resolvedType = Type.GetType(typeRef); if (resolvedType != null) { if (resolvedType.GUID != Guid.Empty) { return(TryResolveType(guid, out resolvedType)); } if (!resolvedType.IsAbstract) { Debug.LogWarning($"{resolvedType.Name} is missing a {nameof(GuidAttribute)}. This extension has been upgraded to use System.Type.GUID instead of System.Type.AssemblyQualifiedName"); return(true); } } return(false); }
public static void DeserializeInto(this SerializationData data, ref object instance, bool forceReflected = false) { try { if (string.IsNullOrEmpty(data.json)) { instance = null; return; } #if DEBUG_SERIALIZATION Debug.Log(data.ToString($"<color=#3388FF>Deserializing into: <b>{instance?.GetType().Name ?? "null"} [{instance?.GetHashCode().ToString() ?? "N/A"}]</b></color>")); #endif var operation = StartOperation(); operation.objectReferences.AddRange(data.objectReferences); DeserializeJson(operation.serializer, data.json, ref instance, forceReflected); EndOperation(operation); } catch (Exception ex) { try { Debug.LogWarning(data.ToString("Deserialization Failure Data"), instance as UnityObject); } catch (Exception ex2) { Debug.LogWarning("Failed to log deserialization failure data:\n" + ex2, instance as UnityObject); } throw new SerializationException($"Deserialization into '{instance?.GetType().ToString() ?? "null"}' failed.", ex); } }
public static void CopyExecutable(string destinationDirectory) { try { // TODO: Fix the directory once the project in build automatically - Risul Debug.Log($"[{nameof(DecompressorExecutableManager)}] - Saving exe files to directory {destinationDirectory}"); Process.Start(destinationDirectory); var sourceDirectoryPath = Path.Combine("vdt_Data", "Tools", "ImageSegmentationDecompressor"); if (Directory.Exists(sourceDirectoryPath) == false) { Debug.LogWarning($"[{nameof(DecompressorExecutableManager)}] - The Folder for Decompressor is not created yet. Run Build Script to create Decompressor"); return; } var sourceFilePaths = Directory.GetFiles(sourceDirectoryPath); foreach (var sourceFilePath in sourceFilePaths) { var fileName = Path.GetFileName(sourceFilePath); var destinationFilePath = Path.Combine(destinationDirectory, fileName); File.Copy(sourceFilePath, destinationFilePath); } Process.Start(destinationDirectory); RunExeFile(destinationDirectory); } catch (Exception e) { Debug.Log($"[{nameof(DecompressorExecutableManager)}] - Exception occured during copying Decompressor file {e.StackTrace}"); throw; } }
internal void CheckMissingDependenciesForCollections(SubSystemBase sys) { if (m_collectionDependencies.Count > 0) { Debug.LogWarning( $"{sys} finished its update but there are ICollectionComponent instances, one of which was of type {m_collectionDependencies[0].type}, that were accessed but did not have their dependencies updated."); } }
public static void Warning(object a_Message) { #if !UNITY_5_3_OR_NEWER && DEBUG Console.WriteLine(a_Message + "..."); #elif UNITY_5_3_OR_NEWER && DEBUG UnityDebug.LogWarning(a_Message + "..."); #endif }
public void Warn(object message) { if (!IsWarnEnabled) { return; } Debugger.LogWarning(Tag + message); }