Exemple #1
0
 public static RenderPackage? LoadFromXml(ComputeContext computeContext, KernelXmlFile kernelXml, IParameterSet oldParameterSetCache)
 {
     var kernel = RenderKernel.Create(computeContext, kernelXml.Files.Select(File.ReadAllText).ToArray());
     if (kernel == null)
         return null;
     var controls = kernelXml.ControlsFunc();
     if (oldParameterSetCache != null && controls.GetType() == oldParameterSetCache.GetType())
         controls = oldParameterSetCache;
     return new RenderPackage(kernel, controls);
 }
Exemple #2
0
        public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig config, IParameterSet parameters, ParameterSetter setter)
        {
            CoalesceMacroConfig realConfig = config as CoalesceMacroConfig;

            if (realConfig == null)
            {
                throw new InvalidCastException("Unable to cast config as a CoalesceMacroConfig");
            }

            object targetValue = null;

            if (vars.TryGetValue(realConfig.SourceVariableName, out object currentSourceValue) && !Equals(currentSourceValue ?? string.Empty, realConfig.DefaultValue ?? string.Empty))
            {
                targetValue = currentSourceValue;
            }
            else
            {
                if (!vars.TryGetValue(realConfig.FallbackVariableName, out targetValue))
                {
                    environmentSettings.Host.LogDiagnosticMessage("Unable to find a variable to fall back to called " + realConfig.FallbackVariableName, "Authoring", realConfig.SourceVariableName, realConfig.DefaultValue);
                    targetValue = realConfig.DefaultValue;
                }
            }

            Parameter pd = new Parameter
            {
                IsVariable = true,
                Name       = config.VariableName
            };

            vars[config.VariableName] = targetValue?.ToString();
            setter(pd, targetValue?.ToString());
        }
Exemple #3
0
 public InterpolationCrossover(IRandom random, IParameterSet parameterSet, IList <IConflictDetector> conflictDetectors)
     : base(random, parameterSet, conflictDetectors)
 {
 }
Exemple #4
0
        public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
        {
            EvaluateMacroConfig config = rawConfig as EvaluateMacroConfig;

            if (config == null)
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as EvaluateMacroConfig");
            }

            ConditionEvaluator evaluator = EvaluatorSelector.Select(config.Evaluator, Cpp2StyleEvaluatorDefinition.Evaluate);

            byte[]          data   = Encoding.UTF8.GetBytes(config.Value);
            int             len    = data.Length;
            int             pos    = 0;
            IProcessorState state  = new GlobalRunSpec.ProcessorState(environmentSettings, vars, data, Encoding.UTF8);
            bool            result = evaluator(state, ref len, ref pos, out bool faulted);

            Parameter p;

            if (parameters.TryGetParameterDefinition(config.VariableName, out ITemplateParameter existingParam))
            {
                // If there is an existing parameter with this name, it must be reused so it can be referenced by name
                // for other processing, for example: if the parameter had value forms defined for creating variants.
                // When the param already exists, use its definition, but set IsVariable = true for consistency.
                p            = (Parameter)existingParam;
                p.IsVariable = true;
            }
            else
            {
                p = new Parameter
                {
                    IsVariable = true,
                    Name       = config.VariableName
                };
            }

            vars[config.VariableName] = result.ToString();
            setter(p, result.ToString());
        }
