Example #1
0
        /// <summary>
        /// Processes a PaletteInfo object into a PaletteMaterialContent object.
        /// </summary>
        /// <param name="input">The PaletteInfo to process.</param>
        /// <param name="context">The processor context.</param>
        /// <returns>The processed PaletteMaterialContent</returns>
        public override PaletteMaterialContent Process(PaletteInfo input,
                                                       ContentProcessorContext context)
        {
#if XNA4
            throw new NotImplementedException();
#else
            // Set all the variables based on the input.
            EffectProcessor effectProcessor = new EffectProcessor();
            EffectContent   effectContent   = new EffectContent();
            effectContent.EffectCode = input.SourceCode;
            CompiledEffect compiled;
            if (context.TargetPlatform == TargetPlatform.Xbox360)
            {
                compiled = Effect.CompileEffectFromSource(
                    input.SourceCode, null, null, CompilerOptions.None, TargetPlatform.Xbox360);
            }
            else
            {
                compiled = effectProcessor.Process(effectContent, context);
            }
            PaletteMaterialContent content = new PaletteMaterialContent();
            content.PaletteSize = input.PaletteSize;
            content.ByteCode    = compiled.GetEffectCode();
            BasicMaterialContent basic = input.BasicContent;
            content.Alpha              = basic.Alpha;
            content.DiffuseColor       = basic.DiffuseColor;
            content.EmissiveColor      = basic.EmissiveColor;
            content.Name               = basic.Name;
            content.SpecularColor      = basic.SpecularColor;
            content.SpecularPower      = basic.SpecularPower;
            content.Texture            = basic.Texture;
            content.VertexColorEnabled = basic.VertexColorEnabled;
            return(content);
#endif
        }
Example #2
0
        static byte[] GetEffectCode(string filename)
        {
            var basePath       = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "Content");
            var effectFileName = System.IO.Path.Combine(basePath, filename + ".fx");

            EffectContent effectSource = new EffectContent
            {
                Identity   = new ContentIdentity(effectFileName),
                EffectCode = File.ReadAllText(effectFileName),
            };
            EffectProcessor       processor      = new EffectProcessor();
            CompiledEffectContent compiledEffect = processor.Process(effectSource, new ProcessorContext());

            return(compiledEffect.GetEffectCode());

#if DEBUG_SHADER_CODE
            // NOTE: We may need to implement a CompilerIncludeHandler here if we ever use #include in our shaders.
            var compiledEffect = Effect.CompileEffectFromFile(effectFileName, null, null, CompilerOptions.Debug, TargetPlatform.Windows);
            if (!compiledEffect.Success)
            {
                throw new InvalidOperationException(compiledEffect.ErrorsAndWarnings);
            }
            return(compiledEffect.GetEffectCode());
#else
            // We have to use a file stream instead of passing the file name directly because the latter method just botches up non-ASCII paths. :(
            //using (var effectFileStream = File.OpenRead(effectFileName))
            //{
            //    // NOTE: We may need to implement a CompilerIncludeHandler here if we ever use #include in our shaders.
            //    var compiledEffect = Effect.CompileEffectFromFile(effectFileStream, null, null, CompilerOptions.None, TargetPlatform.Windows);
            //    if (!compiledEffect.Success)
            //        throw new InvalidOperationException(compiledEffect.ErrorsAndWarnings);
            //    return compiledEffect.GetEffectCode();
            //}
#endif
        }
Example #3
0
        /// <summary>
        /// Processes a PaletteInfo object into a PaletteMaterialContent object.
        /// </summary>
        /// <param name="input">The PaletteInfo to process.</param>
        /// <param name="context">The processor context.</param>
        /// <returns>The processed PaletteMaterialContent</returns>
        public override PaletteMaterialContent Process(PaletteInfo input,
                                                       ContentProcessorContext context)
        {
            // Set all the variables based on the input.
            EffectProcessor effectProcessor = new EffectProcessor();
            EffectContent   effectContent   = new EffectContent();

            effectContent.EffectCode = input.SourceCode;
            CompiledEffect         compiled = effectProcessor.Process(effectContent, context);
            PaletteMaterialContent content  = new PaletteMaterialContent();

            content.PaletteSize = input.PaletteSize;
            content.ByteCode    = compiled.GetEffectCode();
            BasicMaterialContent basic = input.BasicContent;

            content.Alpha              = basic.Alpha;
            content.DiffuseColor       = basic.DiffuseColor;
            content.EmissiveColor      = basic.EmissiveColor;
            content.Name               = basic.Name;
            content.SpecularColor      = basic.SpecularColor;
            content.SpecularPower      = basic.SpecularPower;
            content.Texture            = basic.Texture;
            content.VertexColorEnabled = basic.VertexColorEnabled;
            return(content);
        }
Example #4
0
        internal static Effect ReadAndCompile(string filePath)
        {
            var fullPath = AssetManager.GetFullPath(filePath, ".fx");

            if (!string.IsNullOrEmpty(fullPath))
            {
                var importer        = new EffectImporter();
                var processor       = new EffectProcessor();
                var pipelineManager = new PipelineManager("", "", "")
                {
                    Profile  = Runner.Application.Game.Graphics.GraphicsProfile,
                    Platform = GetTargetPlatform()
                };

                var processorContext = new PipelineProcessorContext(
                    pipelineManager,
                    new PipelineBuildEvent());
                var content         = importer.Import(fullPath, null);
                var compiledContent = processor.Process(content, processorContext);
                var graphicsDevice  = Runner.Application.Game.GraphicsDevice;

                return(new Effect(graphicsDevice, compiledContent.GetEffectCode()));
            }

            return(null);
        }
Example #5
0
        public static Effect Compile(GraphicsDevice g, string file)
        {
            EffectImporter  ei  = new EffectImporter();
            EffectContent   ec  = ei.Import(file, new XNADynImporterContext());
            EffectProcessor ep  = new EffectProcessor();
            var             cec = ep.Process(ec, new XNADynProcessorContext());

            return(new Effect(g, cec.GetEffectCode()));
        }
Example #6
0
        /// <summary>
        /// <para>
        /// Applies the status effect to this combatant.
        /// </para>
        /// See the <see cref="Assets.Scripts.Entities.Combat.EffectProcessor"/> class for effect processing logic.
        /// </summary>
        /// <param name="statusEffect">ID for an ability status effect. see EffectProcess.cs.</param>
        /// <param name="potency">The strength or duration if applicable of the status effect</param>
        /// <param name="turnsApplied">The amount of combat turns the affect will be applied for.</param>
        public virtual void applyEffect(int statusEffect, int potency, int turnsApplied)
        {
            EffectProcessor.getInstance().applyEffect(this, statusEffect, potency, turnsApplied);
            string conditionLabel = EffectProcessor.getEffectLabel(statusEffect, potency);

            FloatingPopup.create(combatSprite.transform.position, conditionLabel, Color.blue);

            log.Debug($"<b><color=#87CEEB>[CONDITION]</color></b> -{id}:\"{name}\" has been affected with <color=#87CEEB><b>{conditionLabel}</b></color>");
        }
Example #7
0
	public ElementProcessor(AsBaseEntity _entity)
	{
		m_Owner = _entity;
		
		m_Effect = new EffectProcessor(_entity);
		m_Sound = new SoundProcessor(_entity);		
		m_Potency = new PotencyProcessor(_entity);		
		m_Buff = new BuffProcessor(_entity);
	}
