Пример #1
0
        private static void SetupKernel(IKernel kernel)
        {
            kernel.Load <ProtogameAssetModule>();
            kernel.Load <ProtogameScriptIoCModule>();
            var services            = new GameServiceContainer();
            var assetContentManager = new AssetContentManager(services);

            kernel.Bind <IAssetContentManager>().ToMethod(x => assetContentManager);
            kernel.Bind <IRenderBatcher>().To <NullRenderBatcher>();
            kernel.Bind <ICoroutineScheduler>().To <DefaultCoroutineScheduler>().InSingletonScope();
            kernel.Bind <ICoroutine>().To <DefaultCoroutine>();
            kernel.Bind <IConsole>().To <ServerConsole>().InSingletonScope();
            kernel.Bind <IConsoleHandle>().To <DefaultConsoleHandle>().InParentScope();

            // Only allow source and raw load strategies.
            kernel.Unbind <ILoadStrategy>();
            kernel.Bind <ILoadStrategy>().To <LocalSourceLoadStrategy>();
            var assetModule = new ProtogameAssetModule();

            assetModule.LoadRawAssetStrategies(kernel);

            // Set up remaining bindings.
            kernel.Bind <IAssetCleanup>().To <DefaultAssetCleanup>();
            kernel.Bind <IAssetOutOfDateCalculator>().To <DefaultAssetOutOfDateCalculator>();
            kernel.Bind <IAssetCompilationEngine>().To <DefaultAssetCompilationEngine>();
        }
Пример #2
0
        } // Instance

        #endregion

        #region Constructors

        /// <summary>
        /// Über post processing shader.
        /// </summary>
        private PostProcessingShader() : base("PostProcessing\\PostProcessing")
        {
            AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;
            AssetContentManager.CurrentContentManager = AssetContentManager.SystemContentManager;
            filmLutTexture = new Texture("Shaders\\FilmLut");
            AssetContentManager.CurrentContentManager = userContentManager;
        } // PostProcessingShader
Пример #3
0
        } // RemoveSongs

        /// <summary>
        /// Remove songs from the playlist.
        /// </summary>
        /// <remarks>
        /// If a content manager is unload and this content manager was used to load songs then this method is very useful for remove all the songs loaded in there.
        /// </remarks>
        public static void RemoveSongs(AssetContentManager contentManager)
        {
            // First we count how much elements the new playlist will have.
            int elementCount = 0;

            for (int i = 0; i < playlist.Length; i++)
            {
                if (playlist[i].Asset.ContentManager == contentManager)
                {
                    // If we want to remove the current song we have to stop it first.
                    if (currentIndex == i)
                    {
                        Stop();
                    }
                }
                else
                {
                    elementCount++;
                }
            }
            // Then we create the new playlist.
            LoadedSong[] newPlaylist = new LoadedSong[elementCount];
            int          k           = 0;

            for (int i = 0; i < playlist.Length; i++)
            {
                if (playlist[i].Asset.ContentManager != contentManager)
                {
                    newPlaylist[k] = playlist[i];
                    k++;
                }
            }
            playlist = newPlaylist;
        } // RemoveSongs
Пример #4
0
        } // LoadAllSong

        /// <summary>
        /// Load song in a temporal content manager.
        /// </summary>
        private static Song LoadSongInTemporalContentManager(string _currentSongFilename)
        {
            try
            {
                // Save the current content manager.
                AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;

                if (musicContentManager != null)
                {
                    musicContentManager.Unload();
                }
                else
                {
                    // Creates a new content manager and load the new song.
                    musicContentManager = new AssetContentManager {
                        Name = "Temporal Content Manager", Hidden = true
                    }
                };

                AssetContentManager.CurrentContentManager = musicContentManager;
                Song song = new Song(_currentSongFilename);

                // Restore the user content manager.
                AssetContentManager.CurrentContentManager = userContentManager;

                return(song);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Music Manager: Failed to load song: " + _currentSongFilename, e);
            }
        } // LoadSongInTemporalContentManager
Пример #5
0
        } // Update

        #endregion

        #region Constructor

        /// <summary>
        /// Video Renderer.
        /// </summary>
        public VideoRenderer()
        {
            AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;

            AssetContentManager.CurrentContentManager = AssetContentManager.SystemContentManager;
            texture = new Texture();
            AssetContentManager.CurrentContentManager = userContentManager;
        } // VideoRenderer
Пример #6
0
        } // Instance

        #endregion

        #region Constructor

        private CarPaintShader() : base("Materials\\CarPaint")
        {
            AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;

            AssetContentManager.CurrentContentManager = AssetContentManager.SystemContentManager;
            sparkleNoiseTexture = new Texture("Shaders\\SparkleNoiseMap");
            AssetContentManager.CurrentContentManager = userContentManager;
        } // CarPaintShader
        } // Instance

        #endregion

        #region Constructor

        /// <summary>
        /// Anamorphic Lens Flare Shader.
        /// </summary>
        private AnamorphicLensFlareShader() : base("PostProcessing\\AnamorphicLensFlare")
        {
            AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;

            AssetContentManager.CurrentContentManager = AssetContentManager.SystemContentManager;
            //sunObject = new Sphere(6, 6, 1);   // Algorithmically generated mesh normally sucks when optimized vertex access is needed.
            sunObject = new FileModel("Sphere"); // Exported models for the contrary are great.
            AssetContentManager.CurrentContentManager = userContentManager;
        } // AnamorphicLensFlareShader
        } // SetNormalTexture

        #endregion

        #endregion

        #region Constructor

        /// <summary>
        /// Ray Marching Screen Space Ambient Occlusion.
        /// </summary>
        private RayMarchingAmbientOcclusionShader() : base("GlobalIllumination\\RayMarchingAmbientOcclusionShader")
        {
            AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;

            AssetContentManager.CurrentContentManager = AssetContentManager.SystemContentManager;
            // Set the random normal map. Helps to make the samplers more random.
            randomNormalTexture = new Texture("Shaders\\RandomNormal");
            Resource.Parameters["randomTexture"].SetValue(randomNormalTexture.Resource);
            AssetContentManager.CurrentContentManager = userContentManager;
        } // RayMarchingAmbientOcclusionShader
Пример #9
0
        } // Instance

        #endregion

        #region Constructor

        /// <summary>
        /// Skybox Shader.
        /// </summary>
        private SkydomeShader() : base("Sky\\Skydome")
        {
            skydomeModel = new FileModel("Skydome");
            AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;

            AssetContentManager.CurrentContentManager = AssetContentManager.SystemContentManager;
            skyTextureNight  = new Texture("Shaders\\SkyNight");
            skyTextureSunset = new Texture("Shaders\\SkySunset");
            skyTextureDay    = new Texture("Shaders\\SkyDay");
            AssetContentManager.CurrentContentManager = userContentManager;
        } // SkyboxShader