Exemple #5
0
        private static IReadOnlyList <IOperationProvider> SetupOperations(IEngineEnvironmentSettings environmentSettings, IParameterSet parameters, IGlobalRunConfig runConfig)
        {
            // default operations
            List <IOperationProvider> operations = new List <IOperationProvider>();

            operations.AddRange(runConfig.Operations);

            // replacements
            if (runConfig.Replacements != null)
            {
                foreach (IReplacementTokens replaceSetup in runConfig.Replacements)
                {
                    IOperationProvider replacement = ReplacementConfig.Setup(environmentSettings, replaceSetup, parameters);
                    if (replacement != null)
                    {
                        operations.Add(replacement);
                    }
                }
            }

            if (runConfig.VariableSetup.Expand)
            {
                operations?.Add(new ExpandVariables(null));
            }

            return(operations);
        }
        // Warning: if there are unknown macro "types", they are quietly ignored here.
        // This applies to both the regular and deferred macros.
        internal IEnumerable <IOperationProvider> ProcessMacros(IEngineEnvironmentSettings environmentSettings, IReadOnlyList <IMacroConfig> macroConfigs, IVariableCollection variables, IParameterSet parameters)
        {
            EnsureMacros(environmentSettings.Components);
            EnsureDeferredMacros(environmentSettings.Components);

            ParameterSetter setter = (p, value) =>
            {
                ((RunnableProjectGenerator.ParameterSet)parameters).AddParameter(p);
                parameters.ResolvedValues[p] = RunnableProjectGenerator.InternalConvertParameterValueToType(environmentSettings, p, value, out bool valueResolutionError);
                // TODO: consider checking the valueResolutionError and act on it, if needed.
                // Should be safe to ignore, params should be verified by the time this occurs.
            };

            IList <IMacroConfig> allMacroConfigs = new List <IMacroConfig>(macroConfigs);
            IList <GeneratedSymbolDeferredMacroConfig> deferredConfigList = new List <GeneratedSymbolDeferredMacroConfig>();

            // run the macros that are already setup, stash the deferred ones for afterwards
            foreach (IMacroConfig config in allMacroConfigs)
            {
                if (config is GeneratedSymbolDeferredMacroConfig deferredConfig)
                {
                    deferredConfigList.Add(deferredConfig);
                    continue;
                }

                if (_macroObjects.TryGetValue(config.Type, out IMacro macroObject))
                {
                    macroObject.EvaluateConfig(environmentSettings, variables, config, parameters, setter);
                }
            }

            List <Tuple <IMacro, IMacroConfig> > deferredConfigs = new List <Tuple <IMacro, IMacroConfig> >();

            // Set up all deferred macro configurations - this must be done separately from running them
            //  as certain generation types may require (like generating port numbers) that a shared resource
            //  be held in a particular state to influence the production of other values
            foreach (GeneratedSymbolDeferredMacroConfig deferredConfig in deferredConfigList)
            {
                IDeferredMacro deferredMacroObject;
                if (_deferredMacroObjects.TryGetValue(deferredConfig.Type, out deferredMacroObject))
                {
                    deferredConfigs.Add(Tuple.Create((IMacro)deferredMacroObject, deferredMacroObject.CreateConfig(environmentSettings, deferredConfig)));
                }
            }

            foreach (Tuple <IMacro, IMacroConfig> config in deferredConfigs)
            {
                config.Item1.EvaluateConfig(environmentSettings, variables, config.Item2, parameters, setter);
            }

            return(Array.Empty <IOperationProvider>());
        }
Exemple #7
0
        public Task <ICreationResult> CreateAsync(IEngineEnvironmentSettings environmentSettings, ITemplate templateData, IParameterSet parameters, IComponentManager componentManager, string targetDirectory)
        {
            RunnableProjectTemplate template = (RunnableProjectTemplate)templateData;

            ProcessMacros(environmentSettings, componentManager, template.Config.OperationConfig, parameters);

            IVariableCollection variables = VariableCollection.SetupVariables(environmentSettings, parameters, template.Config.OperationConfig.VariableSetup);

            template.Config.Evaluate(parameters, variables, template.ConfigFile);

            IOrchestrator basicOrchestrator          = new Core.Util.Orchestrator();
            RunnableProjectOrchestrator orchestrator = new RunnableProjectOrchestrator(basicOrchestrator);

            GlobalRunSpec runSpec = new GlobalRunSpec(template.TemplateSourceRoot, componentManager, parameters, variables, template.Config.OperationConfig, template.Config.SpecialOperationConfig, template.Config.LocalizationOperations, template.Config.PlaceholderFilename);

            foreach (FileSource source in template.Config.Sources)
            {
                runSpec.SetupFileSource(source);
                string target = Path.Combine(targetDirectory, source.Target);
                orchestrator.Run(runSpec, template.TemplateSourceRoot.DirectoryInfo(source.Source), target);
            }

            // todo: add anything else we'd want to report to the broker
            return(Task.FromResult <ICreationResult>(new CreationResult()
            {
                PostActions = PostAction.ListFromModel(environmentSettings, template.Config.PostActionModel, variables),
                PrimaryOutputs = CreationPath.ListFromModel(environmentSettings, template.Config.PrimaryOutputs, variables)
            }));
        }
Exemple #8
0
        public void Render(ComputeBuffer<Vector4> buffer, ComputeCommandQueue queue, IParameterSet parameters,
            Size windowSize, int numBlocks, Size coordinates, int bufferWidth = 0)
        {
            lock (_kernelLock)
            {
                if (_kernel == null)
                    return;

                var size = new long[] { windowSize.Width, windowSize.Height };
                var localSize = Threadsize(queue);

                var offset = new long[size.Length];
                var offsetCoords = new long[] { coordinates.Width, coordinates.Height };

                if (numBlocks > 0)
                {
                    for (var i = 0; i < size.Length; i++)
                        size[i] = numBlocks * localSize[i];
                    for (var i = 0; i < size.Length; i++)
                        offset[i] = size[i] * offsetCoords[i];
                }

                var globalSize = GlobalLaunchsizeFor(localSize, size);

                var kernelNumArgs = 0;
                _kernel.SetMemoryArgument(kernelNumArgs++, buffer);
                _kernel.SetValueArgument(kernelNumArgs++, bufferWidth);
                _kernel.SetValueArgument(kernelNumArgs++, windowSize.Width);
                _kernel.SetValueArgument(kernelNumArgs++, windowSize.Height);
                parameters.ApplyToKernel(_kernel, _useDouble, ref kernelNumArgs);

                queue.Execute(_kernel, offset, globalSize, localSize, null);
            }
        }
