public static InputLayout GetInputLayout(Device device, CompilationResult vertexShaderByteCode) { var inputElements = new InputElement[] { new InputElement { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement { SemanticName = "COLOR", SemanticIndex = 0, Format = Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = LightShader.Vertex.AppendAlignedElement1, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; return new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); }
private void ValidateMethod(MethodDeclaration method, List<string> list, CompilationResult result) { var name = method.Name; if (String.IsNullOrWhiteSpace(name)) { result.AddError(new CompilationMessage { FilePath = method.OriginatingTree != null ? method.OriginatingTree.FilePath : null, Location = DocumentLocation.FromTreeNode(method.OriginatingTree, method.OriginatingNode), Message = "All generated method calls must have a valid name." }); return; } if (list.Contains(name)) { result.AddError(new CompilationMessage { FilePath = method.OriginatingTree != null ? method.OriginatingTree.FilePath : null, Location = DocumentLocation.FromTreeNode(method.OriginatingTree, method.OriginatingNode), Message = "Method overloading is not supported. Consider using optional parameters, " + "or providing an alternate name using the ScriptName attribute." }); return; } list.Add(name); }
public CompileStrategyInfoResultCommand(CompilationResult result) { if (result == null) throw new ArgumentNullException("result"); Result = result; }
public ActionResult Compile() { var project = Session["project"] as IRuntimeProject; if (project == null) return HttpNotFound(); //td: right error var result = new CompilationResult(project.compile()); return Json(result, JsonRequestBehavior.AllowGet); }
public PassThroughFilter(Device device) { this.pixelShaderByteCode = ShaderBytecode.CompileFromFile("Graphics/PassThrough.hlsl", "pixel", "ps_4_0", ShaderFlags.OptimizationLevel1, EffectFlags.None, null, null); this.pixelShader = new PixelShader(device, this.pixelShaderByteCode, null); this.sampler = new SamplerState(device, new SamplerStateDescription { MaximumAnisotropy = 16, Filter = SharpDX.Direct3D11.Filter.Anisotropic, AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, MinimumLod = 0f, MaximumLod = 100f }); }
/// <inheritdoc/> public CompilationResult Compile(string shaderSource, string entryPoint, string profile, string sourceFileName = "unknown") { SharpDX.Configuration.ThrowOnShaderCompileError = false; // Compile var compilationResult = SharpDX.D3DCompiler.ShaderBytecode.Compile(shaderSource, entryPoint, profile, SharpDX.D3DCompiler.ShaderFlags.OptimizationLevel0 | SharpDX.D3DCompiler.ShaderFlags.Debug, SharpDX.D3DCompiler.EffectFlags.None, null, null, sourceFileName); var bytecode = compilationResult.Bytecode; var result = new CompilationResult(bytecode == null ? null : new ShaderBytecode(bytecode.Data), compilationResult.HasErrors, compilationResult.Message); return result; }
/// <summary> /// Validates the generated model. /// </summary> /// <param name="model">The compilation model.</param> /// <param name="result">The compilation result.</param> public void Validate(CompilationModel model, CompilationResult result) { var instanceMethods = new List<string>(); var staticMethdos = new List<string>(); foreach (var item in model.Classes) { instanceMethods.Clear(); staticMethdos.Clear(); foreach (var method in item.Methods) { ValidateMethod(method, (method.IsStatic ? staticMethdos : instanceMethods), result); } } }
public static void Init(SharpDX.Direct3D11.Device device) { vertexShaderByteCode = ShaderBytecode.CompileFromFile("Graphics/VertexShader.hlsl", "vertex", "vs_4_0", ShaderFlags.OptimizationLevel1, EffectFlags.None, null, null); vertexShader = new VertexShader(device, vertexShaderByteCode, null); vertices = SharpDX.Direct3D11.Buffer.Create<Vertex>(device, BindFlags.VertexBuffer, new Vertex[] { new Vertex(new Vector4(-1f, -1f, 0.5f, 1f), new Vector2(0f, 1f)), new Vertex(new Vector4(-1f, 1f, 0.5f, 1f), new Vector2(0f, 0f)), new Vertex(new Vector4(1f, -1f, 0.5f, 1f), new Vector2(1f, 1f)), new Vertex(new Vector4(-1f, 1f, 0.5f, 1f), new Vector2(0f, 0f)), new Vertex(new Vector4(1f, 1f, 0.5f, 1f), new Vector2(1f, 0f)), new Vertex(new Vector4(1f, -1f, 0.5f, 1f), new Vector2(1f, 1f)) }, 144, ResourceUsage.Default, CpuAccessFlags.None, ResourceOptionFlags.None, 0); layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), Vertex.elements); binding = new VertexBufferBinding(vertices, 24, 0); buffer = new SharpDX.Direct3D11.Buffer(device, 64, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); data.offset = 0f; data.scale = 1f; }
private static Response GetResponse(CompilationResult content) { var response = new Response(); response.StatusCode = HttpStatusCode.OK; response.ContentType = content.MimeType; response.Headers["ETag"] = content.SourceLastModifiedUtc.Ticks.ToString("x"); response.Headers["Content-Disposition"] = "inline"; response.Headers["Last-Modified"] = content.SourceLastModifiedUtc.ToString("R"); response.Contents = s => { using (var writer = new StreamWriter(s)) { writer.Write(content.Contents); writer.Flush(); } }; return response; }
static void Main(string[] args) { CrawlCompilerConfiguration configuration; if (ParseOptions(args, out configuration)) { CompilationResult result = CrawlCompiler.Compile(configuration); string line = new String('=', Console.BufferWidth); foreach (CompilationMessage message in result.Messages .OrderBy(message => message.Severity) .ThenBy(x => x.File) .ThenBy(x => x.FirstPoint)) { message.WriteToConsole(); Console.Write(line); } } Console.WriteLine("Press enter to exit..."); Console.ReadLine(); }
private static void OutputCompilationSummary(IConsole console, CompilationResult result) { if (result.HasErrors) { if (result.HasWarnings) { console.Out.Write($"Compilation failed with {result.Errors.Count()} error(s) and {result.Warnings.Count()} warning(s):{Environment.NewLine}{Environment.NewLine}"); } else { console.Out.Write($"Compilation failed with {result.Messages.Count()} error(s):{Environment.NewLine}{Environment.NewLine}"); } } else if (result.HasWarnings) { console.Out.Write($"Compilation succeeded with {result.Warnings.Count()} warning(s):{Environment.NewLine}{Environment.NewLine}"); } else { console.Out.Write($"Compilation succeeded with no errors or warnings!{Environment.NewLine}"); } }
public static InputLayout GetInputLayout(Device device, CompilationResult vertexShaderByteCode) { var inputElements = new[] { new InputElement { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = Format.R32G32_Float, Slot = 0, AlignedByteOffset = AppendAlignedElement1, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement { SemanticName = "TEXCOORD", SemanticIndex = 1, Format = Format.R32G32_Float, Slot = 0, AlignedByteOffset = AppendAlignedElement2, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; return(new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements)); }
public void Compile_ReturnsResultFromCompilationServiceIfParseSucceeds() { // Arrange var code = "compiled-content"; var generatorResult = new GeneratorResults( new Block(new BlockBuilder { Type = BlockType.Comment }), Enumerable.Empty <TagHelperDescriptor>(), new ParserErrorSink(), new CodeBuilderResult(code, new LineMapping[0]), new CodeTree()); var host = new Mock <IMvcRazorHost>(); host.Setup(h => h.GenerateCode(It.IsAny <string>(), It.IsAny <Stream>())) .Returns(generatorResult); var fileInfo = new Mock <IFileInfo>(); fileInfo.Setup(f => f.CreateReadStream()) .Returns(Stream.Null); var compilationResult = CompilationResult.Successful(typeof(object)); var compiler = new Mock <ICompilationService>(); compiler.Setup(c => c.Compile(fileInfo.Object, code)) .Returns(compilationResult) .Verifiable(); var relativeFileInfo = new RelativeFileInfo(fileInfo.Object, @"Views\index\home.cshtml"); var razorService = new RazorCompilationService(compiler.Object, host.Object); // Act var result = razorService.Compile(relativeFileInfo); // Assert Assert.Same(compilationResult, result); compiler.Verify(); }
public async Task ReturnsFailedResultIfNoRegisteredCompilerCanCompileInput() { // Arrange var compiled = new Mock <Type>(); TestableDefaultCompilationManager cm = CreateManager(); TestFile file = TestData.CreateDummyFile(); var compiler = new Mock <ICompiler>(MockBehavior.Strict); cm.MockContentIdentifier .Setup(i => i.GenerateContentId(file)) .Returns("Foo"); compiler.Setup(c => c.CanCompile(file)).Returns(false); cm.Compilers.Add(compiler.Object); // Act CompilationResult result = await cm.Compile(file, NullTrace.Instance); // Assert Assert.False(result.Success); Assert.Equal( Resources.DefaultCompilationManager_CannotFindCompiler, result.Messages.Single().Message); }
public override void Initialize() { CompilationResult result = ShaderBytecode.CompileFromFile("./Resources/Shaders/Default_Forward.fx", "fx_4_0"); if (result.HasErrors) { return; } Effect = new Effect(Context.Device, result.Bytecode); Technique = Effect.GetTechniqueByIndex(0); InputElement[] vertexLayout = { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 20, 0, InputClassification.PerVertexData, 0), new InputElement("TANGENT", 0, Format.R32G32B32_Float, 32, 0, InputClassification.PerVertexData, 0), }; InputLayout = new InputLayout(Context.Device, Technique.GetPassByIndex(0).Description.Signature, vertexLayout); LoadShaderVariables(); }
/// <summary> /// Parses a string /// </summary> /// <param name="content">Template to parse</param> /// <param name="model">Template model</param> /// <param name="modelType">Type of the model</param> /// <returns></returns> public static string ParseString(this IRazorLightEngine engine, string content, object model, Type modelType) { if (string.IsNullOrEmpty(content)) { throw new ArgumentNullException(nameof(content)); } ITemplateSource templateSource = new LoadedTemplateSource(content); ModelTypeInfo modelTypeInfo = new ModelTypeInfo(modelType); CompilationResult result = engine.Core.CompileSource(templateSource, modelTypeInfo); result.EnsureSuccessful(); TemplatePage page = engine.Activate(result.CompiledType); page.PageContext = new PageContext() { ModelTypeInfo = modelTypeInfo }; return(engine.RunTemplate(page, model)); }
Type CompileGraph(CodeGenMode mode) { RoslynEcsTranslator translator = (RoslynEcsTranslator)GraphModel.CreateTranslator(); translator.AllowNoJobsFallback = false; // because of the hack in the translator constructor, override right after ((EcsStencil)Stencil).UseJobSystem = mode == CodeGenMode.Jobs; CompilationResult results = GraphModel.Compile(AssemblyType.Memory, translator, CompilationOptions.LiveEditing); if (results?.sourceCode != null && results.sourceCode.Length != 0) { LogAssert.Expect(LogType.Log, new Regex("using.*")); Debug.Log(results.sourceCode[(int)SourceCodePhases.Initial]); } Assert.That(results?.status, Is.EqualTo(CompilationStatus.Succeeded), () => $"Compilation failed, errors: {String.Join("\n", results?.errors)}"); return(EcsStencil.LiveCompileGraph(GraphModel, results, includeVscriptingAssemblies: true)); }
public void GetOrAdd_NormalizesPathSepartorForPaths(string relativePath) { // Arrange var viewPath = "/Areas/Finances/Views/Home/Index.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(viewPath, "some content"); var cache = new CompilerCache(fileProvider); var type = typeof(TestView); var expected = new CompilationResult(type); // Act - 1 var result1 = cache.GetOrAdd(@"Areas\Finances\Views\Home\Index.cshtml", _ => expected); // Assert - 1 Assert.Same(type, result1.CompilationResult.CompiledType); // Act - 2 var result2 = cache.GetOrAdd(relativePath, ThrowsIfCalled); // Assert - 2 Assert.Same(type, result2.CompilationResult.CompiledType); }
private void LoadShader() { CompilationResult result = ShaderBytecode.CompileFromFile("./Resources/Shaders/DebugRenderer.fx", "fx_4_0"); if (result.HasErrors) { DebugLog.Log(result.Message, "Failed to compile shader", LogSeverity.Error); return; } _effect = new Effect(_context.Device, result.Bytecode); _technique = _effect.GetTechniqueByIndex(0); _wvpVar = _effect.GetVariableBySemantic("WORLDVIEWPROJECTION").AsMatrix(); InputElement[] vertexLayout = { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0), }; EffectPass passDesc = _technique.GetPassByIndex(0); _inputLayout = new InputLayout(_context.Device, passDesc.Description.Signature, vertexLayout); }
protected static void CompileFile() { WriteHeader("Compilation of SCSS file"); string inputFilePath = Path.Combine(_filesDirectoryPath, "style.scss"); string outputFilePath = Path.Combine(_filesDirectoryPath, "style.css"); try { using (var sassCompiler = new SassCompiler(new CompilationOptions { SourceMap = true })) { CompilationResult result = sassCompiler.CompileFile(inputFilePath, outputFilePath); WriteVersion(sassCompiler.Version); WriteOutput(result); } } catch (SassException e) { WriteError("During compilation of SCSS file an error occurred.", e); } }
public static CompilationResult Compile(string code) { SyntaxTree tree = CSharpSyntaxTree.ParseText(code, options: new CSharpParseOptions(kind: SourceCodeKind.Script)); var privCorLibLocation = typeof(object).GetTypeInfo().Assembly.Location; var corlibLocation = Path.Combine(Path.GetDirectoryName(privCorLibLocation), "mscorlib.dll"); var sysRuntimeLocation = Path.Combine(Path.GetDirectoryName(privCorLibLocation), "System.Runtime.dll"); var compilation = CSharpCompilation.Create("DotNetFunction", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, scriptClassName: "Function")) .AddReferences(MetadataReference.CreateFromFile(privCorLibLocation) , MetadataReference.CreateFromFile(corlibLocation) , MetadataReference.CreateFromFile(sysRuntimeLocation) , MetadataReference.CreateFromFile(typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).GetTypeInfo().Assembly.Location) //Import MS.CSharp , MetadataReference.CreateFromFile(typeof(XmlDocument).GetTypeInfo().Assembly.Location) //Import XmlDocument , MetadataReference.CreateFromFile(typeof(System.Xml.Linq.XDocument).GetTypeInfo().Assembly.Location) //Import XDocument , MetadataReference.CreateFromFile(typeof(System.Net.Http.HttpRequestMessage).GetTypeInfo().Assembly.Location) , MetadataReference.CreateFromFile(typeof(System.Net.HttpStatusCode).GetTypeInfo().Assembly.Location) , MetadataReference.CreateFromFile(typeof(System.Uri).GetTypeInfo().Assembly.Location) , MetadataReference.CreateFromFile(typeof(Newtonsoft.Json.JsonConvert).GetTypeInfo().Assembly.Location) ) .AddSyntaxTrees(tree); var result = new CompilationResult() { Diagnostics = compilation.GetDiagnostics() }; if (result.Diagnostics != null && !result.Diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error)) { MemoryStream ms = new MemoryStream(); var emitResult = compilation.Emit(ms); result.OutputBinary = ms.ToArray(); } return(result); }
public void CompileInfiniteRecursion() => CheckCompilationResult( new Dictionary <string, string> { { "A", "{{B}}" }, { "B", "{{A}}" } }, new Dictionary <string, string> { { "A", "{{A}}" } }, new Dictionary <string, string>(), new Dictionary <string, string>(), result => { var compiled = result.CompiledConfiguration; Assert.NotNull(compiled); Assert.NotEmpty(compiled); Assert.Equal("", compiled["A"]); }, (compiler, parser, env, structure) => { CompilationResult r = null; var thread = new Thread(() => { r = compiler.Compile(env, structure, parser); }); thread.Start(); // wait for the compilation to finish, but it should finish within a couple seconds // otherwise it's probably caught in an endless loop thread.Join(TimeSpan.FromSeconds(5)); // r will be set if compilation was successful Assert.NotNull(r); return(r); });
static CompilationResult CheckSemanticModel(Microsoft.CodeAnalysis.SyntaxTree syntaxTree, CompilationResult compilationResult) { SemanticModel semanticModel = GetSemanticModel(syntaxTree); // run all the semantic code analyzers var diagnostics = new List <CompilerError>(); Profiler.BeginSample("GetDiagnostics"); ImmutableArray <Diagnostic> rawDiagnostics = semanticModel.GetDiagnostics(); Profiler.EndSample(); Profiler.BeginSample("ProcessDiagnostics"); ProcessDiagnostics(rawDiagnostics, diagnostics); Profiler.EndSample(); if (diagnostics.Any()) { compilationResult.errors = diagnostics; } return(compilationResult); }
private static void WriteOutput(CompilationResult result) { Console.WriteLine("Compiled content:{1}{1}{0}{1}", result.CompiledContent, Environment.NewLine); Console.WriteLine("Source map:{1}{1}{0}{1}", result.SourceMap, Environment.NewLine); IList <string> includedFilePaths = result.IncludedFilePaths; if (includedFilePaths.Count > 0) { Console.WriteLine("Included file paths:"); Console.WriteLine(); foreach (string includedFilePath in includedFilePaths) { Console.WriteLine(includedFilePath); } Console.WriteLine(); } IList <ProblemInfo> warnings = result.Warnings; if (warnings.Count > 0) { Console.WriteLine("Warnings:"); Console.WriteLine(); foreach (ProblemInfo warning in warnings) { Console.WriteLine(warning.Message); Console.WriteLine(); } } Console.WriteLine(); }
private static bool CompileHlslBySharpDX(string shaderPath, string entryPoint, ShaderFunctionType type, out string path, bool debug) { try { string profile = type == ShaderFunctionType.VertexEntryPoint ? "vs_5_0" : type == ShaderFunctionType.FragmentEntryPoint ? "ps_5_0" : "cs_5_0"; string outputPath = shaderPath + ".bytes"; ShaderFlags shaderFlags = debug ? ShaderFlags.SkipOptimization | ShaderFlags.Debug : ShaderFlags.OptimizationLevel3; CompilationResult compilationResult = ShaderBytecode.CompileFromFile( shaderPath, entryPoint, profile, shaderFlags, EffectFlags.None); if (null == compilationResult.Bytecode) { Console.WriteLine($"Failed to compile HLSL: {compilationResult.Message}."); } else { compilationResult.Bytecode.Save(File.OpenWrite(outputPath)); } } catch (Win32Exception) { Console.WriteLine("Unable to invoke HLSL compiler library."); } path = null; return(false); }
private void CompileShader(Device device, string fullPath) { _File = fullPath; _CompiledEffect = ShaderBytecode.CompileFromFile(_File, "SpriteTech", "fx_5_0"); if (_CompiledEffect.HasErrors) { Log.Write("Shader compilation failed with status code: {0} - {1} | Path: {2}", _CompiledEffect.ResultCode.Code, _CompiledEffect.Message, _File); return; } _Effect = new Effect(device, _CompiledEffect); _EffectTechnique = _Effect.GetTechniqueByName("SpriteTech"); _SpriteMap = _Effect.GetVariableByName("SpriteTex").AsShaderResource(); var _EffectPass = _EffectTechnique.GetPassByIndex(0).Description.Signature; InputElement[] _LayoutDescription = { new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0) }; _InputLayout = new InputLayout(device, _EffectPass, _LayoutDescription); }
/// <summary> /// Dispose of this domain. /// This will cause the target app domain to be unloaded if it is not the default app domain. /// The domain will be unusable after disposing. /// </summary> public void Dispose() { if (sandbox != null) { // Unload app domain if (sandbox.IsDefaultAppDomain() == false) { AppDomain.Unload(sandbox); } // Remove from active list activeDomains.Remove(this); lock (this) { loadedAssemblies.Clear(); } sandbox = null; sharedCompiler = null; securityResult = null; compileResult = null; } }
public void ReturnsAndCachesCompiledResultIfCachedValueHasBeenCollected() { // Arrange var compiled = new Mock <Type>(); TestableDefaultCompilationManager cm = CreateManager(); TestFile file = TestData.CreateDummyFile(); var compiler = new Mock <ICompiler>(); cm.Compilers.Add(compiler.Object); cm.MockContentIdentifier .Setup(i => i.GenerateContentId(file)).Returns("Foo"); compiler.Setup(c => c.CanCompile(file)).Returns(true); compiler.Setup(c => c.Compile(file)).Returns(Task.FromResult(CompilationResult.Successful(It.IsAny <string>(), compiled.Object, new[] { new CompilationMessage(MessageLevel.Info, "Foo") }))); // Add a cache entry, but collect it. cm.Cache["Foo"] = new WeakReference <Type>(new FakeType()); GC.Collect(); // Act // Using ".Result" because making this Async causes a reference to the cached type to be held. CompilationResult result = cm.Compile(file, NullTrace.Instance).Result; // Assert Assert.True(result.Success); Assert.False(result.SatisfiedFromCache); Assert.Equal("Foo", result.Messages.Single().Message); Assert.Same(compiled.Object, result.GetCompiledType()); Type cached; Assert.True(cm.Cache["Foo"].TryGetTarget(out cached)); Assert.Same(compiled.Object, cached); }
// Compile a script (or all scripts in a directory), save the compiled result // to the cache and return the compiled type. // If an error occurs in batch compilation, then an attempt is made to compile just the single // request file. public Type CompileScript(string filename, bool batch) { IDictionary <ICompilerInput, string> inputs2FileName = GetInput(filename, batch); string name = NormalizeName(filename); Log("Compiling {0} to {1} with batch: {2}", filename, name, batch); CompilationResult result = DoCompile(inputs2FileName.Keys, name); if (result.Context.Errors.Count > 0) { if (batch == false) { RaiseCompilationException(filename, inputs2FileName, result); } //error compiling a batch, let's try a single file return(CompileScript(filename, false)); } Type type; foreach (var input in inputs2FileName.Keys) { string viewName = Path.GetFileNameWithoutExtension(input.Name); string typeName = TransformToBrailStep.GetViewTypeName(viewName); type = result.Context.GeneratedAssembly.GetType(typeName); Log("Adding {0} to the cache", type.FullName); compilations[inputs2FileName[input]] = type; constructors[type] = type.GetConstructor(new[] { typeof(BooViewEngine) }); // typeof(TextWriter) // typeof(IEngineContext), // typeof(IController), // typeof(IControllerContext) // }); } type = (Type)compilations[filename]; return(type); }
public Tester(IFactory <ICompiler> compilers, SubmissionInfo submissionInfo, TestInfo testInfo) { this.submissionInfo = submissionInfo; this.testInfo = testInfo; CompilationResult checkerCompilationResult = CompilerExtensions.CompileToTempDirectory(testInfo.Checker, compilers); if (!checkerCompilationResult.Success) { throw new FailedActionException( "скомпилировать чекер", "Лог компиляции: " + checkerCompilationResult.CompilerOutput); } checkerPath = checkerCompilationResult.OutputFileName; checkerDirectory = Path.GetDirectoryName(checkerPath); CompilationResult sourceCompilationResult = CompilerExtensions.CompileToTempDirectory(submissionInfo.Source, compilers); result = new TestLog { CompilationReport = sourceCompilationResult.CompilerOutput }; compilationSucceeded = sourceCompilationResult.Success; solutionPath = sourceCompilationResult.OutputFileName; solutionDirectory = Path.GetDirectoryName(solutionPath); }
public virtual void OnCompilationRequest(RequestCompilationOptions options) { CompilationOptions compilationOptions = EditorApplication.isPlaying ? CompilationOptions.LiveEditing : CompilationOptions.Default; // Register m_PluginRepository.RegisterPlugins(compilationOptions); VSGraphModel vsGraphModel = Store.GetState().CurrentGraphModel as VSGraphModel; if (!vsGraphModel || vsGraphModel.Stencil == null) { return; } ITranslator translator = vsGraphModel.Stencil.CreateTranslator(); if (!translator.SupportsCompilation()) { return; } if (options == RequestCompilationOptions.SaveGraph) { AssetDatabase.SaveAssets(); } CompilationResult r = vsGraphModel.Compile(AssemblyType.None, translator, compilationOptions, m_PluginRepository.GetPluginHandlers()); if (Store?.GetState()?.CompilationResultModel is CompilationResultModel compilationResultModel) // TODO: could have disappeared during the await { compilationResultModel.lastResult = r; OnCompilationDone(vsGraphModel, compilationOptions, r); } }
void HandleCompilingErrors(Action action) { CompilationResult.Reset(); try { action(); } catch (Exception) { if (CompilationResult.HasErrors) { throw CompilationResult.CreateException(); } else { //The exception is most likely related to the compilation error //so do noting. Alternatively (may be in the future) we can add //it to the errors collection. //CompilingResult.Errors.Add(e.ToString()); throw; } } finally { //We need to reset Evaluator every time after compilation exception occurs //because Mono throws error on attempt to compile again in this case if (CompilationResult.HasErrors) { SoftReset(); } //Keep CompilationOutput instance with relevant information about last compilation UpdateCompilationOutput(); } }
private static FileResult.Validity FileProcessor(FileInfo file, out FileResult?result) { switch (file.Extension) { case ".gen": case ".scss" when file.Name[0] == '_': result = null; return(FileResult.Validity.Skipped); case ".scss": { try { CompilationOptions options = new() { IncludePaths = file.Directory !.GetFiles("_*.scss").Select(f => f.FullName).ToList(), IndentType = IndentType.Tab, IndentWidth = 1 }; using SassCompiler sassCompiler = new(new V8JsEngineFactory(), options); CompilationResult compilationResult = sassCompiler.CompileFile(file.FullName); result = new(compilationResult.CompiledContent, Path.ChangeExtension(file.Name, "css")); } catch (Exception e) { throw new BuildException(e, "SCSS failure"); } return(FileResult.Validity.Processed); } default: result = null; return(FileResult.Validity.NotProcessed); } }
protected override void Import(ModuleImporter importer, CompilationResult result) => importer.Import(result.RawFile, result.DebugFile, nonNestedTypeToEdit);
private void RaiseCompilationException(string filename, IDictionary<ICompilerInput, string> inputs2FileName, CompilationResult result) { string errors = result.Context.Errors.ToString(true); Log("Failed to compile {0} because {1}", filename, errors); StringBuilder code = new StringBuilder(); foreach (ICompilerInput input in inputs2FileName.Keys) { code.AppendLine() .Append(result.Processor.GetInputCode(input)) .AppendLine(); } throw new HttpParseException("Error compiling Brail code", result.Context.Errors[0], filename, code.ToString(), result.Context.Errors[0].LexicalInfo.Line); }
public static CompilationResult Compile(CompilationJob compilationJob) { var results = new List <CompilationResult>(); // All variable declarations that we've encountered during this // compilation job var derivedVariableDeclarations = new List <Declaration>(); // All variable declarations that we've encountered, PLUS the // ones we knew about before var knownVariableDeclarations = new List <Declaration>(); if (compilationJob.VariableDeclarations != null) { knownVariableDeclarations.AddRange(compilationJob.VariableDeclarations); } // Get function declarations from the library, if provided if (compilationJob.Library != null) { knownVariableDeclarations.AddRange(GetDeclarationsFromLibrary(compilationJob.Library)); } var compiledTrees = new List <(string name, IParseTree tree)>(); // First pass: parse all files, generate their syntax trees, // and figure out what variables they've declared var stringTableManager = new StringTableManager(); foreach (var file in compilationJob.Files) { var tree = ParseSyntaxTree(file); compiledTrees.Add((file.FileName, tree)); RegisterStrings(file.FileName, stringTableManager, tree); } if (compilationJob.CompilationType == CompilationJob.Type.StringsOnly) { // Stop at this point return(new CompilationResult { Declarations = null, ContainsImplicitStringTags = stringTableManager.ContainsImplicitStringTags, Program = null, StringTable = stringTableManager.StringTable, }); } var fileTags = new Dictionary <string, IEnumerable <string> >(); foreach (var parsedFile in compiledTrees) { GetDeclarations(parsedFile.name, parsedFile.tree, knownVariableDeclarations, out var newDeclarations, out var newFileTags); derivedVariableDeclarations.AddRange(newDeclarations); knownVariableDeclarations.AddRange(newDeclarations); fileTags.Add(parsedFile.name, newFileTags); } foreach (var parsedFile in compiledTrees) { var checker = new TypeCheckVisitor(parsedFile.name, knownVariableDeclarations); checker.Visit(parsedFile.tree); derivedVariableDeclarations.AddRange(checker.NewDeclarations); knownVariableDeclarations.AddRange(checker.NewDeclarations); } if (compilationJob.CompilationType == CompilationJob.Type.DeclarationsOnly) { // Stop at this point return(new CompilationResult { Declarations = derivedVariableDeclarations, ContainsImplicitStringTags = false, Program = null, StringTable = null, FileTags = fileTags, }); } foreach (var parsedFile in compiledTrees) { CompilationResult compilationResult = GenerateCode(parsedFile.name, knownVariableDeclarations, compilationJob, parsedFile.tree, stringTableManager); results.Add(compilationResult); } var finalResult = CompilationResult.CombineCompilationResults(results, stringTableManager); // Last step: take every variable declaration we found in all // of the inputs, and create an initial value registration for // it. foreach (var declaration in knownVariableDeclarations) { // We only care about variable declarations here if (declaration.DeclarationType != Declaration.Type.Variable) { continue; } Operand value; if (declaration.DeclarationType == Declaration.Type.Variable && declaration.defaultValue == null) { throw new NullReferenceException($"Variable declaration {declaration.name} ({declaration.ReturnType}) has a null default value. This is not allowed."); } switch (declaration.ReturnType) { case Yarn.Type.Number: value = new Operand(Convert.ToSingle(declaration.DefaultValue)); break; case Yarn.Type.String: value = new Operand(Convert.ToString(declaration.DefaultValue)); break; case Yarn.Type.Bool: value = new Operand(Convert.ToBoolean(declaration.DefaultValue)); break; default: throw new ArgumentOutOfRangeException($"Cannot create an initial value for type {declaration.ReturnType}"); } finalResult.Program.InitialValues.Add(declaration.Name, value); } finalResult.Declarations = derivedVariableDeclarations; finalResult.FileTags = fileTags; return(finalResult); }
public virtual Microsoft.CodeAnalysis.SyntaxTree OnTranslate(VSGraphModel graphModel, AssemblyType assemblyType, CompilationOptions compilationOptions, ref CompilationResult compilationResult) { const string windowsLineEndings = "\r\n"; const string unixLineEndings = "\n"; Microsoft.CodeAnalysis.SyntaxTree syntaxTree = Translate(graphModel, compilationOptions); // we will measure plugins time later string preferredLineEndings; LineEndingsMode lineEndingsForNewScripts = EditorSettings.lineEndingsForNewScripts; switch (lineEndingsForNewScripts) { case LineEndingsMode.OSNative: preferredLineEndings = Application.platform == RuntimePlatform.WindowsEditor ? windowsLineEndings : unixLineEndings; break; case LineEndingsMode.Unix: preferredLineEndings = unixLineEndings; break; case LineEndingsMode.Windows: preferredLineEndings = windowsLineEndings; break; default: preferredLineEndings = unixLineEndings; break; } var adHocWorkspace = new AdhocWorkspace(); var options = adHocWorkspace.Options .WithChangedOption(CSharpFormattingOptions.NewLineForMembersInObjectInit, true) .WithChangedOption(CSharpFormattingOptions.WrappingPreserveSingleLine, false) .WithChangedOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, false) .WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, true) .WithChangedOption(FormattingOptions.NewLine, LanguageNames.CSharp, preferredLineEndings); string codeText = Formatter.Format(syntaxTree.GetCompilationUnitRoot(), adHocWorkspace, options).GetText().ToString(); compilationResult.sourceCode[(int)SourceCodePhases.Initial] = codeText; return(syntaxTree); }
public virtual void OnValidate(VSGraphModel graphModel, AssemblyType assemblyType, CompilationOptions compilationOptions, ref CompilationResult results) { }
/// <summary> /// Perform the actual compilation of the scripts /// Things to note here: /// * The generated assembly reference the Castle.MonoRail.MonoRailBrail and Castle.MonoRail.Framework assemblies /// * If a common scripts assembly exist, it is also referenced /// * The AddBrailBaseClassStep compiler step is added - to create a class from the view's code /// * The ProcessMethodBodiesWithDuckTyping is replaced with ReplaceUknownWithParameters /// this allows to use naked parameters such as (output context.IsLocal) without using /// any special syntax /// * The FixTryGetParameterConditionalChecks is run afterward, to transform "if ?Error" to "if not ?Error isa IgnoreNull" /// * The ExpandDuckTypedExpressions is replace with a derived step that allows the use of Dynamic Proxy assemblies /// * The IntroduceGlobalNamespaces step is removed, to allow to use common variables such as /// date and list without accidently using the Boo.Lang.BuiltIn versions /// </summary> /// <param name="files"></param> /// <param name="name"></param> /// <param name="viewname"> </param> /// <returns></returns> private CompilationResult DoCompile(IEnumerable<ICompilerInput> files, string name,string viewname) { var boomode = false; var filesAsArray = new List<ICompilerInput>(files).ToList(); var firstcode = files.First().Open().ReadToEnd(); var firstname = files.First().Name; filesAsArray.RemoveAt(0); filesAsArray.Insert(0, new StringInput(firstname, firstcode)); boomode = has_boo_only_mode(firstcode); if(boomode) { if(options.CollectStatistics) { Statistics.IsBoo(viewname); } } BooCompiler compiler = SetupCompiler(filesAsArray, boomode); string filename = Path.Combine(baseSavePath, name); compiler.Parameters.OutputAssembly = filename; // this is here and not in SetupCompiler since CompileCommon is also // using SetupCompiler, and we don't want reference to the old common from the new one /*if (common != null) { compiler.Parameters.References.Add(common); }*/ // pre procsssor needs to run before the parser var processor = new BrailPreProcessor(this, boomode); compiler.Parameters.Pipeline.Insert(0, processor); // inserting the add class step after the parser compiler.Parameters.Pipeline.Insert(2, new MONORAILTransformToBrailStep(options)); #if !LIB2 if (boomode) { compiler.Parameters.Pipeline.InsertAfter(typeof(Boo.Lang.Parser.BooParsingStep), new ExpandBmlStep()); compiler.Parameters.Pipeline.InsertAfter(typeof(Boo.Lang.Parser.BooParsingStep), new IncludeAstMacroExpandStep()); } else { compiler.Parameters.Pipeline.InsertAfter(typeof(Boo.Lang.Parser.WSABooParsingStep), new ExpandBmlStep()); compiler.Parameters.Pipeline.InsertAfter(typeof(Boo.Lang.Parser.WSABooParsingStep), new IncludeAstMacroExpandStep()); } #else if (boomode) { compiler.Parameters.Pipeline.InsertAfter(typeof(Boo.Lang.Parser.BooParsingStep), new ExpandBmlStep()); compiler.Parameters.Pipeline.InsertAfter(typeof(Boo.Lang.Parser.BooParsingStep), new IncludeAstMacroExpandStep()); } else { compiler.Parameters.Pipeline.InsertAfter(typeof(Boo.Lang.Parser.WSABooParsingStep), new ExpandBmlStep()); compiler.Parameters.Pipeline.InsertAfter(typeof(Boo.Lang.Parser.WSABooParsingStep), new IncludeAstMacroExpandStep()); } #endif compiler.Parameters.Pipeline.Replace(typeof(ProcessMethodBodiesWithDuckTyping), new ReplaceUknownWithParameters()); compiler.Parameters.Pipeline.Replace(typeof(ExpandDuckTypedExpressions), new ExpandDuckTypedExpressions_WorkaroundForDuplicateVirtualMethods()); #if !LIB2 compiler.Parameters.Pipeline.Replace(typeof(InitializeTypeSystemServices), new InitializeCustomTypeSystem()); #endif compiler.Parameters.Pipeline.InsertBefore(typeof(MacroAndAttributeExpansion), new FixTryGetParameterConditionalChecks()); compiler.Parameters.Pipeline.RemoveAt(compiler.Parameters.Pipeline.Find(typeof(IntroduceGlobalNamespaces))); //compiler.Parameters.Pipeline.InsertBefore(typeof (EmitAssembly), new PrintBoo()); var result = new CompilationResult(compiler.Run(), processor); if (options.SaveBooResult && HttpContext.Current!=null) { if (!string.IsNullOrEmpty(options.SaveBooResultDirectory)) { var dir = HttpContext.Current.Server.MapPath(options.SaveBooResultDirectory); Directory.CreateDirectory(dir); var file = Path.Combine( dir ,"last_boo.txt"); File.WriteAllText(file, result.Context.CompileUnit.ToCodeString()); } } return result; }
public Compilation(Solution solution) { Status = CompilationStatus.NotStarted; Result = CompilationResult.None; m_solution = solution; }
public void CreateScene() { // SwapChain description // Параметры SwapChain, описание смотри ниже var desc = new SwapChainDescription { BufferCount = 1, ModeDescription = new ModeDescription(_form.ClientSize.Width, _form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = _form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // создаем SwapChain - набор буферов для отрисовки // эти буферы необходимы для того, чтобы синхронизировать монитор и конвеер. // Дело в том, безопасно обновлять изображение на мониторе можно только после того, как // будет выведено предидущие изображение. SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out _device, out _swapChain); _context = _device.ImmediateContext; // Ignore all windows events _factory = _swapChain.GetParent<Factory>(); _factory.MakeWindowAssociation(_form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer // получаем один буферов из SwapChain. // Это фоновый буфер, куда отрисовывается следующие изображение в то время как на экран выводится текущее. _backBuffer = Texture2D.FromSwapChain<Texture2D>(_swapChain, 0); _renderView = new RenderTargetView(_device, _backBuffer); // Compile Vertex and Pixel shaders // Читаем из файла шейдер: небольшую подпрограммку для GPU. Vertex shader это вершинный шейдер - подпрограммка // которая принимает на вход матрицу описывающую положение вершины (точки) в пространстве // точка входа функция VS // vs_4_0 - профиль шейдера, по сути версия шейдера. Видеокарты поддерживают _vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0"); _vertexShader = new VertexShader(_device, _vertexShaderByteCode); // Тоже самое с писсельным шейдером, только имя точки входа тут PS _pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0"); _pixelShader = new PixelShader(_device, _pixelShaderByteCode); // Layout from VertexShader input signature // Описываем вход стадии InputAssembler, а имеено вершинный шейдер и те данные (которые возьмутся из буфера вершин (см. ниже) которые пойдут на вход этой стадии) _layout = new InputLayout(_device, ShaderSignature.GetInputSignature(_vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); _result = (from x in Enumerable.Range(0, _sceneDescription.PartHeight) from y in Enumerable.Range(0, _sceneDescription.PartWidth) from plane in _sceneDescription.Planes let rect = _sceneDescription.GetQuadrilateralByPosition(plane, x, y) let colorIndex = x * _sceneDescription.PartWidth + y let color = plane.Colors[colorIndex] select new[] { ToVector4(rect.BottomLeft), ToVector4(color), ToVector4(rect.TopLeft), ToVector4(color), ToVector4(rect.TopRight), ToVector4(color), ToVector4(rect.TopRight), ToVector4(color), ToVector4(rect.BottomRight), ToVector4(color), ToVector4(rect.BottomLeft), ToVector4(color), }) .SelectMany(_ => _) .ToArray(); // Instantiate Vertex buiffer from vertex data // Буфер с описанием вершин ХАРДКОР _vertices = SharpDX.Direct3D11.Buffer.Create(_device, BindFlags.VertexBuffer, _result); // Create Constant Buffer // буфер констант. Используется для передачи данных между оперативной памятью и памятью видеокарты _constantBuffer = new SharpDX.Direct3D11.Buffer(_device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // Create Depth Buffer & View // Буфер глубины он же Z буфер var depthBuffer = new Texture2D(_device, new Texture2DDescription { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = _form.ClientSize.Width, Height = _form.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); _depthView = new DepthStencilView(_device, depthBuffer); // Prepare All the stages // Вот тут устанавливаются параметры конвеера, от начальной фазы до конечной _context.InputAssembler.InputLayout = _layout; // Веселая функция, определяет какие примитивы будут отрисованы (триугольники ил линии, иль еще чего нибудь) _context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; _context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_vertices, Utilities.SizeOf<Vector4>() * 2, 0)); _context.VertexShader.SetConstantBuffer(0, _constantBuffer); _context.VertexShader.Set(_vertexShader); _context.Rasterizer.SetViewports(new Viewport(0, 0, _form.ClientSize.Width, _form.ClientSize.Height, 0.0f, 1.0f)); _context.PixelShader.Set(_pixelShader); // Треугольники должны быть видимы в обеих сторон var rastStage = RasterizerStateDescription.Default(); rastStage.CullMode = CullMode.None; var rs = new RasterizerState(_context.Device, rastStage); _context.Rasterizer.State = rs; }
/// <summary> /// Creates a new instance of the class. /// </summary> public SyntaxValidationVisitor(SyntaxValidatorProvider provider, CompilationResult result) { _provider = provider; _result = result; }
public ActionResult Execute(string notification) { var project = Session["project"] as IRuntimeProject; if (project == null) return HttpNotFound(); //td: right error dynamic clientData; var errors = project.run(new HubNotifier(notification), out clientData); var result = new CompilationResult(errors, clientData); return Json(result, JsonRequestBehavior.AllowGet); }
protected void AfterRootBuild(ProjectGraphNode projectNode, CompilationResult result) { if (result != CompilationResult.IncrementalSkip && projectNode.IsRoot) { var success = result == CompilationResult.Success; if (success) { MakeRunnable(projectNode); } PrintSummary(projectNode, success); } }
public void OnCompilationDone(VSGraphModel vsGraphModel, CompilationOptions options, CompilationResult results) { if (!this) { // Should not happen, but it did, so... Debug.LogWarning("A destroyed VseWindow still has an OnCompilationDone callback registered."); return; } State state = m_Store.GetState(); VseUtility.UpdateCodeViewer(show: false, sourceIndex: SourceCodePhases.Initial, compilationResult: results, selectionDelegate: lineMetadata => { if (lineMetadata == null) { return; } GUID nodeGuid = (GUID)lineMetadata; m_Store.Dispatch(new PanToNodeAction(nodeGuid)); }); //TODO: incremental re-register m_PluginRepository.RegisterPlugins(options); UpdateCompilationErrorsDisplay(state); if (results != null && results.errors.Count == 0) { // TODO : Add delegate to register to compilation Done // VSCompilationService.NotifyChange((ISourceProvider)vsGraphModel.assetModel); } }
protected override void Import(ModuleImporter importer, CompilationResult result) => importer.Import(result.RawFile, result.DebugFile, ModuleImporterOptions.ReplaceModuleAssemblyAttributes | ModuleImporterOptions.ReplaceAssemblyDeclSecurities);
/// <summary> /// To show the result of the compilation. /// </summary> /// <param name="result">The result of the compilation.</param> /// <param name="isRunning">Whether the previously compiled code launched in the current moment.</param> public void ShowCompilationResult(CompilationResult result, bool isRunning) { if (result == null) throw new ArgumentNullException(nameof(result)); _errorsSource.Clear(); _errorsSource.AddRange(result.Errors.Select(error => new CompileResultItem { Type = error.Type, Line = error.NativeError.Line, Column = error.NativeError.Column, Message = error.NativeError.ErrorText, })); if (_errorsSource.All(e => e.Type != CompilationErrorTypes.Error)) { if (isRunning) { _errorsSource.Add(new CompileResultItem { Type = CompilationErrorTypes.Warning, Message = LocalizedStrings.Str1420 }); } _errorsSource.Add(new CompileResultItem { Type = CompilationErrorTypes.Info, Message = LocalizedStrings.Str1421 }); } }
CompilationResult CheckSemanticModel(Microsoft.CodeAnalysis.SyntaxTree syntaxTree, string sourceFilePath, AssemblyType assemblyType, CompilationResult compilationResult) { SemanticModel semanticModel = GetSemanticModel(syntaxTree); // run all the semantic code analyzers var diagnostics = new List <CompilerError>(); Profiler.BeginSample("GetDiagnostics"); ImmutableArray <Diagnostic> rawDiagnostics = semanticModel.GetDiagnostics(); Profiler.EndSample(); Profiler.BeginSample("ProcessDiagnostics"); ProcessDiagnostics(rawDiagnostics, diagnostics); Profiler.EndSample(); Profiler.BeginSample("Format"); var codeText = syntaxTree.GetText().ToString(); compilationResult.sourceCode[(int)SourceCodePhases.Final] = codeText; Profiler.EndSample(); if (diagnostics.Any()) { compilationResult.status = CompilationStatus.Failed; compilationResult.errors = diagnostics; } else { compilationResult.status = CompilationStatus.Succeeded; } return(compilationResult); }
public bool Initialize() { Debug.Assert(!_initialized); #region Shaders string SpriteFX = @"Texture2D SpriteTex; SamplerState samLinear { Filter = MIN_MAG_MIP_LINEAR; AddressU = WRAP; AddressV = WRAP; }; struct VertexIn { float3 PosNdc : POSITION; float2 Tex : TEXCOORD; float4 Color : COLOR; }; struct VertexOut { float4 PosNdc : SV_POSITION; float2 Tex : TEXCOORD; float4 Color : COLOR; }; VertexOut VS(VertexIn vin) { VertexOut vout; vout.PosNdc = float4(vin.PosNdc, 1.0f); vout.Tex = vin.Tex; vout.Color = vin.Color; return vout; }; float4 PS(VertexOut pin) : SV_Target { return pin.Color*SpriteTex.Sample(samLinear, pin.Tex); }; technique11 SpriteTech { pass P0 { SetVertexShader( CompileShader( vs_5_0, VS() ) ); SetHullShader( NULL ); SetDomainShader( NULL ); SetGeometryShader( NULL ); SetPixelShader( CompileShader( ps_5_0, PS() ) ); } };"; #endregion _compiledFX = ShaderBytecode.Compile(SpriteFX, "SpriteTech", "fx_5_0"); { if (_compiledFX.HasErrors) return false; _effect = new Effect(_device, _compiledFX); { _spriteTech = _effect.GetTechniqueByName("SpriteTech"); _spriteMap = _effect.GetVariableByName("SpriteTex").AsShaderResource(); var pass = _spriteTech.GetPassByIndex(0).Description.Signature; InputElement[] layoutDesc = { new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0) }; _inputLayout = new InputLayout(_device, pass, layoutDesc); // Create Vertex Buffer BufferDescription vbd = new BufferDescription { SizeInBytes = 2048 * Marshal.SizeOf(typeof(SpriteVertex)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; _VB = new SharpDX.Direct3D11.Buffer(_device, vbd); // Create and initialise Index Buffer short[] indices = new short[3072]; for (ushort i = 0; i < 512; ++i) { indices[i * 6] = (short)(i * 4); indices[i * 6 + 1] = (short)(i * 4 + 1); indices[i * 6 + 2] = (short)(i * 4 + 2); indices[i * 6 + 3] = (short)(i * 4); indices[i * 6 + 4] = (short)(i * 4 + 2); indices[i * 6 + 5] = (short)(i * 4 + 3); } _indexBuffer = Marshal.AllocHGlobal(indices.Length * Marshal.SizeOf(indices[0])); Marshal.Copy(indices, 0, _indexBuffer, indices.Length); BufferDescription ibd = new BufferDescription { SizeInBytes = 3072 * Marshal.SizeOf(typeof(short)), Usage = ResourceUsage.Immutable, BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; _IB = new SharpDX.Direct3D11.Buffer(_device, _indexBuffer, ibd); BlendStateDescription transparentDesc = new BlendStateDescription() { AlphaToCoverageEnable = false, IndependentBlendEnable = false, }; transparentDesc.RenderTarget[0].IsBlendEnabled = true; transparentDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; transparentDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; transparentDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; transparentDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; transparentDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; transparentDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; transparentDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _transparentBS = new BlendState(_device, transparentDesc); } } _initialized = true; return true; }
protected override void Import(ModuleImporter importer, CompilationResult result) => importer.Import(result.RawFile, result.DebugFile, ModuleImporterOptions.None);