Exemple #1
0
        /// <summary>
        /// Returns files in a specfied directory
        /// </summary>
        /// <param name="foldername"></param>
        /// <param name="searchPattern"></param>
        /// <returns></returns>
        public string[] GetFiles(string foldername, string searchPattern)
        {
            bool folderExists = DirectoryExists(foldername);

            if (!folderExists)
            {
                throw new InvalidFilePathException(foldername);
            }

            List <string> files = new List <string>();

            if (Directory.Exists(foldername))
            {
                Logger.Log(LogType.Log, foldername + " Found in File System.", 5);
                files = Directory.GetFiles(foldername, searchPattern).ToList();
            }

            if (ManifestReader.DirectoryExists(foldername))
            {
                Logger.Log(LogType.Log, foldername + " Found in Assembly Manifest.", 5);
                files.AddRange(ManifestReader.GetFiles(foldername, searchPattern /*.Replace("*", "")*/));
            }

            return(files.ToArray());
        }
Exemple #2
0
        /// <summary>
        ///     Reads a config of type T from file.
        /// </summary>
        /// <typeparam name="T">Type of Config</typeparam>
        /// <param name="path">Path to config</param>
        /// <returns>Deserialized Config File.</returns>
        public static T ReadFromFile <T>(string path) where T : AbstractADLConfig
        {
            T             ret;
            XmlSerializer Serializer = new XmlSerializer(typeof(T));

            if (!File.Exists(path))
            {
                Logger.Log(LogType.Warning, "Config Manager: File" + path + "does not exist", 1);
                return(GetDefault <T>());
            }

            try
            {
                Stream fs = IOManager.GetStream(path);
                ret = (T)Serializer.Deserialize(fs);
                fs.Close();
            }
            catch (Exception)
            {
                ret = GetDefault <T>();
                Logger.Log(
                    LogType.Warning,
                    "Config Manager: Failed to deserialize XML file. Either XML file is corrupted or file access is denied.",
                    1
                    );
            }

            return(ret);
        }
Exemple #3
0
 /// <summary>
 /// Logs all Files to the Console
 /// </summary>
 public static void ListAllFiles()
 {
     foreach (KeyValuePair <string, AssemblyFile> assemblyFile in _assemblyFiles)
     {
         Logger.Log(LogType.Log, assemblyFile.Key, 10);
     }
 }
Exemple #4
0
        public static string BuildProject(
            string msbuildCommand, string projectFile, AssemblyDefinition definitions,
            bool lib = true)
        {
            Logger.Log(LogType.Log, "Building Assembly: " + definitions.AssemblyName, 1);
            string arguments = $"-c {definitions.BuildConfiguration}";

            if (!definitions.NoTargetRuntime)
            {
                arguments = $"--runtime {definitions.BuildTargetRuntime} {arguments}";
            }

            string workingDir = Path.GetDirectoryName(projectFile);

            DotnetAction(msbuildCommand, "build", arguments, workingDir);
            string ret = Path.Combine(
                workingDir,
                "bin",
                definitions.BuildConfiguration,
                lib ? "netstandard2.0" : "netcoreapp2.2"
                );

            if (!definitions.NoTargetRuntime)
            {
                ret = Path.Combine(ret, definitions.BuildTargetRuntime);
            }

            return(ret);
        }
Exemple #5
0
        /// <summary>
        /// Manually adds a Program to the database
        /// </summary>
        /// <param name="instance">CLAPI Instance for the current thread</param>
        /// <param name="file">Path fo the file</param>
        public void AddProgram(CLAPI instance, string file)
        {
            if (!CLAPI.FileExists(file))
            {
                throw new Exception(file);
            }


            string path = Path.GetFullPath(file);

            logger.Log(LogType.Log, "Creating CLProgram from file: " + file);
            CLProgram program = new CLProgram(instance, path, GenDataType);

            foreach (KeyValuePair <string, CLKernel> containedKernel in program.ContainedKernels)
            {
                if (!LoadedKernels.ContainsKey(containedKernel.Key))
                {
                    logger.Log(LogType.Log, "Adding Kernel: " + containedKernel.Key);
                    LoadedKernels.Add(containedKernel.Key, containedKernel.Value);
                }
                else
                {
                    logger.Log(LogType.Log,
                               "Kernel with name: " + containedKernel.Key + " is already loaded. Skipping...");
                }
            }
        }