Exemple #9
0
        public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
        {
            ConstantMacroConfig config = rawConfig as ConstantMacroConfig;

            if (config == null)
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as ConstantMacroConfig");
            }

            Parameter p;

            if (parameters.TryGetParameterDefinition(config.VariableName, out ITemplateParameter existingParam))
            {
                // If there is an existing parameter with this name, it must be reused so it can be referenced by name
                // for other processing, for example: if the parameter had value forms defined for creating variants.
                // When the param already exists, use its definition, but set IsVariable = true for consistency.
                p            = (Parameter)existingParam;
                p.IsVariable = true;
            }
            else
            {
                p = new Parameter
                {
                    IsVariable = true,
                    Name       = config.VariableName
                };
            }

            vars[config.VariableName] = config.Value;
            setter(p, config.Value);
        }
        public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
        {
            string value;

            if (!(rawConfig is RegexMatchMacroConfig config))
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as RegexMatchMacroConfig");
            }

            if (!vars.TryGetValue(config.SourceVariable, out object working))
            {
                value = parameters.TryGetRuntimeValue(environmentSettings, config.SourceVariable, out object resolvedValue, true)
                    ? resolvedValue.ToString()
                    : string.Empty;
            }
            else
            {
                value = working?.ToString() ?? string.Empty;
            }

            bool result = false;

            try
            {
                result = Regex.IsMatch(value, config.Pattern);
            }
            catch (ArgumentException ex)
            {
                environmentSettings.Host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_InvalidRegex, config.Pattern), "Authoring", ex.ToString());
            }

            Parameter p;

            if (parameters.TryGetParameterDefinition(config.VariableName, out ITemplateParameter existingParam))
            {
                // If there is an existing parameter with this name, it must be reused so it can be referenced by name
                // for other processing, for example: if the parameter had value forms defined for creating variants.
                // When the param already exists, use its definition, but set IsVariable = true for consistency.
                p            = (Parameter)existingParam;
                p.IsVariable = true;

                if (string.IsNullOrEmpty(p.DataType))
                {
                    p.DataType = config.DataType;
                }
            }
            else
            {
                p = new Parameter
                {
                    IsVariable = true,
                    Name       = config.VariableName,
                    DataType   = config.DataType
                };
            }

            vars[config.VariableName] = result;
            setter(p, result.ToString());
        }
Exemple #11
0
        public void Evaluate(string variableName, IVariableCollection vars, JObject def, IParameterSet parameters, ParameterSetter setter)
        {
            string             evaluatorName = def.ToString("evaluator");
            ConditionEvaluator evaluator     = EvaluatorSelector.Select(evaluatorName);

            byte[]          data  = Encoding.UTF8.GetBytes(def.ToString("action"));
            int             len   = data.Length;
            int             pos   = 0;
            IProcessorState state = new GlobalRunSpec.ProcessorState(vars, data, Encoding.UTF8);
            bool            res   = evaluator(state, ref len, ref pos);

            Parameter p = new Parameter
            {
                IsVariable = true,
                Name       = variableName
            };

            setter(p, res.ToString());
        }
 public SwapTwoRangeMutation(IRandom random, IParameterSet parameterSet, IList <INeighborhoodConflictDetector> conflictDetectors)
     : base(random, parameterSet, conflictDetectors)
 {
 }
Exemple #13
0
 public Order1Crossover(IRandom random, IParameterSet parameterSet, IList <IConflictDetector> conflictDetectors = null)
     : base(random, parameterSet, conflictDetectors)
 {
 }
 public EliminateSectionMutation(IRandom random, IParameterSet parameterSet, IList <INeighborhoodConflictDetector> conflictDetectors)
     : base(random, parameterSet, conflictDetectors)
 {
 }