Example #8
0
        static int Main(string[] args)
        {
            // Make sure we have the right number of commandline arguments.
            if (args.Length != 4)
            {
                Console.Error.WriteLine("Usage: CompileEffect <targetPlatform> <targetProfile> <input.fx> <output.bin>");
                return(1);
            }

            // Parse the commandline arguments.
            TargetPlatform targetPlatform;

            if (!Enum.TryParse(args[0], true, out targetPlatform))
            {
                Console.Error.WriteLine("Invalid target platform {0}. Valid options are {1}.", args[0], GetEnumValues <TargetPlatform>());
                return(1);
            }

            GraphicsProfile targetProfile;

            if (!Enum.TryParse(args[1], true, out targetProfile))
            {
                Console.Error.WriteLine("Invalid target profile {0}. Valid options are {1}.", args[1], GetEnumValues <GraphicsProfile>());
                return(1);
            }

            string inputFilename  = args[2];
            string outputFilename = args[3];

            try
            {
                Console.WriteLine("Compiling {0} -> {1} for {2}, {3}", Path.GetFileName(inputFilename), outputFilename, targetPlatform, targetProfile);

                ContentBuildLogger logger = new CustomLogger();

                // Import the effect source code.
                EffectImporter         importer        = new EffectImporter();
                ContentImporterContext importerContext = new CustomImporterContext(logger);
                EffectContent          sourceEffect    = importer.Import(inputFilename, importerContext);

                // Compile the effect.
                EffectProcessor         processor        = new EffectProcessor();
                ContentProcessorContext processorContext = new CustomProcessorContext(targetPlatform, targetProfile, logger);
                CompiledEffectContent   compiledEffect   = processor.Process(sourceEffect, processorContext);

                // Write out the compiled effect code.
                File.WriteAllBytes(outputFilename, compiledEffect.GetEffectCode());
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error: {0}", e.Message);
                return(1);
            }

            return(0);
        }
Example #9
0
        public static byte[] ReadBytesFromSourceFile(string fileName)
        {
            EffectImporter  importer  = new EffectImporter( );
            EffectProcessor processor = new EffectProcessor( );

            EffectContent         content  = importer.Import(fileName, new ShaderImporterContext( ));
            CompiledEffectContent compiled = processor.Process(content, new ShaderProcessorContext( ));

            return(compiled.GetEffectCode( ));
        }
Example #10
0
        public BoolEditorViewModel(string propertyName, EffectProcessor effectViewModel) : base(effectViewModel)
        {
            PropertyName      = propertyName;
            m_EffectViewModel = effectViewModel;

            EditorTemplateKey = "BoolEditorTemplate";
            if (m_EffectViewModel.Effect != null)
            {
                m_Value = Convert.ToBoolean(GetPropertyValue(PropertyName));
            }
        }
 public static CompiledEffectContent Compile(EffectContent output, string tempOutputPath, TargetPlatform platform, bool isDebug, string defines)
 {
     var processor = new EffectProcessor();
     var context = new DummyContentProcessorContext(TargetPlatformCast.ToMonoGamePlatform(platform));
     context.ActualOutputFilename = tempOutputPath;
     processor.DebugMode = isDebug
         ? EffectProcessorDebugMode.Debug
         : EffectProcessorDebugMode.Optimize;
     processor.Defines = defines + ";" + GetPlatformDefineForEffect(platform) + ";" +
                         (isDebug ? "CONFIGURATION_DEBUG" : "CONFIGURATION_RELEASE");
     return processor.Process(output, context);
 }
Example #12
0
        private static bool AttemptEffectCompilation(
            ContentProcessorContext context, StitchedEffectContent input,
            StitchedEffectSymbol stitchedEffect, ShaderProfile shaderProfile,
            out CompiledEffectContent compiledEffect)
        {
            // Generate effect code.
            StringWriter        writer        = new StringWriter();
            EffectCodeGenerator codeGenerator = new EffectCodeGenerator(stitchedEffect, shaderProfile, writer);

            codeGenerator.GenerateCode();
            string effectCode = writer.ToString();

            // Save effect code so that if there are errors, we'll be able to view the generated .fx file.
            string tempEffectFile = GetTempEffectFileName(input);

            File.WriteAllText(tempEffectFile, effectCode, Encoding.GetEncoding(1252));

            // Process effect code.
            EffectProcessor effectProcessor = new EffectProcessor
            {
                DebugMode = EffectProcessorDebugMode.Auto,
                Defines   = null
            };

            EffectContent effectContent = new EffectContent
            {
                EffectCode = effectCode,
                Identity   = new ContentIdentity(tempEffectFile),
                Name       = input.Name
            };

            try
            {
                compiledEffect = effectProcessor.Process(effectContent, context);

                // This is only needed if the compilation was successful - if it failed,
                // a more specific error message (with link to the generated file)
                // will be shown to the user.
                context.Logger.LogImportantMessage(string.Format("{0} : Stitched effect generated (double-click this message to view).", tempEffectFile));

                return(true);
            }
            catch (InvalidContentException ex)
            {
                if (ErrorIndicatesNeedForShaderModel3(ex.Message))
                {
                    compiledEffect = null;
                    return(false);
                }
                throw;
            }
        }
Example #13
0
        public static Effect CompileEffect(GraphicsDevice graphicsDevice, params string[] pathParts)
        {
            var effectProcessor = new EffectProcessor();
            var context         = new TestProcessorContext(TargetPlatform.Windows, "notused.xnb");
            var effectPath      = Paths.Effect(pathParts);
            var compiledEffect  = effectProcessor.Process(new EffectContent
            {
                EffectCode = File.ReadAllText(effectPath),
                Identity   = new ContentIdentity(effectPath)
            }, context);

            return(new Effect(graphicsDevice, compiledEffect.GetEffectCode()));
        }
Example #14
0
        public static Effect CompileEffect(GraphicsDevice graphicsDevice, params string[] pathParts)
        {
            var effectProcessor = new EffectProcessor();
            var context = new TestProcessorContext(TargetPlatform.Windows, "notused.xnb");
            var effectPath = Paths.Effect(pathParts);
            var compiledEffect = effectProcessor.Process(new EffectContent
            {
                EffectCode = File.ReadAllText(effectPath),
                Identity = new ContentIdentity(effectPath)
            }, context);

            return new Effect(graphicsDevice, compiledEffect.GetEffectCode());
        }
        public static CompiledEffectContent Compile(EffectContent output, string tempOutputPath, TargetPlatform platform, bool isDebug, string defines)
        {
            var processor = new EffectProcessor();
            var context   = new DummyContentProcessorContext(TargetPlatformCast.ToMonoGamePlatform(platform));

            context.ActualOutputFilename = tempOutputPath;
            processor.DebugMode          = isDebug
                ? EffectProcessorDebugMode.Debug
                : EffectProcessorDebugMode.Optimize;
            processor.Defines = defines + ";" + GetPlatformDefineForEffect(platform) + ";" +
                                (isDebug ? "CONFIGURATION_DEBUG" : "CONFIGURATION_RELEASE");
            return(processor.Process(output, context));
        }
        public EnumEditorViewModel(string propertyName, EffectProcessor effectViewModel, Type enumType)
        {
            m_EffectViewModel = effectViewModel;
            PropertyName      = propertyName;

            EnumValues = GetEnumValues(enumType);

            if (m_EffectViewModel.Effect != null)
            {
                m_Value = (Enum)GetPropertyValue(propertyName);
            }

            EditorTemplateKey = "EnumEditorTemplate";
        }