Пример #10
0
        } // Instance

        #endregion

        #region Constructor

        /// <summary>
        /// Morphological Antialiasing (MLAA).
        /// </summary>
        private MLAAShader() : base("PostProcessing\\MLAA")
        {
            AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;

            AssetContentManager.CurrentContentManager = AssetContentManager.SystemContentManager;
            // IMPORTANT: Be careful of the content processor properties of this texture
            // Pre multiply alpha: false
            // Texture format: No change.
            areaTexture = new Texture("Shaders\\AreaMap32");
            AssetContentManager.CurrentContentManager = userContentManager;
        } // MLAAShader
Пример #11
0
        } // Instance

        #endregion

        #region Constructors

        /// <summary>
        /// This shader generates the G-Buffer of the deferred lighting.
        /// The depth texture has a surface format of 32 bits single channel precision. Equation: -DepthVS / FarPlane
        /// The normals are store using best fit normals for maximum compression (24 bits), and are stored in view space,
        /// but best fit normals works better in world space, this is specially noticed in the presence of big triangles.
        /// The specular power is stored in 8 bits following Killzone 2 method.
        /// There is room in the depth surface to store a mask for ambient lighting (Crysis 2 and Toy Story 3 method).
        /// </summary>
        internal GBufferShader() : base("GBuffer\\GBuffer")
        {
            AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;

            AssetContentManager.CurrentContentManager = AssetContentManager.SystemContentManager;
            // Set the random normal map. Helps to make the samplers more random.
            #if (WINDOWS)
            normalsFittingTexture = new Texture("Shaders\\NormalsFitting1024");
            #else
            normalsFittingTexture = new Texture("Shaders\\NormalsFitting512");
            #endif
            AssetContentManager.CurrentContentManager = userContentManager;
        } // GBufferShader
        /// <summary>
        /// Creates the configuration controls of this asset.
        /// </summary>
        public static void AddControls(LookupTable asset, Window owner, ComboBox comboBoxResource)
        {
            // In asset creation I need to look on the CurrentCreatedAsset property to have the last asset.
            // I can't use CurrentCreatedAsset in edit mode.
            // However I can use asset for creation (maybe in a disposed state but don't worry) and edit mode,
            // and only update the values when I know that CurrentCreatedAsset changes.
            
            #region Group Image

            var groupImage = CommonControls.Group("Image", owner);
            AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;
            AssetContentManager.CurrentContentManager = UserInterfaceManager.UserInterfaceContentManager;
            var imageBoxImage = CommonControls.ImageBox(LookupTable.LookupTableToTexture(asset), groupImage);
            AssetContentManager.CurrentContentManager = userContentManager;
            groupImage.AdjustHeightFromChildren();

            #endregion
            
            #region Group Properties

            GroupBox groupProperties = CommonControls.Group("Properties", owner);

            var sizeTextBox = CommonControls.TextBox("Size", groupProperties, asset.Size.ToString());
            sizeTextBox.Enabled = false;

            groupProperties.AdjustHeightFromChildren();

            #endregion

            // If it is asset creation time.
            if (comboBoxResource != null)
            {
                comboBoxResource.ItemIndexChanged += delegate
                {
                    imageBoxImage.Texture.Dispose();
                    userContentManager = AssetContentManager.CurrentContentManager;
                    AssetContentManager.CurrentContentManager = UserInterfaceManager.UserInterfaceContentManager;
                    imageBoxImage.Texture = LookupTable.LookupTableToTexture((LookupTable)AssetWindow.CurrentCreatedAsset);
                    AssetContentManager.CurrentContentManager = userContentManager;
                    sizeTextBox.Text = ((LookupTable)AssetWindow.CurrentCreatedAsset).Size.ToString();
                };
                // If the user creates the asset (press the create button) then update the changeable properties.
                owner.Closed += delegate
                {
                    imageBoxImage.Texture.Dispose();
                };
            }
        } // AddControls
Пример #13
0
        } // Instance

        #endregion

        #region Constructor

        /// <summary>
        /// Light Pre Pass Spot Light Shader.
        /// </summary>
        private SpotLightShader() : base("LightPrePass\\SpotLight")
        {
            AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;

            AssetContentManager.CurrentContentManager = AssetContentManager.SystemContentManager;
            //boundingLightObject = new Sphere(6, 6, 1);   // Algorithmically generated mesh normally sucks when optimized vertex access is needed.
            boundingLightObject = new FileModel("Sphere"); // Exported models for the contrary are great.
            // TODO: Export a cone.
            AssetContentManager.CurrentContentManager = userContentManager;
            interiorOfBoundingVolumeDepthStencilState = new DepthStencilState
            {
                DepthBufferEnable      = true,
                DepthBufferWriteEnable = false,
                DepthBufferFunction    = CompareFunction.Greater,
            };
        } // SpotLightShader
Пример #14
0
        } // DisposeManagedResources

        #endregion

        #region Initialize

        /// <summary>
        /// Creates the scene content manager and loads the user content.
        /// </summary>
        internal void Initialize()
        {
            AssetContentManager = new AssetContentManager {
                Name = (GetType().Name + " Content Manager")
            };
            AssetContentManager.CurrentContentManager = AssetContentManager;
            GameObjectContentManager = new GameObjectContentManager {
                Name = (GetType().Name + " Content Manager")
            };
            GameObjectContentManager.CurrentContentManager = GameObjectContentManager;
            LoadContent();
            ContentLoaded = true;
            // A collection of all generations could be a good idea at this point.
            // Besides the used managed memory indicates rational values when this is executed here.
            GarbageCollector.CollectGarbage();
        } // Initialize
Пример #15
0
        } // Initialize

        #endregion

        #region Uninitialize

        /// <summary>
        /// Unloads the user content and disposes the scene content manager.
        /// </summary>
        internal void Unitialize()
        {
            if (ContentLoaded)
            {
                EndRun();
                UnloadContent();
                if (AssetContentManager.CurrentContentManager == AssetContentManager)
                {
                    AssetContentManager.CurrentContentManager = null;
                }
                if (GameObjectContentManager.CurrentContentManager == GameObjectContentManager)
                {
                    GameObjectContentManager.CurrentContentManager = null;
                }
                AssetContentManager.Dispose();
                GameObjectContentManager.Dispose();
                ContentLoaded = false;
            }
        } // Unitialize