Exemple #15
0
        public IReadOnlyDictionary <string, IReadOnlyList <IFileChange2> > GetFileChanges(string targetBaseDir, IParameterSet parameters = null, IVariableCollection variables = null)
        {
            if (parameters == null)
            {
                parameters = new MockParameterSet();
            }

            if (variables == null)
            {
                variables = new VariableCollection();
            }

            IRunnableProjectConfig runnableConfig = TemplateConfigTestHelpers.ConfigFromSource(_environment, SourceMountPoint);
            IFileSystemInfo        configFileInfo = TemplateConfigTestHelpers.ConfigFileSystemInfo(SourceMountPoint, _configFile);

            runnableConfig.Evaluate(parameters, variables, configFileInfo);

            MockGlobalRunSpec runSpec   = new MockGlobalRunSpec();
            IDirectory        sourceDir = SourceMountPoint.DirectoryInfo("/");

            IOrchestrator basicOrchestrator          = new Core.Util.Orchestrator();
            RunnableProjectOrchestrator orchestrator = new RunnableProjectOrchestrator(basicOrchestrator);

            Dictionary <string, IReadOnlyList <IFileChange2> > changesByTarget = new Dictionary <string, IReadOnlyList <IFileChange2> >();

            foreach (FileSourceMatchInfo source in runnableConfig.Sources)
            {
                TemplateConfigTestHelpers.SetupFileSourceMatchersOnGlobalRunSpec(runSpec, source);
                IReadOnlyList <IFileChange2> changes = orchestrator.GetFileChanges(runSpec, sourceDir, targetBaseDir, source.Target);
                changesByTarget[source.Target] = changes;
            }

            return(changesByTarget);
        }
        public ICreationEffects GetCreationEffects(IEngineEnvironmentSettings environmentSettings, ITemplate templateData, IParameterSet parameters, IComponentManager componentManager, string targetDirectory)
        {
            RunnableProjectTemplate template = (RunnableProjectTemplate)templateData;

            ProcessMacros(environmentSettings, componentManager, template.Config.OperationConfig, parameters);

            IVariableCollection variables = VariableCollection.SetupVariables(environmentSettings, parameters, template.Config.OperationConfig.VariableSetup);

            template.Config.Evaluate(parameters, variables, template.ConfigFile);

            IOrchestrator basicOrchestrator          = new Core.Util.Orchestrator();
            RunnableProjectOrchestrator orchestrator = new RunnableProjectOrchestrator(basicOrchestrator);

            GlobalRunSpec      runSpec = new GlobalRunSpec(template.TemplateSourceRoot, componentManager, parameters, variables, template.Config.OperationConfig, template.Config.SpecialOperationConfig, template.Config.LocalizationOperations, template.Config.IgnoreFileNames);
            List <IFileChange> changes = new List <IFileChange>();

            foreach (FileSourceMatchInfo source in template.Config.Sources)
            {
                runSpec.SetupFileSource(source);
                string target = Path.Combine(targetDirectory, source.Target);
                changes.AddRange(orchestrator.GetFileChanges(runSpec, template.TemplateSourceRoot.DirectoryInfo(source.Source), target));
            }

            return(new CreationEffects()
            {
                FileChanges = changes,
                CreationResult = GetCreationResult(environmentSettings, template, variables)
            });
        }