Example #17
0
        public static Microsoft.Xna.Framework.Graphics.Effect CompileEffect(GraphicsDevice graphicsDevice, string effectPath)
        {
#if !WINDOWS || DIRECTX || XNA
            var effectProcessor = new EffectProcessor();
            var context         = new TestProcessorContext(TargetPlatform.Windows, "notused.xnb");
            var compiledEffect  = effectProcessor.Process(new EffectContent
            {
                EffectCode = File.ReadAllText(effectPath),
                Identity   = new ContentIdentity(effectPath)
            }, context);

            return(new Microsoft.Xna.Framework.Graphics.Effect(graphicsDevice, compiledEffect.GetEffectCode()));
#else // OpenGL
            throw new NotImplementedException();
#endif
        }
Example #18
0
        private void BuildEffect(string effectFile, TargetPlatform targetPlatform)
        {
            var importerContext = new ImporterContext();
            var importer        = new EffectImporter();
            var input           = importer.Import(effectFile, importerContext);

            Assert.NotNull(input);

            var processorContext = new ProcessorContext(targetPlatform, Path.ChangeExtension(effectFile, ".xnb"));
            var processor        = new EffectProcessor();
            var output           = processor.Process(input, processorContext);

            Assert.NotNull(output);

            // TODO: Should we test the writer?
        }
Example #19
0
        static byte[] GetEffectCode(string filename)
        {
            var basePath       = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "Content");
            var effectFileName = System.IO.Path.Combine(basePath, filename + ".fx");

            var input = new EffectContent()
            {
                // Bizarrely, MonoGame loads the content from the identity's filename and ignores the EffectCode property, so we don't need to bother loading the file ourselves
                Identity = new ContentIdentity(effectFileName),
            };
            var context   = new ProcessorContext();
            var processor = new EffectProcessor();
            var effect    = processor.Process(input, context);

            return(effect.GetEffectCode());
        }
        private void BuildEffect(string effectFile, TargetPlatform targetPlatform, string defines = null)
        {
            var importerContext = new ImporterContext();
            var importer = new EffectImporter();
            var input = importer.Import(effectFile, importerContext);

            Assert.NotNull(input);

            var processorContext = new TestProcessorContext(targetPlatform, Path.ChangeExtension(effectFile, ".xnb"));
            var processor = new EffectProcessor { Defines = defines };
            var output = processor.Process(input, processorContext);

            Assert.NotNull(output);

            // TODO: Should we test the writer?
        }
Example #21
0
        public static Effect CompileEffect(GraphicsDevice graphicsDevice, params string[] pathParts)
        {
#if !WINDOWS || DIRECTX || XNA
            var effectProcessor = new EffectProcessor();
            var context = new TestProcessorContext(TargetPlatform.Windows, "notused.xnb");
            var effectPath = Paths.Effect(pathParts);
            var compiledEffect = effectProcessor.Process(new EffectContent
            {
                EffectCode = File.ReadAllText(effectPath),
                Identity = new ContentIdentity(effectPath)
            }, context);

            return new Effect(graphicsDevice, compiledEffect.GetEffectCode());
#else // OpenGL
            throw new NotImplementedException();
#endif
        }
        private void LoadByteCodeFromSource(string text)
        {
            try
            {
                EffectImporter importer = new EffectImporter();
                EffectContent effectContent = new EffectContent
                {
                    Identity = new ContentIdentity { SourceFilename = "myshader.fx" },
                    EffectCode = text,
                };

                EffectProcessor processor = new EffectProcessor();
                processor.DebugMode = EffectProcessorDebugMode.Optimize;
                CompiledEffectContent compiledEffect = processor.Process(effectContent, new FlaiProcessorContext((GraphicsProfile)_targetProfile.SelectedValue, (TargetPlatform)_targetPlatform.SelectedValue));

                byte[] bytes = compiledEffect.GetEffectCode();
                StringBuilder sb = new StringBuilder(bytes.Length * 3);

                sb.AppendLine("#region Effect Byte Code");
                sb.AppendLine();

                sb.Append("byte[] ByteCode = new byte[]").Append(Environment.NewLine).Append("{").Append(Environment.NewLine);
                for (int i = 0; i < bytes.Length;)
                {
                    sb.Append('\t');
                    int max = Math.Min(i + 8, bytes.Length);
                    for (; i < max; i++)
                    {
                        sb.Append(bytes[i]).Append(", ");
                    }

                    sb.Append(Environment.NewLine);
                }

                sb.Append("};").Append(Environment.NewLine);

                sb.AppendLine();
                sb.Append("#endregion");

                _byteCodeTextBox.Text = sb.ToString();
            }
            catch (InvalidContentException e)
            {
                _byteCodeTextBox.Text = e.Message;
            }
        }
Example #23
0
        static void Main(string[] args)
        {
            Console.Title = "Pico 3D Shader Compiler";
            Console.WriteLine(Console.Title);

            importer  = new EffectImporter( );
            processor = new EffectProcessor( );

            if (args.Length > 1)
            {
                if (args[0].EndsWith(".fx"))
                {
                    if (File.Exists(args[0]))
                    {
                        string output = args[1];

                        if (!output.EndsWith(".psf"))
                        {
                            output = (args[1] + ".psf");
                        }

                        Console.WriteLine("Compiling " + args[0]);
                        Console.WriteLine("Output: " + output);

                        byte[] effect_data = GetEffectCodeBytes(args[0]);
                        SaveBytesToFile(output, effect_data);

                        Console.WriteLine("[ Compiling OK ]");
                        effect_data = null;
                    }
                    else
                    {
                        Console.WriteLine("Input file does not exists!");
                    }
                }
                else
                {
                    Console.WriteLine("Wrong input file format!");
                }
            }
            else
            {
                Console.WriteLine("Check your input arguments.");
            }
        }
Example #24
0
        public RangeEditorViewModelEx(string propertyName, double minimum, double maximum, EffectProcessor filterViewModel, Func <T, double> getValue, Action <T, double> setValue)
        {
            Minimum = minimum;
            Maximum = maximum;

            PropertyName = propertyName;

            m_EffectViewModel = filterViewModel;

            m_GetValue = getValue;
            m_SetValue = setValue;

            EditorTemplateKey = "RangeEditorTemplate";
            if (m_EffectViewModel.Effect != null)
            {
                m_Value = m_GetValue((T)m_EffectViewModel.Effect);
            }
        }