Exemple #6
0
        /// <summary>
        ///     Removes all the excess spaces around the specified separator
        /// </summary>
        /// <param name="line">The line to operate on</param>
        /// <param name="separator">the separator to be used</param>
        /// <param name="logobj">The object from where all resulting logs come from</param>
        /// <returns>the fixed line without any excess spaces</returns>
        public static string RemoveExcessSpaces(string line, string separator)
        {
            string ret = line.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries).Unpack(separator);

            Logger.Log(LogType.Log, $"Removing Excess Spaces: {line} => {ret}", 7);

            return(ret);
        }
Exemple #7
0
        /// <summary>
        /// Adds an Assemblys Commands
        /// </summary>
        /// <param name="asm">Assembly to Add</param>
        public static void AddAssembly(Assembly asm)
        {
            List <AbstractCommand> cmds = AssemblyHelper.LoadCommandsFromAssembly(asm);

            for (int i = 0; i < cmds.Count; i++)
            {
                Logger.Log(LogType.Log, "Adding Command: " + cmds[i].GetType().FullName);
                AddCommand(cmds[i]);
            }
        }
Exemple #8
0
        /// <summary>
        /// Public constructor that is loading every font in the specified folder
        /// </summary>
        /// <param name="folderPath">the specified folder</param>
        public FontLibrary(string folderPath)
        {
            fonts = new Dictionary <string, Tuple <string, GameFont> >();
            List <string> files = new List <string>();

            files.AddRange(IOManager.GetFiles(folderPath, "*.ttf"));

            foreach (string file in files)
            {
                Logger.Log(DebugChannel.Log, "Loading Font: " + file, 10);
                LoadFont(file);
            }
        }
Exemple #9
0
        /// <summary>
        /// Converts an assimp scene to a list of game meshes
        /// </summary>
        /// <param name="s">The scene</param>
        /// <param name="path">Path to the object that was loaded by assimp</param>
        /// <returns></returns>
        internal static List <Mesh> LoadAssimpScene(Scene s, string path, object handleIdentifier)
        {
            if (s == null || (s.SceneFlags & SceneFlags.Incomplete) != 0 || s.RootNode == null)
            {
                Logger.Crash(new InvalidFolderPathException(path), true);
                return(new List <Mesh>());
            }

            string directory = Path.GetDirectoryName(path);

            if (directory == string.Empty)
            {
                directory = ".";
            }


            Logger.Log(DebugChannel.Log | DebugChannel.EngineIO, "Loading Assimp Scene Finished.", 5);

            Logger.Log(DebugChannel.Log | DebugChannel.EngineIO, "Processing Nodes...", 6);

            List <Mesh> ret = new List <Mesh>();

            processNode(s.RootNode, s, ret, directory, handleIdentifier);
            return(ret);
        }
Exemple #10
0
        public override bool Run(string[] args)
        {
            Byt3.ADL.Debug.DefaultInitialization();
            EmbeddedFileIOManager.Initialize();

            OpenFLDebugConfig.Settings.MinSeverity = Verbosity.Level3;

            ManifestReader.RegisterAssembly(Assembly
                                            .GetExecutingAssembly());            //Register this assembly(where the files will be embedded in)
            ManifestReader.RegisterAssembly(typeof(OpenFLDebugConfig).Assembly); //Register the OpenFL.Common Assembly as it contains the CL kernels
            ManifestReader.PrepareManifestFiles(false);                          //First Read Assembly files
            ManifestReader
            .PrepareManifestFiles(true);                                         //Replace Any Loaded assembly files with files on the file system.


            if (IOManager.FileExists("assemblyList.txt")) //Alternative, load assembly list to register from text file.
            {
                Logger.Log(DebugChannel.Log, "Loading Assembly List", 1);

                ManifestReader.LoadAssemblyListFromFile("assemblyList.txt");
            }


            GameEngine engine = new GameEngine(EngineSettings.DefaultSettings);

            engine.Initialize();
            engine.InitializeScene <HoBMenuScene>();
            engine.Run();
            engine.Dispose();

            HandleBase.DisposeAllHandles();
            EngineStatisticsManager.DisposeAllHandles();

            return(true);
        }