Exemple #17
0
        public IReadOnlyDictionary <string, string> GetRenames(string sourceDir, string targetBaseDir, IParameterSet parameters, IReadOnlyList <IReplacementTokens> symbolBasedRenames)
        {
            IFileSystemInfo configFileInfo = TemplateConfigTestHelpers.ConfigFileSystemInfo(SourceMountPoint, _configFile);

            parameters.TryGetParameterDefinition("name", out ITemplateParameter nameParam);
            object resolvedNameValue = parameters.ResolvedValues[nameParam];

            return(FileRenameGenerator.AugmentFileRenames(_environment, _sourceBaseDir, configFileInfo, sourceDir, ref targetBaseDir, resolvedNameValue, parameters, new Dictionary <string, string>(), symbolBasedRenames));
        }
        public void Evaluate(IParameterSet parameters, IVariableCollection rootVariableCollection, IFileSystemInfo configFile)
        {
            List <FileSource> sources = new List <FileSource>();
            bool stable = Symbols == null;
            Dictionary <string, bool> computed = new Dictionary <string, bool>();

            while (!stable)
            {
                stable = true;
                foreach (KeyValuePair <string, ISymbolModel> symbol in Symbols)
                {
                    if (symbol.Value.Type == "computed")
                    {
                        ComputedSymbol sym   = (ComputedSymbol)symbol.Value;
                        bool           value = CppStyleEvaluatorDefinition.EvaluateFromString(EnvironmentSettings, sym.Value, rootVariableCollection);
                        stable &= computed.TryGetValue(symbol.Key, out bool currentValue) && currentValue == value;
                        rootVariableCollection[symbol.Key] = value;
                        computed[symbol.Key] = value;
                    }
                    else if (symbol.Value.Type == "bind")
                    {
                        if (parameters.TryGetRuntimeValue(EnvironmentSettings, symbol.Value.Binding, out object bindValue) && bindValue != null)
                        {
                            rootVariableCollection[symbol.Key] = RunnableProjectGenerator.InferTypeAndConvertLiteral(bindValue.ToString());
                        }
                    }
                }
            }

            // evaluate the file glob (specials) conditions
            // the result is needed for SpecialOperationConfig
            foreach (ICustomFileGlobModel fileGlobModel in SpecialCustomSetup)
            {
                fileGlobModel.EvaluateCondition(EnvironmentSettings, rootVariableCollection);
            }

            parameters.ResolvedValues.TryGetValue(NameParameter, out object resolvedNameParamValue);

            // evaluate the conditions and resolve the paths for the PrimaryOutputs
            foreach (ICreationPathModel pathModel in PrimaryOutputs)
            {
                pathModel.EvaluateCondition(EnvironmentSettings, rootVariableCollection);

                if (pathModel.ConditionResult && resolvedNameParamValue != null)
                {
                    if (SourceName != null)
                    {
                        // this path will be included in the outputs, replace the name (same thing we do to other file paths)
                        pathModel.PathResolved = pathModel.PathOriginal.Replace(SourceName, (string)resolvedNameParamValue);
                    }
                    else
                    {
                        pathModel.PathResolved = pathModel.PathOriginal;
                    }
                }
            }

            foreach (ExtendedFileSource source in Sources)
            {
                if (!string.IsNullOrEmpty(source.Condition) && !CppStyleEvaluatorDefinition.EvaluateFromString(EnvironmentSettings, source.Condition, rootVariableCollection))
                {
                    continue;
                }

                List <string> includePattern        = JTokenToCollection(source.Include, SourceFile, IncludePatternDefaults).ToList();
                List <string> excludePattern        = JTokenToCollection(source.Exclude, SourceFile, ExcludePatternDefaults).ToList();
                List <string> copyOnlyPattern       = JTokenToCollection(source.CopyOnly, SourceFile, CopyOnlyPatternDefaults).ToList();
                Dictionary <string, string> renames = new Dictionary <string, string>(source.Rename ?? RenameDefaults);

                if (source.Modifiers != null)
                {
                    foreach (SourceModifier modifier in source.Modifiers)
                    {
                        if (string.IsNullOrEmpty(modifier.Condition) || CppStyleEvaluatorDefinition.EvaluateFromString(EnvironmentSettings, modifier.Condition, rootVariableCollection))
                        {
                            includePattern.AddRange(JTokenToCollection(modifier.Include, SourceFile, new string[0]));
                            excludePattern.AddRange(JTokenToCollection(modifier.Exclude, SourceFile, new string[0]));
                            copyOnlyPattern.AddRange(JTokenToCollection(modifier.CopyOnly, SourceFile, new string[0]));

                            if (modifier.Rename != null)
                            {
                                foreach (JProperty property in modifier.Rename.Properties())
                                {
                                    renames[property.Name] = property.Value.Value <string>();
                                }
                            }
                        }
                    }
                }

                Dictionary <string, string> coreRenames = new Dictionary <string, string>(renames);
                string sourceTargetName = source.Target ?? "./";

                if (resolvedNameParamValue != null && SourceName != null)
                {
                    string targetName = ((string)resolvedNameParamValue).Trim();

                    foreach (KeyValuePair <string, string> entry in coreRenames)
                    {
                        string outRel = entry.Value.Replace(SourceName, targetName);
                        renames[entry.Key] = outRel;
                    }

                    foreach (IFileSystemInfo entry in configFile.Parent.Parent.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
                    {
                        string tmpltRel = entry.PathRelativeTo(configFile.Parent.Parent);
                        string outRel   = tmpltRel.Replace(SourceName, targetName);
                        renames[tmpltRel] = outRel;
                    }

                    sourceTargetName = sourceTargetName.Replace(SourceName, targetName);
                }

                sources.Add(new FileSource
                {
                    CopyOnly = copyOnlyPattern.ToArray(),
                    Exclude  = excludePattern.ToArray(),
                    Include  = includePattern.ToArray(),
                    Source   = source.Source ?? "./",
                    Target   = sourceTargetName,
                    Rename   = renames
                });
            }

            if (Sources.Count == 0)
            {
                IReadOnlyList <string> includePattern  = IncludePatternDefaults;
                IReadOnlyList <string> excludePattern  = ExcludePatternDefaults;
                IReadOnlyList <string> copyOnlyPattern = CopyOnlyPatternDefaults;

                Dictionary <string, string> renames = new Dictionary <string, string>();

                if (SourceName != null)
                {
                    if (parameters.ResolvedValues.TryGetValue(NameParameter, out object resolvedValue))
                    {
                        foreach (IFileSystemInfo entry in configFile.Parent.Parent.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
                        {
                            string tmpltRel = entry.PathRelativeTo(configFile.Parent.Parent);
                            string outRel   = tmpltRel.Replace(SourceName, (string)resolvedValue);
                            renames[tmpltRel] = outRel;
                        }
                    }
                }

                sources.Add(new FileSource
                {
                    CopyOnly = copyOnlyPattern,
                    Exclude  = excludePattern,
                    Include  = includePattern,
                    Source   = "./",
                    Target   = "./",
                    Rename   = renames
                });
            }

            _sources = sources;
        }
        public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
        {
            GeneratePortNumberConfig config = rawConfig as GeneratePortNumberConfig;

            if (config == null)
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as EvaluateMacroConfig");
            }

            config.Socket?.Dispose();

            Parameter p;

            if (parameters.TryGetParameterDefinition(config.VariableName, out ITemplateParameter existingParam))
            {
                // If there is an existing parameter with this name, it must be reused so it can be referenced by name
                // for other processing, for example: if the parameter had value forms defined for creating variants.
                // When the param already exists, use its definition, but set IsVariable = true for consistency.
                p            = (Parameter)existingParam;
                p.IsVariable = true;

                if (string.IsNullOrEmpty(p.DataType))
                {
                    p.DataType = config.DataType;
                }
            }
            else
            {
                p = new Parameter
                {
                    IsVariable = true,
                    Name       = config.VariableName,
                    DataType   = config.DataType
                };
            }

            vars[config.VariableName] = config.Port.ToString();
            setter(p, config.Port.ToString());
        }
Exemple #20
0
        public async Task <TemplateCreationResult> InstantiateAsync(ITemplateInfo templateInfo, string name, string fallbackName, string outputPath, IReadOnlyDictionary <string, string> inputParameters, bool skipUpdateCheck, bool forceCreation, string baselineName)
        {
            // SettingsLoader.LoadTemplate is where the loc info should be read!!!
            // templateInfo knows enough to get at the loc, if any
            ITemplate template = _environmentSettings.SettingsLoader.LoadTemplate(templateInfo, baselineName);

            try
            {
                if (template == null)
                {
                    return(new TemplateCreationResult("Could not load template", CreationResultStatus.NotFound, templateInfo.Name));
                }

                string realName = name ?? fallbackName ?? template.DefaultName;

                if (string.IsNullOrEmpty(realName))
                {
                    return(new TemplateCreationResult("--name", CreationResultStatus.MissingMandatoryParam, template.Name));
                }

                // there should never be param errors here. If there are, the template is malformed, or the host gave an invalid value.
                IParameterSet templateParams = SetupDefaultParamValuesFromTemplateAndHost(template, realName, out IReadOnlyList <string> defaultParamsWithInvalidValues);
                ResolveUserParameters(template, templateParams, inputParameters, out IReadOnlyList <string> userParamsWithInvalidValues);

                if (AnyParametersWithInvalidDefaultsUnresolved(defaultParamsWithInvalidValues, userParamsWithInvalidValues, inputParameters, out IReadOnlyList <string> defaultsWithUnresolvedInvalidValues) ||
                    userParamsWithInvalidValues.Count > 0)
                {
                    string message = string.Join(", ", new CombinedList <string>(userParamsWithInvalidValues, defaultsWithUnresolvedInvalidValues));
                    return(new TemplateCreationResult(message, CreationResultStatus.InvalidParamValues, template.Name));
                }

                bool missingParams = CheckForMissingRequiredParameters(templateParams, out IList <string> missingParamNames);

                if (missingParams)
                {
                    return(new TemplateCreationResult(string.Join(", ", missingParamNames), CreationResultStatus.MissingMandatoryParam, template.Name));
                }

                if (template.IsNameAgreementWithFolderPreferred && string.IsNullOrEmpty(outputPath))
                {
                    outputPath = name;
                }

                ICreationResult creationResult = null;
                string          targetDir      = outputPath ?? _environmentSettings.Host.FileSystem.GetCurrentDirectory();

                try
                {
                    _paths.CreateDirectory(targetDir);
                    Stopwatch         sw = Stopwatch.StartNew();
                    IComponentManager componentManager = _environmentSettings.SettingsLoader.Components;

                    IReadOnlyList <IFileChange> changes            = template.Generator.GetCreationEffects(_environmentSettings, template, templateParams, componentManager, targetDir).FileChanges;
                    IReadOnlyList <IFileChange> destructiveChanges = changes.Where(x => x.ChangeKind != ChangeKind.Create).ToList();

                    if (!forceCreation && destructiveChanges.Count > 0)
                    {
                        if (!_environmentSettings.Host.OnPotentiallyDestructiveChangesDetected(changes, destructiveChanges))
                        {
                            return(new TemplateCreationResult("Cancelled", CreationResultStatus.Cancelled, template.Name));
                        }
                    }

                    creationResult = await template.Generator.CreateAsync(_environmentSettings, template, templateParams, componentManager, targetDir).ConfigureAwait(false);

                    sw.Stop();
                    _environmentSettings.Host.LogTiming("Content generation time", sw.Elapsed, 0);
                    return(new TemplateCreationResult(string.Empty, CreationResultStatus.Success, template.Name, creationResult, targetDir));
                }
                catch (ContentGenerationException cx)
                {
                    string message = cx.Message;
                    if (cx.InnerException != null)
                    {
                        message += Environment.NewLine + cx.InnerException.Message;
                    }

                    return(new TemplateCreationResult(message, CreationResultStatus.CreateFailed, template.Name));
                }
                catch (Exception ex)
                {
                    return(new TemplateCreationResult(ex.Message, CreationResultStatus.CreateFailed, template.Name));
                }
            }
            finally
            {
                ReleaseMountPoints(template);
            }
        }
        public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
        {
            ConstantMacroConfig config = rawConfig as ConstantMacroConfig;

            if (config == null)
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as ConstantMacroConfig");
            }

            Parameter p = new Parameter
            {
                IsVariable = true,
                Name       = config.VariableName
            };

            setter(p, config.Value);
        }