Example #25
0
        /// <summary>
        /// The compile.
        /// </summary>
        /// <param name="asset">
        /// The asset.
        /// </param>
        /// <param name="platform">
        /// The platform.
        /// </param>
        public void Compile(EffectAsset asset, TargetPlatform platform)
        {
            if (string.IsNullOrEmpty(asset.Code))
            {
                return;
            }

            var output = new EffectContent();

            output.EffectCode = this.GetEffectPrefixCode() + asset.Code;

            var tempPath = Path.GetTempFileName();

            using (var writer = new StreamWriter(tempPath))
            {
                writer.Write(output.EffectCode);
            }

            output.Identity = new ContentIdentity(tempPath);

            var tempOutputPath = Path.GetTempFileName();

            var processor = new EffectProcessor();
            var context   = new DummyContentProcessorContext(TargetPlatformCast.ToMonoGamePlatform(platform));

            context.ActualOutputFilename = tempOutputPath;
            var content = processor.Process(output, context);

            asset.PlatformData = new PlatformData {
                Platform = platform, Data = content.GetEffectCode()
            };

            File.Delete(tempPath);
            File.Delete(tempOutputPath);

            try
            {
                asset.ReloadEffect();
            }
            catch (NoAssetContentManagerException)
            {
            }
        }
Example #26
0
        static void Main( string[] args )
        {
            Console.Title = "Pico 3D Shader Compiler";
            Console.WriteLine( Console.Title );

            importer = new EffectImporter( );
            processor = new EffectProcessor( );

            if ( args.Length > 1 ) {
                if ( args[ 0 ].EndsWith( ".fx" ) ) {
                    if ( File.Exists( args[ 0 ] ) ) {
                        string output = args[ 1 ];

                        if ( !output.EndsWith( ".psf" ) ) {
                            output = ( args[ 1 ] + ".psf" );
                        }

                        Console.WriteLine( "Compiling " + args[ 0 ] );
                        Console.WriteLine( "Output: " + output );

                        byte[] effect_data = GetEffectCodeBytes( args[ 0 ] );
                        SaveBytesToFile( output, effect_data );

                        Console.WriteLine( "[ Compiling OK ]" );
                        effect_data = null;
                    }
                    else {
                        Console.WriteLine( "Input file does not exists!" );
                    }
                }
                else {
                    Console.WriteLine( "Wrong input file format!" );
                }
            }
            else {
                Console.WriteLine( "Check your input arguments." );
            }
        }
        public override H3DMaterialContent Process(H3DMaterialContent input, ContentProcessorContext context)
        {
            context.Logger.LogMessage($"Processing H3D Effect {input.Name}");
            var tmpPath = Path.GetTempFileName();

            try
            {
                input.Effect.Identity = new ContentIdentity(tmpPath);
                File.WriteAllText(tmpPath, input.Effect.EffectCode);
                context.Logger.LogMessage($"Using temp file {tmpPath} for compilation");
                var effectProcessor = new EffectProcessor();
                input.EffectCompiled = effectProcessor.Process(input.Effect, context);

                // We don't need to do anything - the textures are imported from the binary file
                return(input);
            }
            catch (Exception ex)
            {
                context.Logger.LogMessage("Error {0}", ex);
                throw;
            }
            finally { File.Delete(tmpPath); }
        }
Example #28
0
        public IProgram Link(Shader shader, IEnumerable <object> units)
        {
            var sources = units.Cast <Tuple <ShaderType, SourceDescription> >();
            //var frag = sources.Where(t => t.Item1 == ShaderType.FragmentShader).Select(t => t.Item2);
            //var vert = sources.Where(t => t.Item1 == ShaderType.VertexShader).Select(t => t.Item2);
            var all = sources.Select(t => t.Item2);

            var merged = all.Skip(1).Aggregate(all.First(), (current, d) => current.Merge(d));


            // XNA doesnt support shader compilation so we have to generate a .fx file
            // with everything merged

            var cp = new SLContentProcessorContext();
            var ep = new EffectProcessor();
            var ec = new EffectContent {
                EffectCode = merged.ToHlslFx()
            };

            var compiledEffect = ep.Process(ec, cp);

            return(new Program(compiledEffect));
        }
Example #29
0
        public override void Load()
        {
            try
            {
                using (StreamReader reader = new StreamReader(Settings.GetLocation(typeof(Shader)) + filename))
                {
                    EffectContent effectSource = new EffectContent();

                    effectSource.Name = name;
                    effectSource.Identity = new ContentIdentity(filename);
                    effectSource.EffectCode = reader.ReadToEnd();

                    EffectProcessor processor = new EffectProcessor();
                    CompiledEffectContent compiledEffect = processor.Process(effectSource, new ProcessorContext());

                    HLSL_Shader = new Effect(Bootstrap.graphics.GraphicsDevice, compiledEffect.GetEffectCode());
                }
                this.loaded = true;
            }
            catch (System.Exception e)
            {
                Debug.LogError(e.Message);
            }
        }
Example #30
0
        public Effect?Build(GraphicsDevice device, string path)
        {
            var content = new EffectContent
            {
                Identity   = new ContentIdentity(path),
                EffectCode = File.ReadAllText(path)
            };

            var processor = new EffectProcessor();

            try
            {
                var compiled = processor.Process(content, new ProcessorContext(this.Logger, path));
                return(new Effect(device, compiled.GetEffectCode()));
            }
            catch (InvalidContentException cex)
            {
                var match = this.EffectCompilerPattern.Match(cex.Message);
                if (match.Success)
                {
                    var line    = match.Captures[0].Value;
                    var message = $"At {line}";
                    this.Logger.Error($"Failed to reload {path}\n\n{message}");
                }
                else
                {
                    this.Logger.Error(cex, "Failed to reload {@file}", path);
                }
            }
            catch (Exception ex)
            {
                this.Logger.Error(ex, "Failed to reload {@file}", path);
            }

            return(null);
        }