Exemple #11
0
        public override bool Run(string[] args)
        {
            ADL.Debug.DefaultInitialization();
            EmbeddedFileIOManager.Initialize();

            ManifestReader.RegisterAssembly(Assembly
                                            .GetExecutingAssembly()); //Register this assembly(where the files will be embedded in)
            ManifestReader.PrepareManifestFiles(false);               //First Read Assembly files
            ManifestReader
            .PrepareManifestFiles(true);                              //Replace Any Loaded assembly files with files on the file system.


            if (IOManager.FileExists("assemblyList.txt")) //Alternative, load assembly list to register from text file.
            {
                Logger.Log(DebugChannel.Log, "Loading Assembly List", 1);

                ManifestReader.LoadAssemblyListFromFile("assemblyList.txt");
            }


            GameEngine engine = new GameEngine(EngineSettings.DefaultSettings);

            engine.Initialize();
            engine.InitializeScene <PhysicsDemoScene>();
            engine.Run();
            engine.Dispose();

            HandleBase.DisposeAllHandles();
            EngineStatisticsManager.DisposeAllHandles();

            return(true);
        }
Exemple #12
0
        public static void Log(Exception exception, bool includeInner)
        {
            if (!initialized)
            {
                CrashLogger.Log(CrashLogType.Error, "Crash handler was not initialized", 1);
                return;
            }

            if (Config.ShortenCrashInfo)
            {
                CrashLogger.Log(CrashLogType.CrashShort, ExceptionHeader(exception), 1);
            }
            else
            {
                CrashLogger.Log(CrashLogType.Crash, ExceptionToString(exception, includeInner), 1);
            }
        }
Exemple #13
0
        public static void RunCommand(CommandInfo commandInfo)
        {
            ProcessStartInfo info;

            if (commandInfo.UseShell)
            {
                info = new ProcessStartInfo(ShellCommand, GetShellArgs(commandInfo.Command));
            }
            else
            {
                info = new ProcessStartInfo(commandInfo.Command);
            }

            info.WorkingDirectory       = commandInfo.WorkingDirectory;
            info.RedirectStandardOutput = commandInfo.CaptureConsoleOut;
            info.RedirectStandardError  = commandInfo.CaptureConsoleOut;
            info.UseShellExecute        = !commandInfo.CaptureConsoleOut;
            info.CreateNoWindow         = !commandInfo.CreateWindow;
            Process p = Process.Start(info);

            p.EnableRaisingEvents = true;
            p.Exited += (sender, args) => ProcessExited(p);

            if (commandInfo.CaptureConsoleOut)
            {
                if (commandInfo.OnOutputReceived != null)
                {
                    p.OutputDataReceived += commandInfo.OnOutputReceived;
                }

                if (commandInfo.OnErrorReceived != null)
                {
                    p.ErrorDataReceived += commandInfo.OnErrorReceived;
                }
            }

            p.BeginErrorReadLine();
            p.BeginOutputReadLine();

            if (!commandInfo.WaitForExit)
            {
                return;
            }

            if (commandInfo.WaitForExitTimeout == -1)
            {
                p.WaitForExit();
            }
            else
            {
                p.WaitForExit(commandInfo.WaitForExitTimeout);
                if (!p.HasExited)
                {
                    Logger.Log(LogType.Warning, $"Command \"{commandInfo.Command}\" Timed Out", 1);
                    p.Kill();
                }
            }
        }