Exemple #22
0
        public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
        {
            GuidMacroConfig config = rawConfig as GuidMacroConfig;

            if (config == null)
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as GuidMacroConfig");
            }

            if (!string.IsNullOrEmpty(config.Format))
            {
                Guid      g     = Guid.NewGuid();
                string    value = char.IsUpper(config.Format[0]) ? g.ToString(config.Format[0].ToString()).ToUpperInvariant() : g.ToString(config.Format[0].ToString()).ToLowerInvariant();
                Parameter p     = new Parameter
                {
                    IsVariable = true,
                    Name       = config.VariableName
                };

                vars[config.VariableName] = value;
                setter(p, value);
            }
            else
            {
                Guid   g           = Guid.NewGuid();
                string guidFormats = GuidMacroConfig.DefaultFormats;
                for (int i = 0; i < guidFormats.Length; ++i)
                {
                    string    value = char.IsUpper(guidFormats[i]) ? g.ToString(guidFormats[i].ToString()).ToUpperInvariant() : g.ToString(guidFormats[i].ToString()).ToLowerInvariant();
                    Parameter p     = new Parameter
                    {
                        IsVariable = true,
                        Name       = config.VariableName + "-" + guidFormats[i]
                    };

                    vars[config.VariableName] = value;
                    setter(p, value);
                }

                Parameter pd = new Parameter
                {
                    IsVariable = true,
                    Name       = config.VariableName
                };

                vars[config.VariableName] = g.ToString("D");
                setter(pd, g.ToString("D"));
            }
        }
        public void EvaluateDeferredConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
        {
            GeneratedSymbolDeferredMacroConfig deferredConfig = rawConfig as GeneratedSymbolDeferredMacroConfig;

            if (deferredConfig == null)
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as a GeneratedSymbolDeferredMacroConfig");
            }

            if (!deferredConfig.Parameters.TryGetValue("value", out JToken valueToken))
            {
                throw new ArgumentNullException("value");
            }

            string       value      = valueToken.ToString();
            IMacroConfig realConfig = new ConstantMacroConfig(deferredConfig.VariableName, value);

            EvaluateConfig(environmentSettings, vars, realConfig, parameters, setter);
        }