Example #31
0
        private static Dictionary <string, Dictionary <int, SpriteFont> > Fonts = new Dictionary <string, Dictionary <int, SpriteFont> >(); //Ref, size to font
        static void InitStatic(GraphicsControl control)
        {
            if (StaticInitialized)
            {
                return;
            }
            StaticInitialized = true;

            //Load effect

            /*
             * string code = Properties.Resources.horizontalBorderEffect;
             *
             * CompiledEffect cEffect =
             *  Effect.CompileEffectFromSource(code, null, null,
             *                                 CompilerOptions.None, TargetPlatform.Windows);
             * if (!cEffect.Success)
             *  cEffect = cEffect;
             *
             * Effect = new Effect(control.GraphicsDevice, cEffect.GetEffectCode(), CompilerOptions.None, null);
             * //Save effect code
             * byte[] effectCode = cEffect.GetEffectCode();
             * FileStream stream = File.Open("compiledEffect", FileMode.Create);
             * stream.Write(effectCode, 0, effectCode.Length);
             * stream.Close();
             * stream.Dispose();*/
            //Effect = new Effect(control.GraphicsDevice, Properties.Resources.compiledEffect, CompilerOptions.None, null);
            //byte[] ce = Properties.Resources.compiledEffect;
            //Effect = new Effect(control.GraphicsDevice, ce);

            //windywell load effect
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            string code = enc.GetString(
                util.Util.ReadAllBytes(File.Open("Effects\\Effects_ps3.0.fx", FileMode.Open))    // Properties.Resources.horizontalBorderEffect;
                );

            code = code.Remove(0, 3);
            EffectProcessor ep     = new EffectProcessor();
            var             effect = ep.Process(new EffectContent {
                EffectCode = code
            }, new CatalogContext());

            byte[] ec = effect.GetEffectCode();
            Effect = new Effect(control.GraphicsDevice, ec);

            //Load fonts
            string[] fontRefferences = new[]
            {
                @"UI\Fonts\Eurostile-Bol.otf",
                @"UI\Fonts\Eurostile-Reg.otf",
                @"UI\Fonts\EurostileExt-Med.otf",
                @"UI\Fonts\EurostileExt-Reg.otf",
                @"UI\Fonts\bl.ttf"
            };
            string[] fontNames = new[]
            {
                "FontHeader",
                "FontStandard",
                "FontHeaderExtended",
                "FontStandardExtended",
                "FontInternational"
            };
            int[] fontSizes = new[] { 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 43, 44, 47, 48, 50, 52, 56, 60, 62, 64, 68 };
            //{ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 28, 30, 32, 34, 35, 36, 38, 40, 42, 48, 50, 52, 56, 60, 62, 64, 68 };

            ContentManager contentManager = new ContentManager(control.Services);

            for (int i = 0; i < fontRefferences.Length; i++)
            {
                FontNames[fontRefferences[i]] = fontNames[i];
                Fonts[fontRefferences[i]]     = new Dictionary <int, SpriteFont>();
                foreach (int fontSize in fontSizes)
                {
                    string name = fontNames[i] + fontSize;
                    if (File.Exists("Fonts\\" + name + ".xnb"))
                    {
                        Fonts[fontRefferences[i]][fontSize] = contentManager.Load <SpriteFont>("Fonts\\" + name);
                    }
                }
            }

            //defaultTexture = new Texture2D(control.GraphicsDevice, 1, 1, true, TextureUsage.None, SurfaceFormat.Color);
            defaultTexture = new Texture2D(control.GraphicsDevice, 1, 1, true, SurfaceFormat.Color);
            defaultTexture.SetData(new[] { new Color(0.5f, 0.5f, 1, 1) });
        }
Example #32
0
        public override T Load <T>(string assetName)
        {
            var g = (IGraphicsDeviceService)ServiceProvider.GetService(typeof(IGraphicsDeviceService));

            if (typeof(T) == typeof(Texture2D))
            {
                if (_textures.ContainsKey(assetName))
                {
                    return((T)(object)_textures[assetName]);
                }

                using (var img = Image.FromFile(ContentProjectManager.GetTexturePath(assetName)))
                {
                    var bmp  = new Bitmap(img);
                    var data = new uint[bmp.Width * bmp.Height];
                    for (var y = 0; y < bmp.Height; ++y)
                    {
                        for (var x = 0; x < bmp.Width; ++x)
                        {
                            var pixel = bmp.GetPixel(x, y);
                            data[x + y * bmp.Width] =
                                Microsoft.Xna.Framework.Color.FromNonPremultiplied(pixel.R, pixel.G, pixel.B, pixel.A).
                                PackedValue;
                        }
                    }
                    if (g != null)
                    {
                        var t = new Texture2D(g.GraphicsDevice, img.Width, img.Height);
                        t.SetData(data);
                        _textures.Add(assetName, t);
                        return((T)(object)t);
                    }
                    else
                    {
                        throw new InvalidOperationException("Must wait with loading until graphics device is initialized.");
                    }
                }
            }
            else if (typeof(T) == typeof(Effect))
            {
                if (_shaders.ContainsKey(assetName))
                {
                    return((T)(object)_shaders[assetName]);
                }

                var shaderPath = ContentProjectManager.GetShaderPath(assetName);
                if (shaderPath != null)
                {
                    using (var file = File.OpenText(shaderPath))
                    {
                        var sourceCode = file.ReadToEnd();

                        var effectSource = new EffectContent
                        {
                            EffectCode = sourceCode,
                            Identity   = new ContentIdentity {
                                SourceFilename = assetName
                            }
                        };
                        var processor      = new EffectProcessor();
                        var compiledEffect = processor.Process(effectSource, new DummyProcessorContext());
                        var effect         = new Effect(g.GraphicsDevice, compiledEffect.GetEffectCode());
                        _shaders.Add(assetName, effect);
                        return((T)(object)effect);
                    }
                }
            }
            else if (typeof(T) == typeof(ParticleEffect))
            {
                using (var xmlReader = XmlReader.Create(ContentProjectManager.GetEffectPath(assetName)))
                {
                    var effect = IntermediateSerializer.Deserialize <ParticleEffect>(xmlReader, null);
                    effect.Initialise();
                    effect.LoadContent(this);
                    return((T)(object)effect);
                }
            }
            else if (typeof(T) == typeof(IFactory[]))
            {
                return((T)(object)FactoryManager.GetFactoriesFromFile(assetName).ToArray());
            }
            else if (typeof(T) == typeof(ItemPool[]))
            {
                return((T)(object)ItemPoolManager.GetItemPools().ToArray());
            }
            else if (typeof(T) == typeof(AttributePool[]))
            {
                return((T)(object)AttributePoolManager.GetAttributePools().ToArray());
            }
            return(default(T));
        }
Example #33
0
    private void initGame()
    {
        /*
         *  Initializing player
         *
         */
        player = new Player(100, 1000, 0, 100f);

        /*
         * Initializing Databases
         *
         */
        itemText   = Resources.Load("Data/Item") as TextAsset;
        recipeText = Resources.Load("Data/Recipe") as TextAsset;
        techText   = Resources.Load("Data/Technology") as TextAsset;

        ItemDatabase.init(itemText);
        RecipeDatabase.init(recipeText);
        TechnologyDatabase.init(techText);
        FieldDropDatabase.init();

        /*
         * Other Managers Initializing
         *
         * **CAUTION**
         * You must initialize managers after initializing databases, player
         * because initializing managers contain loading object, data from database, player
         * also, order of initializing managers also matters
         */

        researchManager = GetComponent <ResearchManager>();
        researchManager.init();

        // craftManager references researchManager
        craftManager = GetComponent <CraftManager>();
        craftManager.init();

        //
        boardManager = GetComponent <BoardManager>();
        boardManager.init();
        soundManager = GetComponentInChildren <SoundManager>();

        /*
         * Effect Processor Initializing
         * **CAUTION**
         * You must initialize this after all other initializing done
         */
        effectProcessor = new EffectProcessor();
        effectProcessor.init();

        ///*
        // * get Inventory
        // */

        //inventory = transform.Find("Canvas/InventoryPanel").gameObject;

        // default scene
        scene = SCENES.BASE;

        // game play variables initialize
        day            = 1;
        exploreChance  = true;
        moveChance     = true;
        researchChance = true;

        // start game
        SceneManager.LoadScene(scene);
    }