Exemple #14
0
        public override SerializableFLProgram Process(StaticInspectionResult input)
        {
            Logger.Log(LogType.Log, "Parsing Tree: " + input.Filename, 1);
            Logger.Log(LogType.Log, "Creating Defined Script Nodes..", 2);
            List <SerializableExternalFLFunction> scripts = ParseScriptDefines(input.DefinedScripts);

            Logger.Log(LogType.Log, "Script Nodes: " + scripts.Select(x => x.Name).Unpack(", "), 4);


            Logger.Log(LogType.Log, "Creating Defined Buffer Nodes..", 2);
            List <SerializableFLBuffer> definedBuffers = ParseDefinedBuffers(input.DefinedBuffers);

            Logger.Log(LogType.Log, "Buffer Nodes: " + definedBuffers.Select(x => x.Name).Unpack(", "), 4);

            Logger.Log(LogType.Log, "Creating Defined Function Nodes..", 2);
            List <SerializableFLFunction> flFunctions =
                ParseFunctions(input.Functions, input.DefinedBuffers, input.DefinedScripts);

            Logger.Log(LogType.Log, "Buffer Nodes: " + flFunctions.Select(x => x.Name).Unpack(", "), 4);
            SerializableFLProgram prog =
                new SerializableFLProgram(input.Filename, scripts, flFunctions, definedBuffers);

            prog.KernelData.AddRange(input.KernelData);
            return(prog);
        }
Exemple #15
0
        /// <summary>
        /// Removes all lines of the source that start with one of the statements
        /// It takes care of possible indentations and spaces
        /// </summary>
        /// <param name="source">the input source</param>
        /// <param name="statements">statements that need to be removed from the source</param>
        /// <returns>the cleaned list of source code lines</returns>
        public static List <string> RemoveStatements(List <string> source, string[] statements)
        {
            for (int i = source.Count - 1; i >= 0; i--)
            {
                foreach (string t in statements)
                {
                    if (source[i].Trim().StartsWith(t))
                    {
                        Logger.Log(LogType.Log,
                                   string.Format("Removing statement {0} on line {1}", t, i), 7);
                        source.RemoveAt(i);
                        break;
                    }
                }
            }

            return(source);
        }
        public override bool Run(string[] args)
        {
            EmbeddedFileIOManager.Initialize();
            ManifestReader.RegisterAssembly(typeof(FLScriptGenerator).Assembly);
            ManifestReader.PrepareManifestFiles(false);

            Runner.AddCommand(new HelpCommand(new DefaultHelpCommand(true)));
            Runner.AddCommand(SetSettingsCommand.CreateSettingsCommand("Settings", Settings));

            Runner.RunCommands(args);

            if (!DoExecute)
            {
                return(true);
            }

            Debug.DefaultInitialization();

            ManifestReader.RegisterAssembly(Assembly.GetExecutingAssembly());
            ManifestReader.PrepareManifestFiles(false);

            ExtPPDebugConfig.Settings.MinSeverity  = Verbosity.Silent;
            OpenFLDebugConfig.Settings.MinSeverity = Verbosity.Level1;
            OpenCLDebugConfig.Settings.MinSeverity = Verbosity.Silent;

            Directory.CreateDirectory(Settings.OutputFolder);
            Random rnd = new Random();

            for (int i = 0; i < Settings.Amount; i++)
            {
                string file = Path.Combine(Settings.OutputFolder, "genscript." + i + ".fl");
                Logger.Log(LogType.Log, "Generating Script...", 1);
                string script = FLScriptGenerator.GenerateRandomScript(
                    rnd.Next(Settings.Functions.Min, Settings.Functions.Max),
                    rnd.Next(Settings.Buffers.Min, Settings.Buffers.Max),
                    rnd.Next(Settings.Additional.Min, Settings.Additional.Max),
                    rnd.Next(Settings.AdditionalFunctions.Min, Settings.AdditionalFunctions.Max));
                Logger.Log(LogType.Log, "Finished Script. Lines: " + script.Count(x => x == '\n'), 1);
                File.WriteAllText(file, script);
            }

            return(true);
        }
        public override StaticInspectionResult Process(LoadSourceStageResult input)
        {
            string[] definedScripts         = null;
            string[] definedBuffers         = null;
            List <StaticFunction> functions = null;


            Logger.Log(LogType.Log, "Statically Inspecting: " + input.Filename, 2);

            Task <string[]> scriptTask = new Task <string[]>(() => FLParser.FindDefineScriptsStatements(input.Source));
            Task <string[]> bufferTask = new Task <string[]>(() => FLParser.FindDefineStatements(input.Source));

            if (parser.WorkItemRunnerSettings.UseMultithread)
            {
                scriptTask.Start();
                bufferTask.Start();
            }
            else
            {
                scriptTask.RunSynchronously();
                bufferTask.RunSynchronously();
            }

            string[] functionsHeaders = FLParser.FindFunctionHeaders(input.Source);

            functions = WorkItemRunner.RunInWorkItems(functionsHeaders.ToList(),
                                                      (list, start, count) => ParseFunctionTask(list, start, count, input.Source),
                                                      parser.WorkItemRunnerSettings);


            Task.WaitAll(scriptTask, bufferTask);
            Logger.Log(LogType.Log, "Buffer And Script Task Finished.", 2);
            definedScripts = scriptTask.Result;
            definedBuffers = bufferTask.Result;


            Logger.Log(LogType.Log, "Tasks Completed.", 2);


            Logger.Log(LogType.Log, "Parsed Scripts: " + functions.Unpack(", "), 4);
            return(new StaticInspectionResult(input.Filename, input.Source, functions, definedBuffers,
                                              definedScripts));
        }