Пример #16
0
        } // Instance

        #endregion

        #region Constructor

        /// <summary>
        /// Light Pre Pass Point Light Shader.
        /// </summary>
        private PointLightShader() : base("LightPrePass\\PointLight")
        {
            AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;

            AssetContentManager.CurrentContentManager = AssetContentManager.SystemContentManager;
            //boundingLightObject = new Sphere(6, 6, 1);   // Algorithmically generated mesh normally sucks when optimized vertex access is needed.
            boundingLightObject = new FileModel("Sphere"); // Exported models for the contrary are great.
            AssetContentManager.CurrentContentManager = userContentManager;

            stencilBlendState = new BlendState
            {
                ColorWriteChannels  = ColorWriteChannels.None,
                ColorWriteChannels1 = ColorWriteChannels.None,
            };
            lightBlendState = new BlendState
            {
                AlphaBlendFunction    = BlendFunction.Add,
                AlphaDestinationBlend = Blend.One,
                AlphaSourceBlend      = Blend.One,
                ColorBlendFunction    = BlendFunction.Add,
                ColorDestinationBlend = Blend.One,
                ColorSourceBlend      = Blend.One,
            };
            stencilDepthStencilState = new DepthStencilState
            {
                DepthBufferEnable      = true,
                DepthBufferWriteEnable = false,
                DepthBufferFunction    = CompareFunction.Less,
                StencilEnable          = true,
                StencilFunction        = CompareFunction.Always,
                StencilDepthBufferFail = StencilOperation.Replace,
                ReferenceStencil       = 1,
            };
            lightDepthStencilState = new DepthStencilState
            {
                DepthBufferEnable      = true,
                DepthBufferWriteEnable = false,
                DepthBufferFunction    = CompareFunction.Greater,
                StencilEnable          = true,
                StencilFunction        = CompareFunction.NotEqual,
                ReferenceStencil       = 1,
            };
        } // PointLightShader