Example #34
0
        static void Main(string[] args)
        {
            Log("Effect farm compiler to efb {0}.", EFParser.EfbVersion);

            if (args.Length < 2)
            {
                Log("Usage: efc <input_file> <config_file> [output_file]");
                return;
            }

            try
            {
                var inputFile = args[0];
                if (!File.Exists(inputFile))
                {
                    Log("Could not find '0'.", inputFile);
                    return;
                }

                var configFile = args[1];
                if (!File.Exists(inputFile))
                {
                    Log("Could not find '0'.", inputFile);
                    return;
                }
                var doc = XDocument.Parse(File.ReadAllText(configFile));

                // Parse config
                var config = new Config
                {
                    Targets = ParseTargets(doc)
                };
                if (config.Targets.Length == 0)
                {
                    GenerateError("No target platforms.");
                }

                var rootEntry = (from n in doc.Descendants("RootEntry") select n).FirstOrDefault();
                if (rootEntry == null)
                {
                    GenerateError("Could not find 'RootEntry' node.");
                }

                config.Root = ParseEntry(rootEntry);

                var variants = config.BuildVariants().ToArray();

                var outputFile = string.Empty;

                if (args.Length < 3)
                {
                    outputFile = Path.ChangeExtension(inputFile, "efb");
                }
                else
                {
                    outputFile = Path.ChangeExtension(args[2], "efb");
                }

                var outputLwt = File.GetLastWriteTime(outputFile);
                if (File.Exists(outputFile) &&
                    outputLwt > File.GetLastWriteTime(inputFile) &&
                    outputLwt > File.GetLastWriteTime(configFile))
                {
                    var resultVariants = Substract(variants, outputFile);
                    if (resultVariants.Length == 0)
                    {
                        Log("{0} is up to date.", Path.GetFileName(outputFile));
                        return;
                    }
                }

                var workingFolder = Path.GetDirectoryName(inputFile);
                var includeFx     = new IncludeFX(workingFolder);

                var importerContext  = new ImporterContext();
                var processorContext = new ProcessorContext();

                var effectImporter = new EffectImporter();
                var effectProcesor = new EffectProcessor();

                Log("{0} variants of effects are going to be compiled.", variants.Length);
                using (var stream = File.Open(outputFile, FileMode.Create))
                    using (var writer = new BinaryWriter(stream))
                    {
                        writer.Write(Encoding.UTF8.GetBytes(EFParser.EfbSignature));
                        writer.Write(EFParser.EfbVersion);

                        var idx = 0;
                        foreach (var variant in variants)
                        {
                            Log("#" + idx + ": " + variant.ToString());

                            switch (variant.Platform)
                            {
                            case EFPlatform.MonoGameDirectX:
                            case EFPlatform.MonoGameOpenGL:
                            {
                                var content = effectImporter.Import(inputFile, importerContext);

                                processorContext._targetPlatform = variant.Platform == EFPlatform.MonoGameDirectX ?
                                                                   TargetPlatform.Windows : TargetPlatform.DesktopGL;
                                effectProcesor.Defines = EFVariant.BuildKey(variant.Defines);

                                var result = effectProcesor.Process(content, processorContext);

                                WriteOutput(writer, variant, result.GetEffectCode());
                            }
                            break;

                            case EFPlatform.FNA:
                            {
                                var result = ShaderBytecode.CompileFromFile(inputFile,
                                                                            "fx_2_0",
                                                                            ShaderFlags.OptimizationLevel3,
                                                                            EffectFlags.None,
                                                                            ToMacroses(variant),
                                                                            includeFx);

                                if (result.ResultCode != Result.Ok)
                                {
                                    GenerateError(result.Message);
                                }

                                WriteOutput(writer, variant, result.Bytecode);
                            }
                            break;
                            }

                            ++idx;
                        }
                    }

                Log("Compilation to {0} was succesful.", Path.GetFileName(outputFile));
            }
            catch (Exception ex)
            {
                Log(ex.ToString());
            }
        }
Example #35
0
        public void LaunchSpell(Fighter fighter, CharacterSpell spell, int cellID)
        {
            if (myState != FightState.PLAYING)
            {
                return;
            }

            Fighter firstTarget = GetAliveFighters().FirstOrDefault(x => x.Cell == cellID);
            int     targetID    = firstTarget == null ? -1 : firstTarget.ID;

            if (!CanLaunchSpell(fighter, spell, cellID, targetID))
            {
                return;
            }

            fighter.AP -= spell.LevelModel.Cost;

            bool isEchec = false;

            if (spell.LevelModel.EC != 0)
            {
                int echecRate = spell.LevelModel.EC - fighter.Stats.GetStat(StatEnum.EchecCritic).Total;

                if (echecRate < 2)
                {
                    echecRate = 2;
                }

                if (Basic.Rand(1, echecRate) == 1)
                {
                    isEchec = true;
                }
            }

            if (isEchec)
            {
                Send("GA;302;" + fighter.ID + ';' + spell.ID);
            }
            else
            {
                fighter.SpellController.OnLaunchSpell(spell, targetID);

                Send("GA;300;" + fighter.ID + ';' + spell.ID + ',' + cellID + ',' + spell.Model.Sprite + ',' + spell.Level + ',' + spell.Model.SpriteInfos);

                bool isCritic = false;

                if (spell.LevelModel.CC != 0 & spell.LevelModel.CriticalEffects.Count > 0)
                {
                    int criticRate = spell.LevelModel.CC - fighter.Stats.GetStat(StatEnum.DamageCritic).Total;

                    if (criticRate < 2)
                    {
                        criticRate = 2;
                    }

                    if (Basic.Rand(1, criticRate) == 1)
                    {
                        isCritic = true;
                    }
                }

                if (isCritic)
                {
                    Send("GA;301;" + fighter.ID + ';' + spell.ID);
                }

                List <EffectSpell> effects = isCritic ? spell.LevelModel.CriticalEffects : spell.LevelModel.Effects;
                List <Fighter>     targets = new List <Fighter>();

                foreach (int cell in CellZone.GetCells(myMap, cellID, fighter.Cell, spell.LevelModel.Type))
                {
                    Fighter target = GetAliveFighters().FirstOrDefault(x => x.Cell == cell);

                    if (target != null)
                    {
                        targets.Add(target);
                    }
                }

                int actualChance = 0;

                foreach (EffectSpell effect in effects)
                {
                    if (effect.Chance > 0)
                    {
                        if (Basic.Rand(1, 100) > effect.Chance + actualChance)
                        {
                            actualChance += effect.Chance;
                            continue;
                        }

                        actualChance -= 100;
                    }

                    targets.RemoveAll(x => x.Dead);

                    EffectProcessor.ApplyEffect(new EffectCast
                                                    ((EffectEnum)effect.ID, spell.ID, cellID, effect.Value, effect.Value2, effect.Value3, effect.Chance, effect.Round, (spell.LevelModel.MinRP == 1 & spell.LevelModel.MaxRP == 1), fighter, effect.Target.RemixTargets(fighter, targets)));
                }
            }

            Send("GA;102;" + fighter.ID + ';' + fighter.ID + ",-" + spell.LevelModel.Cost);

            if (GetWinners() != null)
            {
                FightEnd(GetWinners(), GetEnnemyTeam(GetWinners()));
            }
            else if (isEchec & spell.LevelModel.isECEndTurn)
            {
                TurnEnd();
            }
        }