Exemple #18
0
        public void ADL_Debug_Log_Test()
        {
            LogTextStream lts = new LogTextStream(new PipeStream())
            {
                AddTimeStamp = false
            };


            Debug.PrefixLookupMode = PrefixLookupSettings.Noprefix;
            Assert.True(Debug.PrefixLookupMode == PrefixLookupSettings.Noprefix);


            ADLLogger logger = new ADLLogger("UnitTest");


            Debug.AddOutputStream(lts);
            logger.Log(1, "ffffffffff");

            byte[] buf = new byte[lts.Length];
            lts.Read(buf, 0, buf.Length);
            string s = Debug.TextEncoding.GetString(buf);

            Assert.EndsWith("ffffffffff\n", s); //ADL is appending the \n when using LogTextStreams


            logger.Log(1, "ffffffffff");
            Debug.AdlEnabled = false;
            logger.Log(1, "ffffffffff");
            Debug.AdlEnabled = true;
            buf = new byte[lts.Length];
            lts.Read(buf, 0, buf.Length);
            s = Debug.TextEncoding.GetString(buf);

            Assert.EndsWith("ffffffffff\n", s);


            Debug.PrefixLookupMode = PrefixLookupSettings.Addprefixifavailable | PrefixLookupSettings.Bakeprefixes;

            logger.Log(2 | 4, "CODE COVERAGE");
            logger.Log(2 | 4, "CODE COVERAGE");
        }
Exemple #19
0
        public override LoadSourceStageResult Process(LoadSourceStageResult input)
        {
            Logger.Log(LogType.Log, "Removing Comments.. ", 2);


            WorkItemRunner.RunInWorkItems(input.Source, RemoveCommentTask, parser.WorkItemRunnerSettings);


            Logger.Log(LogType.Log, $"Optimizing Script Length..", 2);
            for (int i = input.Source.Count - 1; i >= 0; i--)
            {
                if (string.IsNullOrWhiteSpace(input.Source[i]))
                {
                    input.Source.RemoveAt(i);
                    continue;
                }

                input.Source[i] = input.Source[i].Trim();
            }

            return(input);
        }