Exemple #24
0
        public void Evaluate(string variableName, IVariableCollection vars, JObject def, IParameterSet parameters, ParameterSetter setter)
        {
            string    format = def.ToString("action");
            bool      utc    = def.ToBool("utc");
            DateTime  time   = utc ? DateTime.UtcNow : DateTime.Now;
            string    value  = time.ToString(format);
            Parameter p      = new Parameter
            {
                IsVariable = true,
                Name       = variableName
            };

            setter(p, value);
        }
Exemple #25
0
        public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
        {
            EvaluateMacroConfig config = rawConfig as EvaluateMacroConfig;

            if (config == null)
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as EvaluateMacroConfig");
            }

            ConditionEvaluator evaluator = EvaluatorSelector.Select(config.Evaluator);

            byte[]          data   = Encoding.UTF8.GetBytes(config.Value);
            int             len    = data.Length;
            int             pos    = 0;
            IProcessorState state  = new GlobalRunSpec.ProcessorState(environmentSettings, vars, data, Encoding.UTF8);
            bool            result = evaluator(state, ref len, ref pos, out bool faulted);

            Parameter p = new Parameter
            {
                IsVariable = true,
                Name       = config.VariableName
            };

            setter(p, result.ToString());
        }
Exemple #26
0
 public RenderPackage(RenderKernel kernel, IParameterSet parameters)
 {
     _kernel = kernel;
     _parameters = parameters;
 }
Exemple #27
0
 /// <summary>
 /// Enumerates all the named parameters and properties of an <see cref="IParameterSet"/>.
 /// </summary>
 /// <param name="parameters">The parameter set.</param>
 /// <returns>
 /// All the named parameters.
 /// </returns>
 /// <exception cref="ArgumentNullException">Thrown if <paramref name="parameters"/> is <c>null</c>.</exception>
 public static IEnumerable <MemberDescription> Parameters(this IParameterSet parameters)
 => Parameters(parameters.ThrowIfNull(nameof(parameters)).GetType());
        private static void ValidateGuidMacroCreatedParametersWithResolvedValues(string variableName, IParameterSet parameters)
        {
            ITemplateParameter setParam;

            Assert.True(parameters.TryGetParameterDefinition(variableName, out setParam));

            Guid paramValue = Guid.Parse((string)parameters.ResolvedValues[setParam]);

            // check that all the param name variants were created, and their values all resolve to the same guid.
            string guidFormats = GuidMacroConfig.DefaultFormats;

            for (int i = 0; i < guidFormats.Length; ++i)
            {
                string             otherFormatParamName = variableName + "-" + guidFormats[i];
                ITemplateParameter testParam;
                Assert.True(parameters.TryGetParameterDefinition(otherFormatParamName, out testParam));
                Guid testValue = Guid.Parse((string)parameters.ResolvedValues[testParam]);
                Assert.Equal(paramValue, testValue);
            }
        }