Example #36
0
 public void TearDown()
 {
     _instance = null;
 }
        protected virtual void ProcessMaterial(MaterialContent input, 
            MaterialContent output, ContentProcessorContext context)
        {
            BasicMaterialContent basicMaterial = input as BasicMaterialContent;

            if (basicMaterial != null)
            {
                if (output is SkinnedModelMaterialContent)
                {
                    SkinnedModelMaterialContent skinnedModelMaterial = output as SkinnedModelMaterialContent;

                    skinnedModelMaterial.EmissiveColor = basicMaterial.EmissiveColor.GetValueOrDefault(
                        Vector3.Zero);
                    skinnedModelMaterial.DiffuseColor = basicMaterial.DiffuseColor.GetValueOrDefault(
                        Vector3.One);
                    skinnedModelMaterial.SpecularColor = basicMaterial.SpecularColor.GetValueOrDefault(
                        Vector3.One);
                    skinnedModelMaterial.SpecularPower = basicMaterial.SpecularPower.GetValueOrDefault(
                        16);

                    EffectContent effectContent = new EffectContent();
                    effectContent.EffectCode = Resources.SkinnedModelEffect;

                    EffectProcessor effectProcessor = new EffectProcessor();
                    skinnedModelMaterial.SkinnedEffectContent = effectProcessor.Process(effectContent, context);
                }
                else if (output is SkinnedMaterialContent)
                {
                    SkinnedMaterialContent skinnedModelMaterial = output as SkinnedMaterialContent;

                    skinnedModelMaterial.EmissiveColor = basicMaterial.EmissiveColor.GetValueOrDefault(
                        Vector3.Zero);
                    skinnedModelMaterial.DiffuseColor = basicMaterial.DiffuseColor.GetValueOrDefault(
                        Vector3.One);
                    skinnedModelMaterial.SpecularColor = basicMaterial.SpecularColor.GetValueOrDefault(
                        Vector3.One);
                    skinnedModelMaterial.SpecularPower = basicMaterial.SpecularPower.GetValueOrDefault(
                        16);
                }
            }
        }
        public static Task <List <IImageProcessor> > CreateEffects()
        {
            // This seems to take 150-200 ms minimum, so better do it on the thread pool.
            return(Task.Run(async() =>
            {
                var imageProcessors = new List <IImageProcessor>();
                EffectProcessor effectViewModel = null;

                var source = await PreloadedImages.Man;

                imageProcessors.Add(new EffectProcessor("Antique", new AntiqueEffect()));
                imageProcessors.Add(new EffectProcessor("Auto Enhance", new AutoEnhanceEffect()));
                imageProcessors.Add(new EffectProcessor("Auto Levels", new AutoLevelsEffect()));
                imageProcessors.Add(new BlendEffectProcessor());
                imageProcessors.Add(new EffectProcessor("Blur", new BlurEffect()));
                imageProcessors.Add(new EffectProcessor("Brightness Effect", new BrightnessEffect()));
                imageProcessors.Add(new EffectProcessor("Cartoon", new CartoonEffect()));
                imageProcessors.Add(new EffectProcessor("ChromaKey", new ChromaKeyEffect()));
                imageProcessors.Add(new EffectProcessor("ColorAdjust", new ColorAdjustEffect()));
                imageProcessors.Add(new EffectProcessor("ColorBoost", new ColorBoostEffect(1.0)));
                imageProcessors.Add(new EffectProcessor("Colorization", new ColorizationEffect()));
                imageProcessors.Add(new EffectProcessor("Color Swap", new ColorSwapEffect(Windows.UI.Color.FromArgb(255, 255, 0, 0), Windows.UI.Color.FromArgb(255, 0, 255, 0), 0.8, false, true)));
                imageProcessors.Add(new EffectProcessor("Contrast", new ContrastEffect(0.5)));
                imageProcessors.Add(new CropEffectProcessor());
                imageProcessors.Add(new CurveProcessor());
                imageProcessors.Add(new EffectProcessor("Despeckle", new DespeckleEffect(DespeckleLevel.Low)));
                imageProcessors.Add(new EffectProcessor("Emboss", new EmbossEffect(0.5)));
                imageProcessors.Add(new EffectProcessor("Exposure", new ExposureEffect(ExposureMode.Natural, 0.5)));
                imageProcessors.Add(new EffectProcessor("Flip", new FlipEffect(FlipMode.Both)));
                imageProcessors.Add(new EffectProcessor("Fog", new FogEffect()));
                imageProcessors.Add(new EffectProcessor("Foundation", new FoundationEffect()));
                imageProcessors.Add(new EffectProcessor("GaussianNoise", new GaussianNoiseEffect(1.0)));

                var gradient = new RadialGradient(new Point(0.5, 0.5), new EllipseRadius(0.5, 0.5));
                gradient.Stops = new[]
                {
                    new GradientStop {
                        Offset = 0.0, Color = Colors.Red
                    },
                    new GradientStop {
                        Offset = 1.0, Color = Colors.Cyan
                    }
                };

                var gradientImageSource = new GradientImageSource(new Size(800, 500), gradient);

                imageProcessors.Add(new EffectProcessor("Grayscale", new GrayscaleEffect()));
                imageProcessors.Add(new EffectProcessor("Grayscale Negative", new GrayscaleNegativeEffect()));
                imageProcessors.Add(new HSLProcessor());
                imageProcessors.Add(new EffectProcessor("HdrEffect", new HdrEffect()));
                imageProcessors.Add(new EffectProcessor("HueSaturationEffect", new HueSaturationEffect()));

                effectViewModel = new EffectProcessor("Levels", new LevelsEffect(), true, true);
                {
                    RangeEditorViewModelEx <LevelsEffect> blackEditor = null;
                    RangeEditorViewModelEx <LevelsEffect> grayEditor = null;
                    RangeEditorViewModelEx <LevelsEffect> whiteEditor = null;

                    blackEditor = new RangeEditorViewModelEx <LevelsEffect>(
                        "Black",
                        0.0,
                        1.0,
                        effectViewModel,
                        effect => effect.Black,
                        (effect, value) =>
                    {
                        effect.Black = value;
                        if (grayEditor.Value < value)
                        {
                            grayEditor.Value = value;
                        }
                        if (whiteEditor.Value < value)
                        {
                            whiteEditor.Value = value;
                        }
                    });

                    grayEditor = new RangeEditorViewModelEx <LevelsEffect>(
                        "Gray",
                        0.0,
                        1.0,
                        effectViewModel,
                        effect => effect.Gray,
                        (effect, value) =>
                    {
                        effect.Gray = value;
                        if (blackEditor.Value > value)
                        {
                            blackEditor.Value = value;
                        }
                        if (whiteEditor.Value < value)
                        {
                            whiteEditor.Value = value;
                        }
                    });

                    whiteEditor = new RangeEditorViewModelEx <LevelsEffect>(
                        "White",
                        0.0,
                        1.0,
                        effectViewModel,
                        effect => effect.White,
                        (effect, value) =>
                    {
                        effect.White = value;
                        if (blackEditor.Value > value)
                        {
                            blackEditor.Value = value;
                        }
                        if (grayEditor.Value > value)
                        {
                            grayEditor.Value = value;
                        }
                    });

                    effectViewModel.Editors.Add(blackEditor);
                    effectViewModel.Editors.Add(grayEditor);
                    effectViewModel.Editors.Add(whiteEditor);
                }
                imageProcessors.Add(effectViewModel);
                imageProcessors.Add(new LinearGradientImageSourceEffectProcessor());
                imageProcessors.Add(new EffectProcessor("Local Boost Automatic", new LocalBoostAutomaticEffect(8)));
                imageProcessors.Add(new EffectProcessor("LocalBoost", new LocalBoostEffect()));
                imageProcessors.Add(new EffectProcessor("Lomo", new LomoEffect()));
                imageProcessors.Add(new EffectProcessor("Magic Pen", new MagicPenEffect()));
                imageProcessors.Add(new EffectProcessor("Milky", new MilkyEffect()));
                imageProcessors.Add(new EffectProcessor("Mirror", new MirrorEffect()));
                imageProcessors.Add(new EffectProcessor("Mono Color", new MonoColorEffect(Windows.UI.Color.FromArgb(255, 255, 0, 0), 0.8)));
                imageProcessors.Add(new EffectProcessor("Moonlight", new MoonlightEffect(21)));
                imageProcessors.Add(new EffectProcessor("Negative", new NegativeEffect()));
                imageProcessors.Add(new EffectProcessor("Noise", new NoiseEffect(NoiseLevel.Maximum)));
                imageProcessors.Add(new EffectProcessor("Oily", new OilyEffect(OilBrushSize.Medium)));
                imageProcessors.Add(new EffectProcessor("Paint", new PaintEffect(4)));
                imageProcessors.Add(new EffectProcessor("Posterize", new PosterizeEffect(10)));
                imageProcessors.Add(new RadialGradientImageSourceEffectProcessor());
                imageProcessors.Add(new ReframingEffectProcessor());
                imageProcessors.Add(new EffectProcessor("Rotation", new RotationEffect()));
                imageProcessors.Add(new RgbLevelsEffectProcessor());
                imageProcessors.Add(new RgbMixerEffectProcessor());
                imageProcessors.Add(new SaturationLightnessProcessor());
                imageProcessors.Add(new EffectProcessor("Sharpness", new SharpnessEffect(0.2)));
                imageProcessors.Add(new EffectProcessor("Sepia", new SepiaEffect()));
                imageProcessors.Add(new EffectProcessor("Sketch", new Lumia.Imaging.Artistic.SketchEffect(SketchMode.Color)));
                imageProcessors.Add(new EffectProcessor("Solarize", new SolarizeEffect(0.8)));
                imageProcessors.Add(new SplitToneEffectProcessor());
                imageProcessors.Add(new SpotlightEffectProcessor());
                imageProcessors.Add(new EffectProcessor("Stamp", new StampEffect(5, 200.0 / 255.0)));
                imageProcessors.Add(new EffectProcessor("Temperature and Tint", new TemperatureAndTintEffect(50.0 / 255.0, 50.0 / 255.0)));
                imageProcessors.Add(new EffectProcessor("Vibrance", new VibranceEffect()));
                imageProcessors.Add(new EffectProcessor("Vignetting", new VignettingEffect(0.8, Windows.UI.Color.FromArgb(255, 255, 0, 0))));
                imageProcessors.Add(new EffectProcessor("Watercolor", new WatercolorEffect(0.8, 0.8)));
                imageProcessors.Add(new EffectProcessor("Warping", new WarpingEffect(WarpMode.Twister, 0.8)));
                imageProcessors.Add(new EffectProcessor("White Balance", new WhiteBalanceEffect(WhitePointCalculationMode.Maximum, Color.FromArgb(1, 219, 213, 199))));
                imageProcessors.Add(new EffectProcessor("Whiteboard Enhancement", new WhiteboardEnhancementEffect(WhiteboardEnhancementMode.Hard), canRenderAtPreviewSize: false));

                //GlamMe effects
                imageProcessors.Add(new BWEffect());
                imageProcessors.Add(new ElegantEffect());
                imageProcessors.Add(new RetroEffect());
                imageProcessors.Add(new VintageEffect());
                imageProcessors.Add(new MintEffect());
                imageProcessors.Add(new OldPosterEffect());
                imageProcessors.Add(new LensBlureSampleEffect());
                imageProcessors.Add(new GlamMeLomoEffect());
                imageProcessors.Add(new FreshEffect());
                imageProcessors.Add(new LightEffect());

                // Creative Studio Effects
                imageProcessors.Add(new BWloEffect());
                imageProcessors.Add(new IndoorEffect());
                imageProcessors.Add(new SunsetEffect());
                imageProcessors.Add(new BWHiEffect());
                imageProcessors.Add(new BWCopperEffect());
                imageProcessors.Add(new LoSatWarmEffect());

                //       imageProcessors.Add(new BlockTiltDoF());
                //       imageProcessors.Add(new EllipseTiltDoF());
                //       imageProcessors.Add(new LandscapeBackgroundDoF());
                //         imageProcessors.Add(new LensBlurProcessor()); // Special command editor

                return imageProcessors;
            }));
        }