Exemple #20
0
        /// <summary>
        /// Tries to Create a Shader from source
        /// </summary>
        /// <param name="subshaders">Dictionary of ShaderType, Path To File</param>
        /// <param name="program">Resulting Shader Program</param>
        /// <returns>The Success State of the Compilation</returns>
        internal static bool TryCreateFromSource(Dictionary <ShaderType, string> subshaders, out ShaderProgram program)
        {
            bool ret = true;

            program = new ShaderProgram();
            List <int> shaders = new List <int>();

            foreach (KeyValuePair <ShaderType, string> shader in subshaders)
            {
                Logger.Log(DebugChannel.Log | DebugChannel.EngineRendering, "Compiling Shader: " + shader.Key, 5);

                bool r = TryCompileShader(shader.Key, shader.Value, out int id);
                ret &= r;
                if (r)
                {
                    shaders.Add(id);
                }
            }


            for (int i = 0; i < shaders.Count; i++)
            {
                Logger.Log(DebugChannel.Log | DebugChannel.EngineRendering,
                           "Attaching Shader to Program: " + subshaders.ElementAt(i).Key, 6);
                GL.AttachShader(program.prgId, shaders[i]);
            }

            Logger.Log(DebugChannel.Log | DebugChannel.EngineRendering, "Linking Program...", 5);
            GL.LinkProgram(program.prgId);

            GL.GetProgram(program.prgId, GetProgramParameterName.LinkStatus, out int success);
            if (success == 0)
            {
                Logger.Crash(new OpenGLShaderException(GL.GetProgramInfoLog(program.prgId)), true);
                return(false);
            }

            return(ret);
        }
Exemple #21
0
        public void ADL_Debug_Log_Test()
        {
            LogTextStream lts = new LogTextStream(new PipeStream())
            {
                AddTimeStamp = false
            };


            Debug.PrefixLookupMode = PrefixLookupSettings.NoPrefix;
            Assert.True(Debug.PrefixLookupMode == PrefixLookupSettings.NoPrefix);


            ADLLogger logger = new ADLLogger(InternalADLProjectDebugConfig.Settings, "UnitTest");


            Debug.AddOutputStream(lts);
            logger.Log(1, "ffffffffff", 0);

            byte[] buf = new byte[lts.Length];
            lts.Read(buf, 0, buf.Length);
            string s = Debug.TextEncoding.GetString(buf);

            Assert.True(s.EndsWith("ffffffffff\n")); //ADL is appending the \n when using LogTextStreams


            logger.Log(1, "ffffffffff", 0);
            buf = new byte[lts.Length];
            lts.Read(buf, 0, buf.Length);
            s = Debug.TextEncoding.GetString(buf);

            Assert.True(s.EndsWith("ffffffffff\n"));


            Debug.PrefixLookupMode = PrefixLookupSettings.AddPrefixIfAvailable | PrefixLookupSettings.BakePrefixes;

            logger.Log(2 | 4, "CODE COVERAGE", 0);
            logger.Log(2 | 4, "CODE COVERAGE", 0);
        }
        internal static string[] PreprocessLines(IFileContent file, Dictionary <string, bool> defs)
        {
            string ext = new string(file.GetFilePath().Reverse().Take(3).Reverse().ToArray());
            string key = "";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                key = "WIN";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                key = "OSX";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                key = "LINUX";
            }

            if (defs == null)
            {
                defs = new Dictionary <string, bool>();
            }
            if (!defs.ContainsKey(key))
            {
                defs.Add(key, true);
            }

            if (Configs.ContainsKey(ext))
            {
                Logger.Log(DebugChannel.Log, "Found Matching PreProcessor Config for: " + ext);
                return(Configs[ext].Preprocess(file, defs));
            }

            Logger.Log(DebugChannel.Log, "Loading File with Default PreProcessing");
            return(Configs["***"].Preprocess(file, defs));
        }
Exemple #23
0
        /// <summary>
        /// Loads Textures from AssimpMaterials
        /// </summary>
        /// <param name="m">Assimp Material</param>
        /// <param name="texType">Type of texture</param>
        /// <param name="dir">The directory of the file that references this material</param>
        /// <returns>A list of textures that were attached to the material</returns>
        internal static List <Texture> LoadMaterialTextures(Material m, TextureType texType, string dir)
        {
            List <Texture> ret = new List <Texture>();

            Logger.Log(DebugChannel.Log | DebugChannel.EngineIO,
                       "Loading Baked Material Textures of type: " + Enum.GetName(typeof(TextureType), texType),
                       1);
            for (int i = 0; i < m.GetMaterialTextureCount((Assimp.TextureType)texType); i++)
            {
                m.GetMaterialTexture((Assimp.TextureType)texType, i, out TextureSlot s);
                Texture tx = FileToTexture(dir + s.FilePath);
                tx.TexType = texType;
                ret.Add(tx);
            }

            return(ret);
        }