Пример #17
0
        /// <summary>
        /// Load layout file.
        /// </summary>
        public static Container Load(string filename)
        {
            Container mainContainer = null;
            AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;
            AssetContentManager temporalContent = new AssetContentManager { Name = "Temporal Content Manager", Hidden = true };
            AssetContentManager.CurrentContentManager = temporalContent;
            try
            {
                Document layoutDocument = new Document("Layout\\" + filename);
                try
                {
                    if (layoutDocument.Resource.Element("Layout").Element("Controls") != null)
                    {
                        foreach (var control in layoutDocument.Resource.Element("Layout").Element("Controls").Elements())
                        {
                            string className = control.Attribute("Class").Value;
                            Type type = Type.GetType("XNAFinalEngine.UserInterface." + className);
                            if (type == null)
                            {
                                throw new Exception("Failed to load layout: Control doesn't exist");
                            }
                            mainContainer = (Container)LoadControl(control, type, null);
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new InvalidOperationException("Failed to load layout: " + filename + ".\nThere are probably syntax errors.", e);
                }
            }
            finally
            {
                // Dispose the temporal content manager and restore the user content manager.
                temporalContent.Dispose();
                AssetContentManager.CurrentContentManager = userContentManager;
            }

            return mainContainer;
        } // Load
Пример #18
0
        } // CloneMainCamera

        #endregion

        #region On Screen Size Changed

        /// <summary>
        /// Reset the viewport dimensions and adjust the viewport camera's render target size.
        /// </summary>
        private void OnScreenSizeChanged(object caller, System.EventArgs eventArgs)
        {
            viewportControl.Left   = (int)(MainWindow.ViewportArea.Width * normalizedViewport.X + MainWindow.ViewportArea.X);
            viewportControl.Top    = (int)(MainWindow.ViewportArea.Height * normalizedViewport.Y + MainWindow.ViewportArea.Y);
            viewportControl.Width  = (int)(MainWindow.ViewportArea.Width * normalizedViewport.Width);
            viewportControl.Height = (int)(MainWindow.ViewportArea.Height * normalizedViewport.Height);
            if (viewportCamera != null)
            {
                editorCameraScript.ClientArea = viewportControl.ClientArea;
                if (mode != ViewportMode.Game)
                {
                    viewportCamera.Camera.RenderTargetSize = new Size(ClientWidth, ClientHeight);
                    viewportCamera.Camera.AspectRatio      = ClientWidth / (float)ClientHeight;
                }
                else
                {
                    Size  size;
                    float renderTargetAspectRatio = Camera.AspectRatio,
                          renderSpaceAspectRatio  = ClientArea.Width / (float)ClientArea.Height;
                    if (renderTargetAspectRatio > renderSpaceAspectRatio)
                    {
                        size = new Size(ClientArea.Width, (int)(ClientArea.Width / renderTargetAspectRatio));
                    }
                    else
                    {
                        size = new Size((int)(renderTargetAspectRatio * ClientArea.Height), ClientArea.Height);
                    }
                    viewportCamera.Camera.RenderTargetSize = size;
                }
                if (viewportCamera.Camera.RenderTarget == null)
                {
                    AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;
                    AssetContentManager.CurrentContentManager = EditorManager.EditorContentManager;
                    viewportCamera.Camera.RenderTarget        = new RenderTarget(viewportCamera.Camera.RenderTargetSize, SurfaceFormat.Color, false);
                    AssetContentManager.CurrentContentManager = userContentManager;
                }
            }
        } // OnScreenSizeChanged
Пример #19
0
        private static void BulkCompile(List<string> assemblies, List<string> platforms, string output)
        {
            // Create kernel.
            var kernel = new StandardKernel();
            kernel.Load<ProtogameAssetIoCModule>();
            kernel.Load<ProtogameScriptIoCModule>();
            var services = new GameServiceContainer();
            var assetContentManager = new AssetContentManager(services);
            kernel.Bind<IAssetContentManager>().ToMethod(x => assetContentManager);
            kernel.Bind<IRenderBatcher>().To<NullRenderBatcher>();

            // Only allow source and raw load strategies.
            kernel.Unbind<ILoadStrategy>();
            kernel.Bind<ILoadStrategy>().To<LocalSourceLoadStrategy>();
            var assetModule = new ProtogameAssetIoCModule();
            assetModule.LoadRawAssetStrategies(kernel);

            // The assembly load strategy is required for references.
            // Assets loaded with the assembly load strategy won't have
            // any savers defined, so they won't ever get processed.
            kernel.Bind<ILoadStrategy>().To<AssemblyLoadStrategy>();

            // Load additional assemblies.
            foreach (var filename in assemblies)
            {
                var file = new FileInfo(filename);
                try
                {
                    var assembly = Assembly.LoadFrom(file.FullName);
                    foreach (var type in assembly.GetTypes())
                    {
                        try
                        {
                            if (type.IsAbstract || type.IsInterface)
                                continue;
                            if (type.Assembly == typeof(FontAsset).Assembly)
                                continue;
                            if (typeof(IAssetLoader).IsAssignableFrom(type))
                            {
                                Console.WriteLine("Binding IAssetLoader: " + type.Name);
                                kernel.Bind<IAssetLoader>().To(type);
                            }
                            if (typeof(IAssetSaver).IsAssignableFrom(type))
                            {
                                Console.WriteLine("Binding IAssetSaver: " + type.Name);
                                kernel.Bind<IAssetSaver>().To(type);
                            }
                            if (type.GetInterfaces().Any(x => x.Name == "IAssetCompiler`1"))
                            {
                                Console.WriteLine("Binding IAssetCompiler<>: " + type.Name);
                                kernel.Bind(type.GetInterfaces().First(x => x.Name == "IAssetCompiler`1")).To(type);
                            }
                            if (typeof(ILoadStrategy).IsAssignableFrom(type))
                            {
                                Console.WriteLine("Binding ILoadStrategy: " + type.Name);
                                kernel.Bind<ILoadStrategy>().To(type);
                            }
                        }
                        catch
                        {
                            // Might not be able to load the assembly, so just skip over it.
                        }
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Can't load " + file.Name);
                }
            }

            // Set up remaining bindings.
            kernel.Bind<IAssetCleanup>().To<DefaultAssetCleanup>();
            kernel.Bind<IAssetOutOfDateCalculator>().To<DefaultAssetOutOfDateCalculator>();
            kernel.Bind<IAssetCompilationEngine>().To<DefaultAssetCompilationEngine>();

            // Get the asset compilation engine.
            var compilationEngine = kernel.Get<IAssetCompilationEngine>();
            compilationEngine.Execute(platforms, output);
        }
Пример #20
0
        /// <summary>
        /// Compiles the built-in embedded resources.
        /// </summary>
        private static void BuiltinCompile()
        {
            // Create kernel.
            var kernel = new StandardKernel();

            kernel.Load <ProtogameAssetIoCModule>();
            kernel.Load <ProtogameScriptIoCModule>();
            var services            = new GameServiceContainer();
            var assetContentManager = new AssetContentManager(services);

            kernel.Bind <IAssetContentManager>().ToMethod(x => assetContentManager);

            // Only allow source and raw load strategies.
            kernel.Unbind <ILoadStrategy>();
            kernel.Bind <ILoadStrategy>().To <LocalSourceLoadStrategy>();
            var assetModule = new ProtogameAssetIoCModule();

            assetModule.LoadRawAssetStrategies(kernel);

            // Set up remaining bindings.
            kernel.Bind <IAssetCleanup>().To <DefaultAssetCleanup>();
            kernel.Bind <IAssetOutOfDateCalculator>().To <DefaultAssetOutOfDateCalculator>();
            kernel.Bind <IAssetCompilationEngine>().To <DefaultAssetCompilationEngine>();

            // Rebind for builtin compilation.
            kernel.Rebind <IRawAssetLoader>().To <BuiltinRawAssetLoader>();

            // Set up the compiled asset saver.
            var compiledAssetSaver = new CompiledAssetSaver();

            // Retrieve the asset manager.
            var assetManager = kernel.Get <LocalAssetManager>();

            assetManager.AllowSourceOnly = true;
            assetManager.SkipCompilation = true;

            // Retrieve the transparent asset compiler.
            var assetCompiler = kernel.Get <ITransparentAssetCompiler>();

            // Retrieve all of the asset savers.
            var savers = kernel.GetAll <IAssetSaver>();

            var rawLoader = kernel.Get <IRawAssetLoader>();

            // For each of the platforms, perform the compilation of assets.
            foreach (var platformName in new[]
            {
                "Android",
                "iOS",
                "Linux",
                "MacOSX",
                "Ouya",
                "RaspberryPi",
                "Windows",
                "WindowsPhone8",
                "WindowsStoreApp"
            })
            {
                Console.WriteLine("Starting compilation for " + platformName);
                var platform   = (TargetPlatform)Enum.Parse(typeof(TargetPlatform), platformName);
                var outputPath = Environment.CurrentDirectory;
                assetManager.RescanAssets();

                // Create the output directory if it doesn't exist.
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }

                // Get a list of asset names that we need to recompile for this platform.
                var assetNames = rawLoader.ScanRawAssets();

                foreach (var asset in assetNames.Select(assetManager.GetUnresolved))
                {
                    assetCompiler.HandlePlatform(asset, platform, true);

                    foreach (var saver in savers)
                    {
                        var canSave = false;
                        try
                        {
                            canSave = saver.CanHandle(asset);
                        }
                        catch (Exception)
                        {
                        }

                        if (canSave)
                        {
                            try
                            {
                                var result = saver.Handle(asset, AssetTarget.CompiledFile);
                                compiledAssetSaver.SaveCompiledAsset(
                                    outputPath,
                                    asset.Name,
                                    result,
                                    result is CompiledAsset,
                                    platformName);
                                Console.WriteLine("Compiled " + asset.Name + " for " + platform);
                                break;
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("ERROR: Unable to compile " + asset.Name + " for " + platform);
                                Console.WriteLine("ERROR: " + ex.GetType().FullName + ": " + ex.Message);
                                break;
                            }
                        }
                    }

                    assetManager.Dirty(asset.Name);
                }
            }
        }
Пример #21
0
        private static void BulkCompile(List <string> assemblies, List <string> platforms, string output)
        {
            // Create kernel.
            var kernel = new StandardKernel();

            kernel.Load <ProtogameAssetIoCModule>();
            kernel.Load <ProtogameScriptIoCModule>();
            var services            = new GameServiceContainer();
            var assetContentManager = new AssetContentManager(services);

            kernel.Bind <IAssetContentManager>().ToMethod(x => assetContentManager);

            // Only allow source and raw load strategies.
            kernel.Unbind <ILoadStrategy>();
            kernel.Bind <ILoadStrategy>().To <LocalSourceLoadStrategy>();
            var assetModule = new ProtogameAssetIoCModule();

            assetModule.LoadRawAssetStrategies(kernel);

            // The assembly load strategy is required for references.
            // Assets loaded with the assembly load strategy won't have
            // any savers defined, so they won't ever get processed.
            kernel.Bind <ILoadStrategy>().To <AssemblyLoadStrategy>();

            // Load additional assemblies.
            foreach (var filename in assemblies)
            {
                var file = new FileInfo(filename);
                try
                {
                    var assembly = Assembly.LoadFrom(file.FullName);
                    foreach (var type in assembly.GetTypes())
                    {
                        try
                        {
                            if (type.IsAbstract || type.IsInterface)
                            {
                                continue;
                            }
                            if (type.Assembly == typeof(FontAsset).Assembly)
                            {
                                continue;
                            }
                            if (typeof(IAssetLoader).IsAssignableFrom(type))
                            {
                                Console.WriteLine("Binding IAssetLoader: " + type.Name);
                                kernel.Bind <IAssetLoader>().To(type);
                            }
                            if (typeof(IAssetSaver).IsAssignableFrom(type))
                            {
                                Console.WriteLine("Binding IAssetSaver: " + type.Name);
                                kernel.Bind <IAssetSaver>().To(type);
                            }
                            if (type.GetInterfaces().Any(x => x.Name == "IAssetCompiler`1"))
                            {
                                Console.WriteLine("Binding IAssetCompiler<>: " + type.Name);
                                kernel.Bind(type.GetInterfaces().First(x => x.Name == "IAssetCompiler`1")).To(type);
                            }
                            if (typeof(ILoadStrategy).IsAssignableFrom(type))
                            {
                                Console.WriteLine("Binding ILoadStrategy: " + type.Name);
                                kernel.Bind <ILoadStrategy>().To(type);
                            }
                        }
                        catch
                        {
                            // Might not be able to load the assembly, so just skip over it.
                        }
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Can't load " + file.Name);
                }
            }

            // Set up remaining bindings.
            kernel.Bind <IAssetCleanup>().To <DefaultAssetCleanup>();
            kernel.Bind <IAssetOutOfDateCalculator>().To <DefaultAssetOutOfDateCalculator>();
            kernel.Bind <IAssetCompilationEngine>().To <DefaultAssetCompilationEngine>();

            // Get the asset compilation engine.
            var compilationEngine = kernel.Get <IAssetCompilationEngine>();

            compilationEngine.Execute(platforms, output);
        }
Пример #22
0
        /// <summary>
        /// Creates and shows the configuration window of this asset.
        /// </summary>
        public static Window Show<TAssetType>(Asset asset) where TAssetType : Asset
        {
            AssetContentManager temporalContentManager = null;
            AssetContentManager userContentManager = null;

            bool assetCreation = asset == null;
            PropertyInfo filenamesProperty = typeof(TAssetType).GetProperty("Filenames"); // Search for the Filenames property, not all assets have it.
            bool resourcedAsset = filenamesProperty != null; // Indicates if the asset has a resource (textures, models, etc.) or if it is a property asset (shadows, ambient light, etc.)
            string[] filenames = null;
            if (assetCreation)
            {
                // If the asset has an internal XNA Resource (textures, models, sounds)
                if (resourcedAsset)
                {
                    filenames = (string[])filenamesProperty.GetValue(asset, null);
                    // If there is no asset to create then return                
                    if (filenames.Length == 0)
                    {
                        CurrentCreatedAsset = null; // To avoid unwanted event references.
                        return null;
                    }
                    userContentManager = AssetContentManager.CurrentContentManager;
                    temporalContentManager = new AssetContentManager { Name = "Temporal Content Manager", Hidden = true };
                    AssetContentManager.CurrentContentManager = temporalContentManager;

                    // Create a temporal asset with the first resource in the list.
                    asset = (Asset)typeof(TAssetType).GetConstructor(new[] { typeof(string) }).Invoke(new object[] { filenames[0] });
                }
                // If not... (ambient light, post process, shadows, etc.)
                else
                    asset = (Asset)typeof(TAssetType).GetConstructor(new Type[] { }).Invoke(null);
                
                CurrentCreatedAsset = asset;
            }

            #region Window

            var window = new UserInterface.AssetWindow
            {
                AssetName = asset.Name,
                AssetType = (typeof(TAssetType)).Name,
            };
            window.AssetNameChanged += delegate
            {
                string oldName = asset.Name;
                asset.SetUniqueName(window.AssetName);
                if (asset.Name != oldName)
                {
                    window.AssetName = asset.Name; // The window name could be change if the name was not unique.
                    asset.Name = oldName; // This is done for the undo.
                    using (Transaction.Create())
                    {
                        // Apply the command and store for the undo feature.
                        ActionManager.SetProperty(asset, "Name", window.AssetName);
                        ActionManager.CallMethod(// Redo
                                                 UserInterfaceManager.Invalidate,
                                                 // Undo
                                                 UserInterfaceManager.Invalidate);
                    }
                   
                }
            };
            window.Draw += delegate { window.AssetName = asset.Name; };
            // In creation I don't want that the user mess with other things.)
            if (assetCreation)
                window.ShowModal();

            #endregion

            #region Group Resource

            GroupBox groupResource;
            ComboBox comboBoxResource = null;
            ComboBox comboBoxContentManager = null;

            if (resourcedAsset)
            {
                groupResource = CommonControls.Group("Resource", window);
                comboBoxResource = CommonControls.ComboBox("Resource", groupResource);
                comboBoxContentManager = CommonControls.ComboBox("Content Manager", groupResource);
                groupResource.AdjustHeightFromChildren();
            }

            #endregion

            #region Creation Mode

            if (assetCreation)
            {
                
                #region Combo Box Resource
                
                if (resourcedAsset)
                {
                    comboBoxResource.Items.AddRange(filenames);
                    comboBoxResource.ItemIndex = 0;
                    // Events
                    comboBoxResource.ItemIndexChanged += delegate
                    {
                        if (filenames[comboBoxResource.ItemIndex] != asset.Filename)
                        {
                            // This is a disposable asset so...
                            temporalContentManager.Unload();
                            // To contemplate some assets like Lookup Tables and some textures.
                            if (!asset.IsDisposed)
                                asset.Dispose();
                            asset = (Asset)typeof(TAssetType).GetConstructor(new[] { typeof(string) }).Invoke(new object[] { filenames[comboBoxResource.ItemIndex] });
                            CurrentCreatedAsset = asset;
                            window.AssetName = asset.Name;
                        }
                    };
                    comboBoxResource.Draw += delegate
                    {
                        if (comboBoxResource.ListBoxVisible)
                            return;
                        for (int i = 0; i < comboBoxResource.Items.Count; i++)
                        {
                            if ((string)comboBoxResource.Items[i] == asset.Filename)
                            {
                                if (comboBoxResource.ItemIndex != i)
                                {
                                    comboBoxResource.ItemIndex = i;
                                    break;
                                }
                            }
                        }
                    };

                }
                
                #endregion

                #region Combo Box Content Manager

                if (resourcedAsset)
                {
                    // The names of the content manager are added here because we want to place the item index in the current content manager.
                    comboBoxContentManager.Items.Clear();
                    // Add content names.
                    foreach (AssetContentManager contentManager in AssetContentManager.SortedContentManagers)
                    {
                        if (!contentManager.Hidden)
                            comboBoxContentManager.Items.Add(contentManager.Name);
                    }
                    // Find the current content manager.
                    comboBoxContentManager.ItemIndex = 0;
                    for (int i = 0; i < comboBoxContentManager.Items.Count; i++)
                    {
                        if (AssetContentManager.SortedContentManagers[i] == userContentManager)
                        {
                            comboBoxContentManager.ItemIndex = i;
                            break;
                        }
                    }
                    comboBoxResource.Draw += delegate
                    {
                        // The names of the content manager are added here because someone could dispose or add a new one.
                        comboBoxContentManager.Items.Clear();
                        // Add names
                        foreach (AssetContentManager contentManager in AssetContentManager.SortedContentManagers)
                        {
                            if (!contentManager.Hidden)
                                comboBoxContentManager.Items.Add(contentManager.Name);
                        }
                    };
                }

                #endregion

                #region Window Closed
                
                window.Closed += delegate
                {
                    if (resourcedAsset)
                        temporalContentManager.Dispose();
                    if (window.ModalResult == ModalResult.Cancel)
                    {
                        // Returns null.
                        CurrentCreatedAsset = null;
                        if (!asset.IsDisposed)
                            asset.Dispose();
                    }
                    else
                    {
                        if (resourcedAsset)
                        {
                            if (!asset.IsDisposed) // To contemplate some assets like Lookup Tables and some textures.
                                asset.Dispose();
                            // Search the content manager reference using its name.
                            foreach (AssetContentManager contenManager in AssetContentManager.SortedContentManagers)
                            {
                                if (contenManager.Name == (string)(comboBoxContentManager.Items[comboBoxContentManager.ItemIndex]))
                                {
                                    AssetContentManager.CurrentContentManager = contenManager;
                                    break;
                                }
                            }
                            // And create the asset with this content manager.
                            CurrentCreatedAsset = (Asset)typeof(TAssetType).GetConstructor(new[] { typeof(string) }).Invoke(new object[] { filenames[comboBoxResource.ItemIndex] });
                        }
                        CurrentCreatedAsset.Name = window.AssetName;
                    }
                    // Restore user content manager.
                    if (resourcedAsset)
                        AssetContentManager.CurrentContentManager = userContentManager;
                    // Remove references to the event.
                    CurrentCreatedAssetChanged = null;
                };

                #endregion

            }

            #endregion

            #region Edit Mode

            else // If it is in edit mode...
            {
                // Fill Resource Combo Box.
                if (resourcedAsset)
                {
                    comboBoxResource.Items.Add(asset.Filename);
                    comboBoxResource.ItemIndex = 0;
                    comboBoxResource.Enabled = false;
                    // Fill Content Manager Combo Box.
                    if (asset.ContentManager != null)
                        comboBoxContentManager.Items.Add(asset.ContentManager.Name);
                    else
                        comboBoxContentManager.Items.Add("Does not have a Content Manager");
                    comboBoxContentManager.ItemIndex = 0;
                    comboBoxContentManager.Enabled = false;
                }
            }
            #endregion

            #region Specific Controls for Specific Assets

            if (typeof(TAssetType) == typeof(Texture))
                TextureControls.AddControls((Texture)asset, window, comboBoxResource);
            else if (typeof(TAssetType) == typeof(PostProcess))
                PostProcessControls.AddControls((PostProcess) asset, window, comboBoxResource);
            else if (typeof(TAssetType) == typeof(LookupTable))
                LookupTableControls.AddControls((LookupTable)asset, window, comboBoxResource);
            else if (typeof(TAssetType) == typeof(AmbientLight))
                AmbientLightControls.AddControls((AmbientLight)asset, window, comboBoxResource);
            else if (typeof(TAssetType) == typeof(HorizonBasedAmbientOcclusion))
                HorizonBasedAmbientOcclusionControls.AddControls((HorizonBasedAmbientOcclusion)asset, window, comboBoxResource);
            else if (typeof(TAssetType) == typeof(BasicShadow))
                ShadowControls.AddControls((BasicShadow)asset, window, comboBoxResource);
            else if (typeof(TAssetType) == typeof(Sphere))
                PrimitiveControls.AddControls((Sphere)asset, window, assetCreation);
            else if (typeof(TAssetType) == typeof(Box))
                PrimitiveControls.AddControls((Box)asset, window, assetCreation);
            else if (typeof(TAssetType) == typeof(Plane))
                PrimitiveControls.AddControls((Plane)asset, window, assetCreation);
            else if (typeof(TAssetType) == typeof(Cylinder))
                PrimitiveControls.AddControls((Cylinder)asset, window, assetCreation);
            else if (typeof(TAssetType) == typeof(Cone))
                PrimitiveControls.AddControls((Cone)asset, window, assetCreation);
            else if (typeof(TAssetType) == typeof(BlinnPhong))
                BlinnPhongControls.AddControls((BlinnPhong)asset, window);
            else if (typeof(TAssetType) == typeof(Constant))
                ConstantControls.AddControls((Constant)asset, window);
            else if (typeof(TAssetType) == typeof(CarPaint))
                CarPaintControls.AddControls((CarPaint)asset, window);

            #endregion);

            if (assetCreation)
            {
                #region Buttons

                window.StatusBar = new StatusBar();
                var buttonApply = new Button
                {
                    Anchor = Anchors.Top | Anchors.Right,
                    //Top = window.AvailablePositionInsideControl + CommonControls.ControlSeparation,
                    Top = 5,
                    Left = window.ClientWidth - 4 - 70 * 2 - 8,
                    Text = "Create",
                    Parent = window.StatusBar,
                };
                buttonApply.Click += delegate { window.Close(); };

                var buttonClose = new Button
                {
                    Anchor = Anchors.Top | Anchors.Right,
                    Text = "Cancel",
                    ModalResult = ModalResult.Cancel,
                    Top = buttonApply.Top,
                    Left = window.ClientWidth - 70 - 8,
                    Parent = window.StatusBar
                };
                window.StatusBar.Height = buttonApply.Top + buttonApply.Height + 5;

                #endregion
            }

            window.AdjustHeightFromChildren();
            window.Height += 5;
            if (window.Height > 600)
                window.Height = 600;
            return window;
        } // Show
        /// <summary>
        /// Initializes the User Interface Manager.
        /// </summary>
        /// <param name="autoUpdate">Auto update and render.</param>
        public static void Initialize(bool autoUpdate = true)
        {
            if (initialized)
                return;
            try
            {
                Visible = true;
                InputEnabled = true;
                initialized = true;
                // Set some public parameters.
                TextureResizeIncrement = 32;
                ToolTipDelay = 500;
                AutoUnfocus = true;
                ToolTipsEnabled = true;
            
                #if (WINDOWS)
                    MenuDelay = SystemInformation.MenuShowDelay;
                    DoubleClickTime = SystemInformation.DoubleClickTime;
                    window = (Form)System.Windows.Forms.Control.FromHandle(EngineManager.GameWindow.Handle);
                    window.FormClosing += FormClosing;
                #endif

                RootControls  = new ControlsList();
                OrderList = new ControlsList();

                EngineManager.DeviceReset += OnDeviceReset;

                states.Buttons = new Control[32];
                states.Click = -1;
                states.Over = null;

                // Input events
                InputSystem = new Input();
                InputSystem.MouseDown  += MouseDownProcess;
                InputSystem.MouseUp    += MouseUpProcess;
                InputSystem.MousePress += MousePressProcess;
                InputSystem.MouseMove  += MouseMoveProcess;
                InputSystem.KeyDown    += KeyDownProcess;
                InputSystem.KeyUp      += KeyUpProcess;
                InputSystem.KeyPress   += KeyPressProcess;

                // Final render target.
                AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;
                UserInterfaceContentManager = new AssetContentManager { Name = "User Interface Content Manager", Hidden = true };
                AssetContentManager.CurrentContentManager = UserInterfaceContentManager;
                renderTarget = new RenderTarget(Helpers.Size.FullScreen, SurfaceFormat.Color, false, RenderTarget.AntialiasingType.NoAntialiasing)
                {
                    Name = "User Interface Render Target",
                };
                AssetContentManager.CurrentContentManager = userContentManager;

                // Init User Interface Renderer.
                Renderer.Initialize();

                // Set Default skin.
                SetSkin("Default");

                // Window resize.
                oldScreenWidth = Screen.Width;
                oldScreenHeight = Screen.Height;
                Screen.ScreenSizeChanged += OnScreenSizeChanged;

                EngineManager.DeviceDisposed += delegate
                {
                    Renderer.Initialize();
                    // Invalidate all controls.
                    OnDeviceReset(null, new EventArgs());
                    SetSkin(Skin.CurrentSkinName);
                };

                if (autoUpdate)
                {
                    // To automatically update and render.
                    userInterfaceGameObject = new GameObject2D();
                    userInterfaceGameObject.AddComponent<ScripUserInterface>();
                }
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("User Interface Manager: Error occurred during initialization. Was the engine started?", e);
            }
        } // Initialize
Пример #24
0
        /// <summary>
        /// Compiles the built-in embedded resources.
        /// </summary>
        private static void BuiltinCompile()
        {
            // Create kernel.
            var kernel = new StandardKernel();
            kernel.Load<ProtogameAssetIoCModule>();
            kernel.Load<ProtogameScriptIoCModule>();
            var services = new GameServiceContainer();
            var assetContentManager = new AssetContentManager(services);
            kernel.Bind<IAssetContentManager>().ToMethod(x => assetContentManager);
            kernel.Bind<IRenderBatcher>().To<NullRenderBatcher>();

            // Only allow source and raw load strategies.
            kernel.Unbind<ILoadStrategy>();
            kernel.Bind<ILoadStrategy>().To<LocalSourceLoadStrategy>();
            var assetModule = new ProtogameAssetIoCModule();
            assetModule.LoadRawAssetStrategies(kernel);

            // Set up remaining bindings.
            kernel.Bind<IAssetCleanup>().To<DefaultAssetCleanup>();
            kernel.Bind<IAssetOutOfDateCalculator>().To<DefaultAssetOutOfDateCalculator>();
            kernel.Bind<IAssetCompilationEngine>().To<DefaultAssetCompilationEngine>();

            // Rebind for builtin compilation.
            kernel.Rebind<IRawAssetLoader>().To<BuiltinRawAssetLoader>();

            // Set up the compiled asset saver.
            var compiledAssetSaver = new CompiledAssetSaver();

            // Retrieve the asset manager.
            var assetManager = kernel.Get<LocalAssetManager>();
            assetManager.AllowSourceOnly = true;
            assetManager.SkipCompilation = true;

            // Retrieve the transparent asset compiler.
            var assetCompiler = kernel.Get<ITransparentAssetCompiler>();

            // Retrieve all of the asset savers.
            var savers = kernel.GetAll<IAssetSaver>();

            var rawLoader = kernel.Get<IRawAssetLoader>();

            // For each of the platforms, perform the compilation of assets.
            foreach (var platformName in new[]
                {
                    "Android",
                    "iOS",
                    "Linux",
                    "MacOSX",
                    "Ouya",
                    "Windows",
                })
            {
                Console.WriteLine("Starting compilation for " + platformName);
                var platform = (TargetPlatform)Enum.Parse(typeof(TargetPlatform), platformName);
                var outputPath = Environment.CurrentDirectory;
                assetManager.RescanAssets();

                // Create the output directory if it doesn't exist.
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }

                // Get a list of asset names that we need to recompile for this platform.
                var assetNames = rawLoader.ScanRawAssets();

                foreach (var asset in assetNames.Select(assetManager.GetUnresolved))
                {
                    Console.Write("Compiling " + asset.Name + " for " + platform + "... ");
                    try
                    {
                        assetCompiler.HandlePlatform(asset, platform, true);

                        foreach (var saver in savers)
                        {
                            var canSave = false;
                            try
                            {
                                canSave = saver.CanHandle(asset);
                            }
                            catch (Exception)
                            {
                            }

                            if (canSave)
                            {
                                try
                                {
                                    var result = saver.Handle(asset, AssetTarget.CompiledFile);
                                    compiledAssetSaver.SaveCompiledAsset(
                                        outputPath,
                                        asset.Name,
                                        result,
                                        result is CompiledAsset,
                                        platformName);
                                    Console.WriteLine("done.");
                                    break;
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("failed!");
                                    Console.WriteLine("ERROR: Unable to compile " + asset.Name + " for " + platform);
                                    Console.WriteLine("ERROR: " + ex.GetType().FullName + ": " + ex.Message);
                                    break;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("failed!");
                        Console.WriteLine("ERROR: Unable to compile " + asset.Name + " for " + platform);
                        Console.WriteLine("ERROR: " + ex.GetType().FullName + ": " + ex.Message);
                        break;
                    }

                    assetManager.Dirty(asset.Name);
                }
            }
        }
Пример #25
0
        } // CreateSaveData

        #endregion

        #region Load Save Data

        /// <summary>
        /// Create the structure that will be serialized.
        /// It stores content managers, assets and game objects.
        /// </summary>
        private static void LoadSaveData(SceneData sceneData)
        {
            // Generate content managers data.
            foreach (var contentManagerData in sceneData.ContentManagersData)
            {
                // Create Content Manager
                AssetContentManager contentManager = new AssetContentManager { Name = contentManagerData.Name };
                foreach (var assetId in contentManagerData.AssetsId)
                {
                    // The not resourced assets are already created and can change the content manager without recreation.
                    foreach (var assetsWithoutResourceData in sceneData.AssetsWithoutResourceData)
                    {
                        if (assetId == assetsWithoutResourceData.Id)
                        {
                            assetsWithoutResourceData.Asset.ChangeContentManager(contentManager);
                            break;
                        }
                    }
                }
            }
            // Recreate game objects (and the transform component)
            foreach (var gameObjectData in sceneData.GameObjectData)
            {
                GameObject gameObject;
                if (gameObjectData.is3D)
                {
                    gameObject = new GameObject3D();
                    ((GameObject3D)gameObject).Transform.LocalMatrix = gameObjectData.LocalMatrix;
                }
                else
                {
                    gameObject = new GameObject2D();
                    ((GameObject2D)gameObject).Transform.LocalMatrix = gameObjectData.LocalMatrix;
                }
                gameObject.Name = gameObjectData.Name;
                gameObject.Layer = Layer.GetLayerByNumber(gameObjectData.LayerNumber);
                gameObject.Active = gameObjectData.Active;
                gameObjectData.NewGameObject = gameObject; // Use to recreate the hierarchy.
                foreach (var componentData in gameObjectData.ComponentData)
                {
                    // Create the component.
                    // Reflection is needed because we can't know the type in compiler time and I don't want to use an inflexible big switch sentence.
                    gameObject.GetType().GetMethod("AddComponent").MakeGenericMethod(componentData.Component.GetType()).Invoke(gameObject, null);
                    // Each serializable property will be copy to the new component.
                    PropertyInfo componentProperty = gameObject.GetType().GetProperty(componentData.Component.GetType().Name);
                    List<PropertyInfo> propertiesName = GetSerializableProperties(componentData.Component.GetType());
                    for (int i = 0; i < propertiesName.Count; i++)
                    {
                        var property = propertiesName[i];
                        Component component = (Component) componentProperty.GetValue(gameObject, null);
                        Object value = property.GetValue(componentData.Component, null);
                        property.SetValue(component, value, null);
                    }
                }
            }
            // Recreate hierarchy.
            foreach (var gameObjectData in sceneData.GameObjectData)
            {
                // If it is has a parent.
                if (gameObjectData.ParentId != long.MaxValue)
                {
                    // Search all loaded game objects
                    foreach (var searchedGameObjectData in sceneData.GameObjectData)
                    {
                        if (searchedGameObjectData.Id == gameObjectData.ParentId)
                        {
                            if (gameObjectData.is3D)
                                ((GameObject3D)gameObjectData.NewGameObject).Parent = (GameObject3D)searchedGameObjectData.NewGameObject;
                            else
                                ((GameObject2D)gameObjectData.NewGameObject).Parent = (GameObject2D)searchedGameObjectData.NewGameObject;
                            break;
                        }
                    }
                }
            }
        } // CreateSaveData
Пример #26
0
        /// <summary>
        /// Manage the skin content (mouse cursors, elements' images, fonts, and skin's parameters)
        /// </summary>
        public static void LoadSkin(string skinName)
        {
            CurrentSkinName = skinName;

            AssetContentManager userContentManager = AssetContentManager.CurrentContentManager;

            #region Unload previous skin

            Controls = new SkinList <SkinControlInformation>();
            Fonts    = new SkinList <SkinFont>();
            Images   = new SkinList <SkinImage>();
            #if (WINDOWS)
            Cursors = new SkinList <SkinCursor>();
            #endif

            if (skinContentManager == null)
            {
                skinContentManager = new AssetContentManager {
                    Name = "Skin Content Manager", Hidden = true
                }
            }
            ;
            else
            {
                skinContentManager.Unload();
            }
            AssetContentManager.CurrentContentManager = skinContentManager;

            #endregion

            #region Load Description File

            string fullPath = "Skin" + "\\" + skinName + "\\Description";
            skinDescription = new Document(fullPath);

            // Read XML data.
            if (skinDescription.Resource.Element("Skin") != null)
            {
                try
                {
                    LoadImagesDescription();
                    LoadFontsDescription();
                    #if (WINDOWS)
                    LoadCursorsDescription();
                    #endif
                    LoadControlsDescription();
                }
                catch (Exception e)
                {
                    throw new Exception("Failed to load skin: " + skinName + ".\n\n" + e.Message);
                }
            }
            else
            {
                throw new Exception("Failed to load skin: " + skinName + ". Skin tag doesn't exist.");
            }

            #endregion

            #region Load Resources

            try
            {
                foreach (SkinFont skinFont in Fonts)
                {
                    skinFont.Font = new Font(skinFont.Filename);
                }
                #if (WINDOWS)
                foreach (SkinCursor skinCursor in Cursors)
                {
                    skinCursor.Cursor = new Cursor(skinName + "\\" + skinCursor.Filename);
                }
                #endif
                foreach (SkinImage skinImage in Images)
                {
                    skinImage.Texture = new Texture("Skin\\" + skinName + "\\" + skinImage.Filename);
                }
                foreach (SkinControlInformation skinControl in Controls)
                {
                    foreach (SkinLayer skinLayer in skinControl.Layers)
                    {
                        if (skinLayer.Image.Name != null)
                        {
                            skinLayer.Image = Images[skinLayer.Image.Name];
                        }
                        else
                        {
                            skinLayer.Image = Images[0];
                        }
                        skinLayer.Text.Font = skinLayer.Text.Name != null ? Fonts[skinLayer.Text.Name] : Fonts[0];
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception("Failed to load skin: " + skinName + ".\n\n" + e.Message);
            }

            #endregion

            // Restore user content manager.
            AssetContentManager.CurrentContentManager = userContentManager;
        } // LoadSkin
        } // DisposeManagedResources

        #endregion

        #region Change Content Manager

        /// <summary>
        /// Change the content manager.
        /// </summary>
        public void ChangeContentManager(AssetContentManager contentManager)
        {
            ContentManager = contentManager;
        } // ChangeContentManager