Exemple #29
0
        public void Evaluate(string variableName, IVariableCollection vars, JObject def, IParameterSet parameters, ParameterSetter setter)
        {
            switch (def["action"].ToString())
            {
            case "new":
                int       low   = def.ToInt32("low");
                int       high  = def.ToInt32("high", int.MaxValue);
                Random    rnd   = new Random();
                int       val   = rnd.Next(low, high);
                string    value = val.ToString();
                Parameter p     = new Parameter
                {
                    IsVariable = true,
                    Name       = variableName
                };

                setter(p, value);
                break;
            }
        }
        // Returns a list of operations which contains the custom operations and the default operations.
        // If there are custom Conditional operations, don't include the default Conditionals.
        //
        // Note: we may need a more robust filtering mechanism in the future.
        private static IReadOnlyList <IOperationProvider> ResolveOperations(IGlobalRunConfig runConfig, IDirectory templateRoot, IVariableCollection variables, IParameterSet parameters)
        {
            IReadOnlyList <IOperationProvider> customOperations  = SetupCustomOperations(runConfig.CustomOperations, templateRoot, variables);
            IReadOnlyList <IOperationProvider> defaultOperations = SetupOperations(parameters, runConfig);

            List <IOperationProvider> operations = new List <IOperationProvider>(customOperations);

            if (customOperations.Any(x => x is Conditional))
            {
                operations.AddRange(defaultOperations.Where(op => !(op is Conditional)));
            }
            else
            {
                operations.AddRange(defaultOperations);
            }

            return(operations);
        }
        public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
        {
            string value = null;
            CaseChangeMacroConfig config = rawConfig as CaseChangeMacroConfig;

            if (config == null)
            {
                throw new InvalidCastException("Couldn't cast the rawConfig as CaseChangeMacroConfig");
            }

            if (!vars.TryGetValue(config.SourceVariable, out object working))
            {
                if (RuntimeValueUtil.TryGetRuntimeValue(parameters, environmentSettings, config.SourceVariable, out object resolvedValue, true))
                {
                    value = resolvedValue.ToString();
                }
                else
                {
                    value = string.Empty;
                }
            }
        // Note the deferred-config macros (generated) are part of the runConfig.Macros
        //      and not in the ComputedMacros.
        //  Possibly make a separate property for the deferred-config macros
        private static void ProcessMacros(IEngineEnvironmentSettings environmentSettings, IComponentManager componentManager, IGlobalRunConfig runConfig, IParameterSet parameters)
        {
            if (runConfig.Macros != null)
            {
                IVariableCollection   varsForMacros  = VariableCollection.SetupVariables(environmentSettings, parameters, runConfig.VariableSetup);
                MacrosOperationConfig macroProcessor = new MacrosOperationConfig();
                macroProcessor.ProcessMacros(environmentSettings, componentManager, runConfig.Macros, varsForMacros, parameters);
            }

            if (runConfig.ComputedMacros != null)
            {
                IVariableCollection   varsForMacros  = VariableCollection.SetupVariables(environmentSettings, parameters, runConfig.VariableSetup);
                MacrosOperationConfig macroProcessor = new MacrosOperationConfig();
                macroProcessor.ProcessMacros(environmentSettings, componentManager, runConfig.ComputedMacros, varsForMacros, parameters);
            }
        }
Exemple #33
0
 public UniformCrossover(IRandom random, IParameterSet parameterSet, IList <IConflictDetector> conflictDetectors)
     : base(random, parameterSet, conflictDetectors)
 {
 }
Exemple #34
0
 public void Draw(Action<ComputeBuffer<Vector4>, ComputeCommandQueue, IParameterSet, Size> renderer, IParameterSet parameters, Size windowSize)
 {
     if (_disposed)
         throw new ObjectDisposedException(ToString());
     GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
     GL.Finish();
     _queue.AcquireGLObjects(new[] { _openCl }, null);
     renderer(_openCl, _queue, parameters, windowSize);
     _queue.ReleaseGLObjects(new[] { _openCl }, null);
     _queue.Finish();
     GL.BindBuffer(BufferTarget.PixelUnpackBuffer, _pub);
     GL.BindTexture(TextureTarget.Texture2D, _texture);
     GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, _width, _height, PixelFormat.Rgba, PixelType.Float, IntPtr.Zero);
     GL.Begin(PrimitiveType.Quads);
     GL.TexCoord2(0f, 1f);
     GL.Vertex3(0f, 0f, 0f);
     GL.TexCoord2(0f, 0f);
     GL.Vertex3(0f, 1f, 0f);
     GL.TexCoord2(1f, 0f);
     GL.Vertex3(1f, 1f, 0f);
     GL.TexCoord2(1f, 1f);
     GL.Vertex3(1f, 0f, 0f);
     GL.End();
 }
Exemple #35
0
 public void Render(ComputeBuffer<Vector4> buffer, ComputeCommandQueue queue, IParameterSet parameters, Size windowSize)
 {
     Render(buffer, queue, parameters, windowSize, 0, new Size(0, 0));
 }