Exemple #24
0
        /// <summary>
        /// Takes an object from the pool.
        /// if the pool has no free objects and it as maximum capacity it will log a warning and return unmanaged instances
        /// </summary>
        /// <returns>An object</returns>
        public PooledObject <T> Take()
        {
            int id = GetFreeId();

            if (id == -1)
            {
                Logger.Log(DebugChannel.Warning | DebugChannel.EngineCore,
                           "Object Pool is full, returning Unmanaged Instance.",
                           10);
                PooledObject <T> item = new PooledObject <T>(factory(), null, -1);

                return(item);
            }

            internalList[id].SetIsUsed(true);
            return(internalList[id]);
        }
Exemple #25
0
        public static List <Out> RunInWorkItems <In, Out>(List <In> input, RunWorkItemDel <In, Out> action,
                                                          WorkItemRunnerSettings settings)
        {
            List <Task <List <Out> > > taskList = new List <Task <List <Out> > >();
            int workSize  = settings.GetOptimalWorkSize(input.Count);
            int currentID = 0;
            int taskNr    = 0;
            int maxTasks  = input.Count / workSize;

            Logger.Log(LogType.Log, $"Starting {maxTasks} Tasks...", 2);
            while (currentID != input.Count)
            {
                int len = Math.Min(workSize, input.Count - currentID);
                int id  = currentID;
                int nr  = taskNr;
                Task <List <Out> > task = new Task <List <Out> >(() => action(input, id, len));
                task.ContinueWith(t => Logger.Log(LogType.Log, "Task " + nr + " of " + maxTasks + " completed.", 2));

                taskList.Add(task);
                if (settings.UseMultithread)
                {
                    task.Start();
                }
                else
                {
                    task.RunSynchronously();
                }

                currentID += len;
                taskNr++;
            }

            Logger.Log(LogType.Log, $"Waiting for Tasks..", 2);
            Task.WaitAll(taskList.ToArray());

            List <Out> ret       = new List <Out>(input.Count);
            int        nextIndex = 0;

            for (int i = 0; i < taskList.Count; i++)
            {
                ret.AddRange(taskList[i].Result);
            }

            return(ret);
        }
Exemple #26
0
        public override LoadSourceStageResult Process(FLParserInput input)
        {
            if (input.Source != null)
            {
                return(new LoadSourceStageResult(
                           input.Filename,
                           input.Source.ToList(),
                           input.MainFile,
                           input.KernelData
                           ));
            }

            Logger.Log(LogType.Log, "Loading Source: " + input.Filename, 1);

            Dictionary <string, bool> defines = input.Defines;


            return(new LoadSourceStageResult(
                       input.Filename,
                       TextProcessorAPI.PreprocessLines(input.Filename, defines).ToList(),
                       input.MainFile,
                       input.KernelData
                       ));
        }