Example #39
0
        public override EffectBinary Process(EffectSourceCode input, ContentProcessorContext context)
        {
            // Remove comments
            Regex  commentRegex = new Regex("//.*$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            string effectCode   = commentRegex.Replace(input.EffectCode, "");

            // Remove carriage returns and line feeds
            commentRegex = new Regex(@"(\r\n)|\n", RegexOptions.IgnoreCase);
            effectCode   = commentRegex.Replace(effectCode, "");

            // Check effect validity
            // EffectProcessor should check almost all potential errors in the effect code
            EffectContent content = new EffectContent {
                EffectCode = effectCode
            };
            EffectProcessor compiler = new EffectProcessor {
                DebugMode = EffectProcessorDebugMode.Auto
            };

            compiler.Process(content, context);

            // If we are here, the effect is assumed to be ok!

            // Extract techniques
            IEnumerable <EffectTechnique> techniques = ExtractTechniques(effectCode);

            // Now we have to find entry points for each pass and compile them
            Compiler     helper = new Compiler();
            EffectBinary result = new EffectBinary();

            foreach (var technique in techniques)
            {
                EffectTechniqueBinary effectTechniqueBinary = new EffectTechniqueBinary {
                    Name = technique.Name
                };

                foreach (var pass in technique.Passes)
                {
                    List <string> errors = new List <string>();

                    // Compiling vertex shader
                    CompilerResult vsResult = helper.Process(effectCode, errors, "vs_2_0", pass.VertexShaderEntryPoint, 3, false, true);

                    // This should not happen but...
                    if (errors.Count > 0)
                    {
                        ExceptionHelper.RaiseException(String.Join("\n", errors));
                    }

                    // Compiling pixel shader
                    CompilerResult psResult = helper.Process(effectCode, errors, "ps_2_0", pass.PixelShaderEntryPoint, 3, false, true);

                    // This should not happen but...
                    if (errors.Count > 0)
                    {
                        ExceptionHelper.RaiseException(String.Join("\n", errors));
                    }

                    // Generating a pass binary
                    EffectPassBinary passBinary = new EffectPassBinary
                    {
                        Name                   = pass.Name,
                        RenderStates           = pass.RenderStates,
                        VertexShaderByteCode   = vsResult.ShaderCode,
                        VertexShaderParameters = Encoding.Unicode.GetBytes(vsResult.ConstantsDefinition),
                        PixelShaderByteCode    = psResult.ShaderCode,
                        PixelShaderParameters  = Encoding.Unicode.GetBytes(psResult.ConstantsDefinition)
                    };

                    effectTechniqueBinary.PassBinaries.Add(passBinary);
                }

                result.TechniquesBinaries.Add(effectTechniqueBinary);
            }

            return(result);
        }