Exemple #27
0
        public override bool Run(string[] args)

        {
            Debug.DefaultInitialization();

            Runner.AddCommand(new DefaultHelpCommand(true));
            Runner.AddCommand(new ExitAfterFlagCommand());
            Runner.AddCommand(new EngineTimeoutFlagCommand());
            Runner.AddCommand(new EngineSceneRunCommand());

            Logger.Log(LogType.Log, "exit = Exit Current Shell", 1);


            if (args.Length != 0)
            {
                Runner.RunCommands(args);
                if (Exit)
                {
                    return(true);
                }
            }

            while (true)
            {
                Console.Write("root/testing>");
                string command = Console.ReadLine();
                if (command == "exit")
                {
                    break;
                }

                Runner.RunCommands(command.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
            }

            return(true);
        }
        public static void InitializePluginSystem()
        {
            loaderForm.TopMost           = false;
            PluginManager.OnLog         += args => pluginLogger.Log(LogType.Log, args.Message, 1);
            PluginManager.OnLog         += PluginManagerLoadLog;
            PluginManager.OnInitialized += PluginManagerOnOnInitialized;
            PluginManager.Initialize(
                Path.Combine(PluginPaths.EntryDirectory, "data"),
                "internal",
                "plugins",
                (msg, title) =>
                StyledMessageBox.Show(
                    title,
                    msg,
                    MessageBoxButtons.YesNo,
                    SystemIcons.Question
                    ) ==
                DialogResult.Yes,
                SetProgress,
                Path.Combine(PluginPaths.EntryDirectory, "static-data.sd")
                );

            loaderForm.TopMost = true;
        }
Exemple #29
0
        public override bool Run(string[] args)
        {
            ADL.Debug.DefaultInitialization();
            EmbeddedFileIOManager.Initialize();

            ManifestReader.RegisterAssembly(Assembly
                                            .GetExecutingAssembly()); //Register this assembly(where the files will be embedded in)
            ManifestReader.PrepareManifestFiles(false);               //First Read Assembly files
            ManifestReader
            .PrepareManifestFiles(true);                              //Replace Any Loaded assembly files with files on the file system.

            ge = new GameEngine(EngineSettings.DefaultSettings);


            Logger.Log(LogType.Log, "\"exit\" closes the Console.", 1);
            Logger.Log(LogType.Log, "\"nameofdemo\" Opens the selected Demo.", 1);
            ListSceneNames();
            if (args.Length != 0)
            {
                RunCommand(args);
            }

            while (true)
            {
                Console.Write("engine/demos>");
                string format = Console.ReadLine();
                if (format == "exit")
                {
                    break;
                }

                string[] arg = format.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                RunCommand(arg);
            }

            return(true);
        }
Exemple #30
0
        public static string RunParsedFLExecutionBenchmark(bool warm, string testAdd, List <string> files,
                                                           int iterations,
                                                           string performanceFolder = "performance", Type[] checkPipeline = null, bool useMultiThreading = false,
                                                           int workSizeMultiplier   = 2)
        {
            FLSetup setup = new FLSetup("FL_ParsedExecution_Performance" + testAdd, "resources/kernel", performanceFolder,
                                        checkPipeline, useMultiThreading, workSizeMultiplier);
            StringBuilder logOut = new StringBuilder($"Performance Tests: {DateTime.Now:HH:mm:ss}\n");

            for (int i = 0; i < files.Count; i++)
            {
                Logger.Log(LogType.Log, "Running Script: " + files[i], 1);
                Bitmap   bmp = null;
                FLBuffer buf = null;
                SerializableFLProgram parsedProgram = null;
                FLProgram             program       = null;

                string key = "FLParsedExecutionPerformance+" + Path.GetFileNameWithoutExtension(files[i]) + "." + i;

                Logger.Log(LogType.Log, $"------------------------Run {key} Starting------------------------", 1);

                parsedProgram = setup.Parser.Process(new FLParserInput(files[i]));

                PerformanceTester.PerformanceResult result = PerformanceTester.Tester.RunTest(key, iterations,
                                                                                              (int its) => //BeforeTest
                {
                    bmp     = new Bitmap(BITMAP_RESOLUTION, BITMAP_RESOLUTION);
                    buf     = new FLBuffer(CLAPI.MainThread, bmp, files[i]);
                    program = parsedProgram.Initialize(setup.InstructionSet);
                    if (warm)
                    {
                        program.SetCLVariablesAndWarm(CLAPI.MainThread, buf, true, warm);
                    }
                },
                                                                                              (int its) => { program.Run(CLAPI.MainThread, buf, true); },
                                                                                              (int its) => //After Test
                {
                    Logger.Log(LogType.Log, "------------------------Run Finished------------------------", 1);

                    if (its == iterations - 1)
                    {
                        SaveOutput("parsed-output", bmp, program, setup, files[i]);
                    }

                    program.FreeResources();
                    buf.Dispose();
                    bmp.Dispose();
                });
                logOut.AppendLine("\t" + result);

                Logger.Log(LogType.Log, $"------------------------Run {key} Finished------------------------", 1);

                setup.WriteResult(result);
            }


            logOut.AppendLine();
            setup.WriteLog(logOut.ToString());
            setup.Dispose();
            return(logOut.ToString());
        }