public TransformHierarchy(LocalReference location, LocalReference gameObjectReference, LocalReference parent, int rootIndex, LocalReference prefabInstance, ExternalReference correspondingSourceObject, bool isStripped) : base("Transform", location, gameObjectReference, prefabInstance, correspondingSourceObject, isStripped) { Parent = parent; RootIndex = rootIndex; }
public ScriptComponentHierarchy(LocalReference reference, ExternalReference scriptReference, LocalReference gameObject, LocalReference prefabInstance, ExternalReference correspondingSourceObject , bool isStripped) : base("MonoBehaviour", reference, gameObject, prefabInstance, correspondingSourceObject, isStripped) { ScriptReference = scriptReference; }
public void LoadTextureReferences(TiledMap map, ContentProcessorContext context) { TextureReferences = new Dictionary <string, ExternalReference <Texture2DContent> >(); foreach (var tileset in map.Tilesets) { if ( tileset.Properties.ContainsKey(TilesetParser.IgnoreTilesetTextureFlag) && bool.Parse(tileset.Properties[TilesetParser.IgnoreTilesetTextureFlag]) ) { continue; // Skip texture, if we won't need it. } foreach (var path in tileset.TexturePaths) { if (TextureReferences.ContainsKey(path)) { continue; } var assetReference = new ExternalReference <Texture2DContent>(TiledMapImporter.TmxRootDir + "/" + path); TextureReferences.Add(path, context.BuildAsset <Texture2DContent, Texture2DContent>(assetReference, "", null, "", "")); } } foreach (var imageLayer in map.ImageLayers) { if (TextureReferences.ContainsKey(imageLayer.TexturePath)) { continue; } var asserReference = new ExternalReference <Texture2DContent>(TiledMapImporter.TmxRootDir + "/" + imageLayer.TexturePath); TextureReferences.Add(imageLayer.TexturePath, context.BuildAsset <Texture2DContent, Texture2DContent>(asserReference, "", null, "", "")); } }
public override AtlasContent Process(AtlasDeclaration input, ContentProcessorContext context) { Dictionary <int, Bitmap> images = new Dictionary <int, Bitmap>(); Dictionary <int, string> imageNames = new Dictionary <int, string>(); ImagePacker imagePacker = new ImagePacker(); var imgFiles = input.Images.Select(i => Path.Combine(input.AtlasRootDir, i.Replace('/', '\\'))); if (imgFiles.Count() == 0) { throw new ArgumentException("No Image found"); } Bitmap output; Dictionary <string, Sprite> map; imagePacker.PackImage(imgFiles, true, true, 4096, 4096, 0, true, out output, out map); var finalSprites = map.Select(s => { s.Value.Name = s.Key.Substring(0, s.Key.LastIndexOf('.')).Substring(input.AtlasRootDir.Length + 1).Replace('\\', '/').Trim('.', '/'); return(s.Value); }).ToArray(); var atlasPngPath = Path.Combine(input.AtlasRootDir, input.Name + ".png"); using (FileStream outputSpriteFile = new FileStream(atlasPngPath, FileMode.Create)) { output.Save(outputSpriteFile, ImageFormat.Png); } context.AddOutputFile(atlasPngPath); ExternalReference <TextureContent> texture = new ExternalReference <TextureContent>(atlasPngPath); texture = BuildTexture($"{input.Name}Texture", texture, context); return(new AtlasContent { Texture = texture, Sprites = finalSprites }); }
public ObjectContent(XmlNode node, ObjectTemplateContent template) { this.Name = node.Name; this.TextureReference = template.TextureReference; this.IsTiled = template.IsTiled; this.Origin = template.Origin; this.Source = template.Source; if (node.Attributes["height"] != null) this.Height = int.Parse(node.Attributes["height"].Value, CultureInfo.InvariantCulture); else this.Height = template.Height; if (node.Attributes["x"] != null) this.Position.X = int.Parse(node.Attributes["x"].Value, CultureInfo.InvariantCulture); if (node.Attributes["y"] != null) this.Position.Y = int.Parse(node.Attributes["y"].Value, CultureInfo.InvariantCulture); if (node.Attributes["width"] != null) this.Width = int.Parse(node.Attributes["width"].Value, CultureInfo.InvariantCulture); else this.Width = template.Width; if (node.Attributes["angle"] != null) this.Rotation = float.Parse(node.Attributes["angle"].Value, CultureInfo.InvariantCulture); if (this.IsTiled) { this.Source.Width = this.Width; this.Source.Height = this.Height; } }
/// <summary> /// Writes the name of an external file to the output binary. /// </summary> /// <typeparam name="T">The type of reference.</typeparam> /// <param name="reference">External reference to a data file for the content item.</param> public void WriteExternalReference <T>(ExternalReference <T> reference) { if (reference == null) { Write(string.Empty); } else { string fileName = reference.Filename; if (string.IsNullOrEmpty(fileName)) { Write(string.Empty); } else { // Make sure the filename ends with .xnb if (!fileName.EndsWith(".xnb")) { throw new ArgumentException(string.Format("ExternalReference '{0}' must reference a .xnb file", fileName)); } // Make sure it is in the same root directory if (!fileName.StartsWith(rootDirectory, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(string.Format("ExternalReference '{0}' must be in the root directory '{1}'", fileName, rootDirectory)); } // Strip the .xnb extension fileName = fileName.Substring(0, fileName.Length - 4); // Get the relative directory fileName = PathHelper.GetRelativePath(referenceRelocationPath, fileName); Write(fileName); } } }
/// <summary> /// Converts an array of sprite filenames into a sprite sheet object. /// </summary> public override SpriteSheetContent Process(string[] input, ContentProcessorContext context) { SpriteSheetContent spriteSheet = new SpriteSheetContent(); List <BitmapContent> sourceSprites = new List <BitmapContent>(); // Loop over each input sprite filename. foreach (string inputFilename in input) { // Store the name of this sprite. string spriteName = Path.GetFileNameWithoutExtension(inputFilename); spriteSheet.SpriteNames.Add(spriteName, sourceSprites.Count); // Load the sprite texture into memory. ExternalReference <TextureContent> textureReference = new ExternalReference <TextureContent>(inputFilename); TextureContent texture = context.BuildAndLoadAsset <TextureContent, TextureContent>(textureReference, "TextureProcessor"); sourceSprites.Add(texture.Faces[0][0]); } // Pack all the sprites into a single large texture. BitmapContent packedSprites = SpritePacker.PackSprites(sourceSprites, spriteSheet.SpriteRectangles, context); spriteSheet.Texture.Mipmaps.Add(packedSprites); return(spriteSheet); }
private SpriteHeader ReadHeader(string Header, ContentProcessorContext Context) { var Reader = CreateReader(Header); string FileName = Reader.Read(); string RawSize = Reader.Read(); Rectangle Margins = Rectangle.Empty; if (Reader.HasMore()) { string MarginLeftTop = Reader.Read(); string MarginBottomRight = Reader.Read(); var MLT = ReadIndex(MarginLeftTop); var MBR = ReadIndex(MarginBottomRight); Margins = new Rectangle(MLT.Item1, MLT.Item2, MBR.Item1, MBR.Item2); } var Size = ReadIndex(RawSize); var TextureReference = new ExternalReference <Texture2DContent>(FileName); var Texture = (Texture2DContent)Context.BuildAndLoadAsset <Texture2DContent, TextureContent>(TextureReference, "TextureProcessor"); return(new SpriteHeader() { Columns = Size.Item1, Rows = Size.Item2, Name = Path.GetFileNameWithoutExtension(FileName), Texture = Texture, Margins = Margins }); }
private void ProcessTextures(MaterialContent input, SkinnedModelMaterialContent skinnedModelMaterial, ContentProcessorContext context) { foreach (string key in input.Textures.Keys) { ExternalReference <TextureContent> texture = input.Textures[key]; if (!String.IsNullOrEmpty(texturePath)) { string fullFilePath; if (texturePathType == PathType.Relative) { // If relative path string sourceAssetPath = Path.GetDirectoryName(input.Identity.SourceFilename); fullFilePath = Path.GetFullPath( Path.Combine(sourceAssetPath, texturePath)); } else { fullFilePath = texturePath; } texture.Filename = Path.Combine(fullFilePath, Path.GetFileName(texture.Filename)); } ProcessTexture(key, texture, skinnedModelMaterial, context); } }
public override ExternalReference <TOutput> BuildAsset <TInput, TOutput>(ExternalReference <TInput> sourceAsset, string processorName, OpaqueDataDictionary processorParameters, string importerName, string assetName) { throw new NotImplementedException(); }
public override TOutput BuildAndLoadAsset <TInput, TOutput>(ExternalReference <TInput> sourceAsset, string processorName, OpaqueDataDictionary processorParameters, string importerName) { var sourceFilepath = PathHelper.Normalize(sourceAsset.Filename); // The processorName can be null or empty. In this case the asset should // be imported but not processed. This is, for example, necessary to merge // animation files as described here: // http://blogs.msdn.com/b/shawnhar/archive/2010/06/18/merging-animation-files.aspx. bool processAsset = !string.IsNullOrEmpty(processorName); _manager.ResolveImporterAndProcessor(sourceFilepath, ref importerName, ref processorName); var buildEvent = new PipelineBuildEvent { SourceFile = sourceFilepath, Importer = importerName, Processor = processAsset ? processorName : null, Parameters = _manager.ValidateProcessorParameters(processorName, processorParameters), }; var processedObject = _manager.ProcessContent(buildEvent); // Record that we processed this dependent asset. _pipelineEvent.Dependencies.AddUnique(sourceFilepath); return((TOutput)processedObject); }
public override TOutput Process(TInput input, ContentProcessorContext context) { ExternalReference <TextureContent> texture = new ExternalReference <TextureContent>(input.TexturePath); input.Texture = context.BuildAndLoadAsset <TextureContent, TextureContent>(texture, null); return(input); }
/// <summary> /// Processes the raw .tsx XML and creates a TilesetContent /// for use in an XNA framework game /// </summary> /// <param name="input">The XML string</param> /// <param name="context">The pipeline context</param> /// <returns>A TilesetContent instance corresponding to the tsx input</returns> public override TOutput Process(TInput input, ContentProcessorContext context) { // Process the Tilesets for (int i = 0; i < input.Tilesets.Count; i++) { var tileset = input.Tilesets[i]; ExternalReference <TilesetContent> externalRef = new ExternalReference <TilesetContent>(tileset.Source); tileset.Reference = context.BuildAsset <TilesetContent, TilesetContent>(externalRef, "TilesetProcessor"); } foreach (TilemapLayerContent layer in input.Layers) { List <uint> dataIds = new List <uint>(); foreach (var id in layer.DataString.Split(',')) { dataIds.Add(uint.Parse(id)); } ; layer.Data = dataIds.ToArray(); } foreach (TilemapObjectContent obj in input.Objects) { } // The tileset has been processed return(input); }
private void LoadFromPackagesConfig() { IEnumerable <PackageReference> packageReferences = new List <PackageReference>(); string packageConfig = Path.Combine(_projectDir, Constants.PackagesConfig); if (File.Exists(packageConfig)) { try { using var fileStream = new FileStream(packageConfig, FileMode.Open); var configReader = new PackagesConfigReader(fileStream); var packages = configReader.GetPackages(true); packages?.ToList().ForEach(package => { var reference = new ExternalReference() { Identity = package.PackageIdentity.Id, Version = package.PackageIdentity.Version.OriginalVersion }; if (!_externalReferences.NugetReferences.Contains(reference)) { _externalReferences.NugetReferences.Add(reference); } }); } catch (Exception ex) { Logger.LogError(ex, "Error while parsing file {0}", packageConfig); } } }
public override ExternalReference <TOutput> BuildAsset <TInput, TOutput>(ExternalReference <TInput> sourceAsset, string processorName, OpaqueDataDictionary processorParameters, string importerName, string assetName) { if (string.IsNullOrEmpty(assetName)) { var contentPath = PathHelper.GetRelativePath(_manager.ProjectDirectory, sourceAsset.Filename); var filename = Path.GetFileNameWithoutExtension(contentPath); var path = Path.GetDirectoryName(contentPath); // TODO: Is this only does for textures or // for all sub-assets like this? // // TODO: Replace the _0 with a hex 32bit hash of // the processor+parameters. This ensures no collisions // when two models process textures with different settings. // assetName = Path.Combine(path, filename) + "_0"; } // Build the content. var buildEvent = _manager.BuildContent(sourceAsset.Filename, assetName, importerName, processorName, processorParameters); // Record that we built this dependent asset. _pipelineEvent.BuildAsset.AddUnique(buildEvent.DestFile); return(new ExternalReference <TOutput>(buildEvent.DestFile)); }
/// <summary> /// Converts an array of sprite filenames into a texture atlas object. /// </summary> public override TextureAtlasContent Process(string[] input, ContentProcessorContext context) { logger = context.Logger; var textureAtlas = new TextureAtlasContent { animationFPS = (int)animationFPS }; var sourceSprites = new List <BitmapContent>(); var imagePaths = new List <string>(); // first, we need to sort through and figure out which passed in paths are images and which are folders foreach (var inputPath in input) { // first, the easy one. if it isnt a directory its an image so just add it if (!Directory.Exists(inputPath)) { if (isValidImageFile(inputPath)) { imagePaths.Add(inputPath); } continue; } // we have a directory. we need to recursively add all images in all subfolders processDirectory(inputPath, imagePaths, textureAtlas); } // Loop over each input sprite filename foreach (var inputFilename in imagePaths) { // Store the name of this sprite. var spriteName = getSpriteNameFromFilename(inputFilename, input); textureAtlas.spriteNames.Add(spriteName, sourceSprites.Count); context.Logger.LogMessage("Adding texture: {0}", spriteName); // Load the sprite texture into memory. var textureReference = new ExternalReference <TextureContent>(inputFilename); var texture = context.BuildAndLoadAsset <TextureContent, TextureContent>(textureReference, "TextureProcessor"); if (inputFilename.Contains(".9")) { logger.LogMessage("\tprocessing nine patch texture"); textureAtlas.nineSliceSplits[spriteName] = processNinePatchTexture(texture); } sourceSprites.Add(texture.Faces[0][0]); } // Pack all the sprites into a single large texture. var packedSprites = TextureAtlasPacker.packSprites(sourceSprites, textureAtlas.spriteRectangles, compressTexture, context); textureAtlas.texture.Mipmaps.Add(packedSprites); if (compressTexture) { textureAtlas.texture.ConvertBitmapType(typeof(Dxt5BitmapContent)); } return(textureAtlas); }
protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context) { EffectMaterialContent myMaterial = new EffectMaterialContent(); if (material is BasicMaterialContent) { return(base.ConvertMaterial(material, context)); } else if (material is EffectMaterialContent) { EffectMaterialContent effectMaterialContent = (EffectMaterialContent)material; // // remap effect // myMaterial.Effect = new ExternalReference <EffectContent>(effectMaterialContent.Effect.Filename); // textures foreach (KeyValuePair <string, ExternalReference <TextureContent> > pair in effectMaterialContent.Textures) { string textureKey = pair.Key; ExternalReference <TextureContent> textureContent = pair.Value; if (!string.IsNullOrEmpty(textureContent.Filename)) { myMaterial.Textures.Add(textureKey, material.Textures[textureKey]); } } } return(base.ConvertMaterial(myMaterial, context)); }
/// <summary> /// Processes the raw .tsx XML and creates a TilesetContent /// for use in an XNA framework game /// </summary> /// <param name="input">The XML string</param> /// <param name="context">The pipeline context</param> /// <returns>A TilesetContent instance corresponding to the tsx input</returns> public override TOutput Process(TInput input, ContentProcessorContext context) { // Process the Tilesets for (int i = 0; i < input.Tilesets.Count; i++) { var tileset = input.Tilesets[i]; ExternalReference <TilesetContent> externalRef = new ExternalReference <TilesetContent>(tileset.Source); tileset.Reference = context.BuildAsset <TilesetContent, TilesetContent>(externalRef, "TilesetProcessor"); } foreach (TilemapLayerContent layer in input.Layers) { List <uint> dataIds = new List <uint>(); foreach (var id in layer.DataString.Split(',')) { dataIds.Add(uint.Parse(id)); } ; layer.Data = dataIds.ToArray(); } // Correction for tile objects X,Y being left,bottom origin instead of left,top foreach (TilemapObjectGroupContent objectGroup in input.ObjectGroups) { foreach (ObjectGroupObjects groupObject in objectGroup.Objects) { groupObject.Y -= input.TileHeight; } } // The tileset has been processed return(input); }
/// <summary> /// Imports the asset. /// </summary> /// <param name="context">Contains any required custom process parameters.</param> public void Import(ContentProcessorContext context) { if (context == null) throw new ArgumentNullException("context"); if (string.IsNullOrWhiteSpace(ModelDescription.FileName)) throw new InvalidContentException("The attribute 'File' is not set in the model description (.drmdl file).", Identity); var fileName = ContentHelper.FindFile(ModelDescription.FileName, Identity); var asset = new ExternalReference<NodeContent>(fileName); var node = context.BuildAndLoadAsset<NodeContent, NodeContent>(asset, null, null, ModelDescription.Importer); // BuildAndLoadAsset does not return root node in MonoGame. while (node.Parent != null) node = node.Parent; if (node.GetType() == typeof(NodeContent)) { // Root node is of type NodeContent. // --> Copy root node content and children. Name = node.Name; Transform = node.Transform; Animations.AddRange(node.Animations); OpaqueData.AddRange(node.OpaqueData); var children = node.Children.ToArray(); node.Children.Clear(); // Clear parents. Children.AddRange(children); } else { // Root node is a derived type. // --> Add node as child. Children.Add(node); } }
private string BuildTexture(string textureName) { if (textureName == null || textureName.Length == 0) { return(""); } string assetLocation = new FileInfo(rootPath).DirectoryName + @"/" + textureName; string comparePath = rootPath; if (importTextures) { OpaqueDataDictionary processorParameters = new OpaqueDataDictionary(); processorParameters.Add("ColorKeyColor", this.colourKeyColour); processorParameters.Add("ColorKeyEnabled", this.ColorKeyEnabled); processorParameters.Add("TextureFormat", this.TextureFormat); processorParameters.Add("GenerateMipmaps", this.GenerateMipmaps); processorParameters.Add("ResizeToPowerOfTwo", this.ResizeTexturesToPowerOfTwo); ExternalReference <TextureContent> texture = context.BuildAsset <TextureContent, TextureContent>(new ExternalReference <TextureContent>(textureName, new ContentIdentity(rootPath)), typeof(TextureProcessor).Name, processorParameters, null, null); assetLocation = texture.Filename; comparePath = context.OutputFilename; } else { if (!File.Exists(assetLocation)) { context.Logger.LogWarning("", new ContentIdentity(rootPath), "File not found:\t{1} ({0})", textureName, @".\" + GetSharedPath(assetLocation, comparePath) + new FileInfo(assetLocation).Extension); return(""); } } return(GetSharedPath(assetLocation, comparePath)); }
/// <summary> /// Produces ModelAnimationInfo from skeleton and animations. /// </summary> /// <param name="input">skeleton</param> /// <param name="context">The context for this processor</param> /// <returns>AnimationContentDictionary</returns> public override AnimationContentDictionary Process(BoneContent input, ContentProcessorContext context) { inputSkeleton = input; inputSkeleton.Identity.FragmentIdentifier = ""; this.context = context; string modelFilePath = GetModelFilePath(inputSkeleton.Identity); if (modelFilePath != null) { context.Logger.LogWarning("", inputSkeleton.Identity, "animation will be checked against model " + modelFilePath); ExternalReference <NodeContent> er = new ExternalReference <NodeContent>(modelFilePath); model = (NodeContent)context.BuildAndLoadAsset <NodeContent, Object>(er, "PassThroughProcessor"); modelSkeleton = MeshHelper.FindSkeleton(model); CheckBones(modelSkeleton, inputSkeleton); } else { context.Logger.LogWarning("", inputSkeleton.Identity, "corresponding model not found"); context.Logger.LogWarning("", inputSkeleton.Identity, "animation filename should follow the <modelName>_<animationName>.<ext> pattern to get animation skeleton checked against model"); } AnimationContentDictionary animations = Interpolate(input.Animations); return(animations); }
//private class resp //{ // public string code { get; set; } // public string date { get; set; } //}; public string GetCheckoutMercadoPago(string titulo, decimal preco, int alunoId, int cursoId, string cupom) { // Cria um objeto de preferência Preference preference = new Preference(); // Cria um item na preferência preference.Items.Add( new Item() { Title = titulo, Quantity = 1, CurrencyId = CurrencyId.BRL, UnitPrice = (decimal)preco } ); //var request = _httpContext.HttpContext.Request; //var basePath = request.Host + request.PathBase; //preference.BackUrls = new BackUrls() //{ // Success = basePath + "/Pagamentos/MercadoPagoSuccess", // Failure = basePath + "/Pagamentos/MercadoPagoFailure", // Pending = basePath + "/Pagamentos/MercadoPagoPending" //}; ExternalReference er = new ExternalReference("A" + alunoId + "C" + cursoId + "X" + cupom); preference.ExternalReference = "A" + alunoId + "C" + cursoId + "X" + cupom; preference.Save(); //ViewData["Code"] = preference.Id; return(preference.Id); }
private bool ValidateNewReport( BrokenExternalReferencesReport report, ItInterface includedInterfaceWhichFails, EndpointValidationError expectedInterfaceError, BrokenLinkCause brokenLinkCauseForInterface, ExternalReference includedReferenceWhichFails, EndpointValidationError expectedReferenceError, BrokenLinkCause brokenLinkCauseForReference) { Assert.Equal(_now, report.Created); var brokenLinkInInterface = Assert.Single(report.BrokenInterfaceLinks); Assert.Same(includedInterfaceWhichFails, brokenLinkInInterface.BrokenReferenceOrigin); Assert.Equal(brokenLinkInInterface.ErrorResponseCode, (int?)expectedInterfaceError.StatusCode); Assert.Equal(brokenLinkInInterface.Cause, brokenLinkCauseForInterface); Assert.Equal(brokenLinkInInterface.ValueOfCheckedUrl, includedInterfaceWhichFails.Url); var brokenLinkInExternalReference = Assert.Single(report.BrokenExternalReferences); Assert.Same(includedReferenceWhichFails, brokenLinkInExternalReference.BrokenReferenceOrigin); Assert.Equal(brokenLinkInExternalReference.ErrorResponseCode, (int?)expectedReferenceError.StatusCode); Assert.Equal(brokenLinkInExternalReference.ValueOfCheckedUrl, includedReferenceWhichFails.URL); Assert.Equal(brokenLinkInExternalReference.Cause, brokenLinkCauseForReference); return(true); }
/// <summary> /// Builds Distorter textures with the DisplacementMapProcessor /// </summary> protected override ExternalReference <TextureContent> BuildTexture( string textureName, ExternalReference <TextureContent> texture, ContentProcessorContext context) { return(context.BuildAsset <TextureContent, TextureContent>(texture, "DisplacementMapProcessor")); }
/// <summary> /// Processes the raw .tsx XML and creates a TilesetContent /// for use in an XNA framework game /// </summary> /// <param name="input">The XML string</param> /// <param name="context">The pipeline context</param> /// <returns>A TilesetContent instance corresponding to the tsx input</returns> public override TOutput Process(TInput input, ContentProcessorContext context) { // The image is a separate file - we need to create an external reference to represent it // Then we can load that file through the content pipeline and embed it into the TilesetContent ExternalReference <TextureContent> externalRef = new ExternalReference <TextureContent>(input.ImageFilename); OpaqueDataDictionary options = new OpaqueDataDictionary(); if (input.ImageColorKey != null) { options.Add("ColorKeyColor", input.ImageColorKey); } input.Texture = context.BuildAndLoadAsset <TextureContent, TextureContent>(externalRef, "TextureProcessor", options, "TextureImporter"); // Create the Tiles array input.Tiles = new TileContent[input.TileCount]; // Run the logic to generate the individual tile source rectangles for (int i = 0; i < input.TileCount; i++) { var source = new Rectangle( (i % input.Columns) * (input.TileWidth + input.Spacing) + input.Margin, // x coordinate (i / input.Columns) * (input.TileHeight + input.Spacing) + input.Margin, // y coordinate input.TileWidth, input.TileHeight ); input.Tiles[i] = new TileContent(source); } // The tileset has been processed return(input); }
/// <summary> /// builds an external reference to a texture /// </summary> internal static ExternalReference <TextureContent> BuildTexture(string file, ContentProcessorContext context) { ExternalReference <Texture2DContent> tex = new ExternalReference <Texture2DContent>(file); tex.Name = Path.GetFileNameWithoutExtension(file); CreateDictionaryIfNecessary(); //string extension = Path.GetExtension(file); //UseBlackAsAlpha = extension.ToLower() == ".bmp"; //if (UseBlackAsAlpha) //{ // TextureProcessor.ColorKeyColor = Color.Black; // TextureProcessor.ColorKeyEnabled = true; //} //else //{ // TextureProcessor.ColorKeyEnabled = false; //} return(context.BuildAsset <Texture2DContent, TextureContent>( tex, typeof(TextureProcessor).Name, dictionary, "TextureImporter", null // Passing null lets the content pipeline decide on the default name, which is what we want. )); }
public void BuildExternalReference <TInput>(ContentProcessorContext context, string source, OpaqueDataDictionary parameters = null) { var sourceAsset = new ExternalReference <TInput>(source); var externalReference = context.BuildAsset <TInput, TInput>(sourceAsset, "", parameters, "", ""); _externalReferences.Add(source, externalReference); }
private ExternalReference<TextureContent> BuildTexture(string textureName, ExternalReference<TextureContent> texture, ContentProcessorContext context, ContentIdentity identity) { // Finding resources is not as robust in MonoGame: Fix path. texture.Filename = ContentHelper.FindFile(texture.Filename, identity); return OnBuildTexture(textureName, texture, context); }
public override AnimationData Process(AnimationData input, ContentProcessorContext context) { var inRef = new ExternalReference <TextureContent>(input.sheet); input.sheetRef = context.BuildAsset <TextureContent, TextureContent>(inRef, "TextureProcessor"); return(input); }
/// <summary> /// Reads a reference to another input that is external to this input. /// </summary> /// <typeparam name="T">Type of object to read</typeparam> /// <returns> /// Object read /// </returns> public T ReadExternal <T>() where T : ISavable { if (_input.ReadSByte() == -1) { return(default(T)); } bool isExternal = _input.ReadBoolean(); if (isExternal) { ExternalReference extReference = ReadSavable <ExternalReference>(); return(ContentManager.Load <T>(extReference.FileName, extReference.LoaderParameters)); } //Otherwise load the savable as usual Object obj = CreateType(); if (!(obj is T)) { throw new InvalidCastException("Cannot read savable as the requested type."); } T savable = (T)obj; savable.Read(this); return(savable); }
public void ReadExternalReference <T>(ExternalReference <T> existingInstance) { if (!MoveToElement("Reference")) { return; } var str = Xml.ReadElementContentAsString(); Action <Type, string> fixup = (type, filename) => { if (type != typeof(T)) { throw NewInvalidContentException(null, "Invalid external reference type"); } existingInstance.Filename = filename; }; List <Action <Type, string> > fixups; if (!_externalReferences.TryGetValue(str, out fixups)) { _externalReferences.Add(str, fixups = new List <Action <Type, string> >()); } fixups.Add(fixup); }
public override BitmapFontProcessorResult Process(BitmapFontFile bitmapFontFile, ContentProcessorContext context) { try { context.Logger.LogMessage("Processing BMFont, Kerning pairs: {0}", bitmapFontFile.Kernings.Count); var result = new BitmapFontProcessorResult(bitmapFontFile); result.PackTexturesIntoXnb = PackTexturesIntoXnb; foreach (var fontPage in bitmapFontFile.Pages) { // find our texture so we can embed it in the xnb asset var imageFile = Path.Combine(Path.GetDirectoryName(bitmapFontFile.File), fontPage.File); context.Logger.LogMessage("looking for image file: {0}", imageFile); if (!File.Exists(imageFile)) { throw new Exception(string.Format("Could not locate font atlas file {0} relative to folder {1}", fontPage.File, Directory.GetCurrentDirectory())); } if (PackTexturesIntoXnb) { context.Logger.LogMessage("Found texture: {0}. Packing into xnb", imageFile); var textureReference = new ExternalReference <TextureContent>(imageFile); var texture = context.BuildAndLoadAsset <TextureContent, TextureContent>(textureReference, "TextureProcessor"); var textureContent = new Texture2DContent(); textureContent.Mipmaps.Add(texture.Faces[0][0]); if (CompressTextures) { textureContent.ConvertBitmapType(typeof(Dxt5BitmapContent)); } result.Textures.Add(textureContent); } else { var textureFilename = PathHelper.MakeRelativePath(Directory.GetCurrentDirectory(), imageFile) .Replace("Content/", string.Empty); textureFilename = Path.ChangeExtension(textureFilename, null); context.Logger.LogMessage( "Not writing texture but it is expected to exist and be processed: {0}", textureFilename); result.TextureNames.Add(textureFilename); result.TextureOrigins.Add(new Vector2(fontPage.X, fontPage.Y)); } } return(result); } catch (Exception ex) { context.Logger.LogMessage("Error {0}", ex); throw; } }
protected override ExternalReference<CompiledEffectContent> BuildEffect(ExternalReference<EffectContent> effect, ContentProcessorContext context) { OpaqueDataDictionary processorParameters = new OpaqueDataDictionary(); if (context.Parameters.ContainsKey("Defines")) processorParameters.Add("Defines", context.Parameters["Defines"]); return context.BuildAsset<EffectContent, CompiledEffectContent>(effect, "DeferredRendererFXProcessor", processorParameters, "EffectImporter", effect.Name); }
protected override ExternalReference<TextureContent> BuildTexture(string textureName, ExternalReference<TextureContent> texture, ContentProcessorContext context) { // Named textures will each have their own custom processor switch (textureName) { case HMModelProcessor.SPECULAR_MAP_KEY: return context.BuildAsset<TextureContent, TextureContent>(texture, typeof (HMSpecularProcessor).Name); default: // Default processing for all others return base.BuildTexture(textureName, texture, context); } }
public FluidSurface() { Effect = new ExternalReference<EffectContent>(); DiffuseColor = Vector3.One; EmissiveColor = Vector3.Zero; SpecularColor = Vector3.One; SpecularPower = 1.0f; MinAlpha = 0.5f; MaxAlpha = 0.9f; DistanceAlphaFactor = 0.01f; SpringPower = 0.2f; }
protected override ExternalReference<TextureContent> BuildTexture(string textureName, ExternalReference<TextureContent> texture, ContentProcessorContext context) { if (textureName == NormalMappingModelProcessor.NormalMapKey) { // put the normal map through the special NormalMapTextureProcessor, // which will convert it to a signed format. return context.BuildAsset<TextureContent, TextureContent>(texture, typeof(NormalMapTextureProcessor).Name); } // Apply default processing to all other textures. return base.BuildTexture(textureName, texture, context); }
protected override ExternalReference<TextureContent> BuildTexture(string textureName, ExternalReference<TextureContent> texture, ContentProcessorContext context) { // Fallback if we aren't buiding for iOS. var platform = ContentHelper.GetMonoGamePlatform(); if (platform != MonoGamePlatform.iOS) return base.BuildTexture(textureName, texture, context); var processorParameters = new OpaqueDataDictionary(); processorParameters.Add("ColorKeyColor", this.ColorKeyColor); processorParameters.Add("ColorKeyEnabled", this.ColorKeyEnabled); processorParameters.Add("TextureFormat", this.TextureFormat); processorParameters.Add("GenerateMipmaps", this.GenerateMipmaps); processorParameters.Add("ResizeToPowerOfTwo", this.ResizeTexturesToPowerOfTwo); processorParameters.Add("PremultiplyAlpha", this.PremultiplyTextureAlpha); return context.BuildAsset<TextureContent, TextureContent>(texture, typeof(MGTextureProcessor).Name, processorParameters, null, null); }
public Reader retrieve(ExternalReference externalReference, String _string) { try { Reader _in = new java.io.InputStreamReader(externalReference.getUri().toURL().openConnection().getInputStream(), "UTF-8"); char[] buf = new char[4096]; StringBuilder sb = new StringBuilder(); for (int n; (n = _in.read(buf)) > 0; ) { sb.Append(buf, 0, n); } return new java.io.StringReader(sb.ToString()); } catch (Exception ex) { throw new UriCallbackException(externalReference, ex); } }
private string GetTextureFileName(ExternalReference<TextureContent> texture) { try { return ContentHelper.FindFile(texture.Filename, _input.Identity); } catch (InvalidContentException) { // Referenced texture file not found. // No problem - use file name, but strip path. return Path.GetFileName(texture.Filename); } }
protected virtual ExternalReference<DRMaterialContent> OnBuildMaterial(ExternalReference<DRMaterialContent> material, ContentProcessorContext context) { return context.BuildAsset<DRMaterialContent, DRMaterialContent>(material, typeof(DRMaterialProcessor).Name, null, typeof(DRMaterialImporter).Name, null); }
/// <summary> /// Builds the material. /// </summary> /// <param name="material"> /// The external material (<see cref="string"/>) or the local material /// (<see cref="MaterialContent"/>). /// </param> /// <returns> /// The processed material. /// </returns> private object BuildMaterial(object material) { object convertedMaterial; if (!_materials.TryGetValue(material, out convertedMaterial)) { string name = material as string; if (name != null) { // Build external material (XML file). string fileName = ContentHelper.FindFile(name, _input.Identity); var reference = new ExternalReference<DRMaterialContent>(fileName); convertedMaterial = OnBuildMaterial(reference, _context); } else { // Build local material. convertedMaterial = OnConvertMaterial((MaterialContent)material, _context); } } return convertedMaterial; }
public V2DContentHolder GetV2DContent(ContentProcessorContext context) { V2DContentHolder result = new V2DContentHolder(); result.v2dWorld = genV2d.v2dWorld;// V2DWorld.CreateFromXml(genV2d.path); //XmlSerializer xs = new XmlSerializer(typeof(V2DWorld)); //StringWriter sw = new StringWriter(); //xs.Serialize(sw, result.v2dWorld); result.contentTextures.Clear(); foreach (string s in usedImages.Keys) { ExternalReference<TextureContent> tr = new ExternalReference<TextureContent>(s); Texture2DContent texture = context.BuildAndLoadAsset<TextureContent, Texture2DContent>(tr, null); result.contentTextures.Add(Path.GetFileNameWithoutExtension(s), texture); } return result; }
/// <summary> /// プロセッサ処理 /// </summary> public override MaterialContent Process(MaterialContent input, ContentProcessorContext context) { MaterialContent finalinput; if (context.TargetPlatform == TargetPlatform.WindowsPhone) { finalinput = input; } else { BasicMaterialContent basicinput = input as BasicMaterialContent; if(basicinput==null) throw new InvalidContentException(string.Format( "MMDProcessorはEffectMaterialContentのみをサポートします" + "入力メッシュは{0}を使用しています。", input.GetType())); ExternalReference<EffectContent> effect; //リソースからファイルを作成して読み込むという超セコイ方法…… if (!Directory.Exists("ext")) Directory.CreateDirectory("ext"); FileStream fs; if (context.TargetPlatform == TargetPlatform.Windows) { fs = new FileStream(Path.Combine("ext", "MMDWinEffect.fx"), FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(MMDXResource.MMDWinEffect); bw.Close(); effect = new ExternalReference<EffectContent>(Path.Combine("ext", "MMDWinEffect.fx")); } else if (context.TargetPlatform == TargetPlatform.Xbox360) { fs = new FileStream(Path.Combine("ext", "MMDXBoxEffect.fx"), FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(MMDXResource.MMDXBoxEffect); bw.Close(); effect = new ExternalReference<EffectContent>(Path.Combine("ext", "MMDXBoxEffect.fx")); } else throw new NotImplementedException("ターゲットプラットフォーム:" + context.TargetPlatform.ToString() + " は対応していません"); EffectMaterialContent effectcontent = new EffectMaterialContent(); effectcontent.Effect = effect; //パラメータ設定 effectcontent.OpaqueData.Add("ShaderIndex", ShaderIndex); //パラメータコピー foreach (var data in basicinput.OpaqueData) { effectcontent.OpaqueData.Add(data.Key, data.Value); } //テクスチャのコピー if (basicinput.Textures.Count > 0) { foreach (var it in basicinput.Textures) { effectcontent.Textures.Add(it.Key, it.Value); } } //データの渡し finalinput = effectcontent; } //テクスチャの事前アルファ計算は無し this.PremultiplyTextureAlpha = false; return base.Process(finalinput, context); }
protected virtual void ProcessTexture(string key, ExternalReference<TextureContent> texture, MaterialContent output, ContentProcessorContext context) { if (output is SkinnedModelMaterialContent) { SkinnedModelMaterialContent skinnedModelMaterial = output as SkinnedModelMaterialContent; if (key.Equals(DiffuseMapKey)) { skinnedModelMaterial.DiffuseMapEnabled = true; skinnedModelMaterial.DiffuseMapContent = base.BuildTexture(key, texture, context); } else if (key.Equals(NormalMapKey)) { skinnedModelMaterial.NormalMapEnabled = true; skinnedModelMaterial.NormalMapContent = base.BuildTexture(key, texture, context); } else if (key.Equals(SpecularMapKey)) { skinnedModelMaterial.SpecularMapEnabled = true; skinnedModelMaterial.SpecularMapContent = base.BuildTexture(key, texture, context); } } else if (output is SkinnedMaterialContent) { SkinnedMaterialContent skinnedModelMaterial = output as SkinnedMaterialContent; if (key.Equals(DiffuseMapKey)) { skinnedModelMaterial.Texture = base.BuildTexture(key, texture, context); context.Logger.LogWarning(null, null, "built {0}", skinnedModelMaterial.Texture.Filename); } } }
public V2DContent GetV2DContent(ContentProcessorContext context) { V2DContent result = new V2DContent(); result.v2dWorld = v2dWorld; //XmlSerializer xs = new XmlSerializer(typeof(V2DWorld)); //StringWriter sw = new StringWriter(); //xs.Serialize(sw, result.v2dWorld); result.contentTextures.Clear(); foreach (string s in paths.Values) { ExternalReference<TextureContent> tr = new ExternalReference<TextureContent>(s); Texture2DContent texture = context.BuildAndLoadAsset<TextureContent, Texture2DContent>(tr, null); result.contentTextures.Add(Path.GetFileNameWithoutExtension(s), texture); } return result; }
/// <summary> /// Builds a texture for use by this material. /// </summary> protected override ExternalReference<TextureContent> BuildTexture( string textureName, ExternalReference<TextureContent> texture, ContentProcessorContext context) { // Use our custom CubemapProcessor for the environment map texture. if (textureName == "EnvironmentMap") { return context.BuildAsset<TextureContent, TextureContent>(texture, "CubemapProcessor"); } // Apply default processing to all other textures. return base.BuildTexture(textureName, texture, context); }
/// <summary> /// プロセッサ処理 /// </summary> public override MaterialContent Process(MaterialContent input, ContentProcessorContext context) { MaterialContent finalinput; if (context.TargetPlatform == TargetPlatform.WindowsPhone) { finalinput = input; } else { BasicMaterialContent basicinput = input as BasicMaterialContent; if (basicinput == null) throw new InvalidContentException(string.Format( "MMDProcessorはEffectMaterialContentのみをサポートします" + "入力メッシュは{0}を使用しています。", input.GetType())); ExternalReference<EffectContent> effect; //リソースからファイルを作成して読み込むという超セコイ方法…… if (!Directory.Exists("ext")) Directory.CreateDirectory("ext"); FileStream fs; fs = new FileStream(Path.Combine("ext", "MMDAccessoryEffect.fx"), FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(MMDXResource.AccessoryEffect); bw.Close(); effect = new ExternalReference<EffectContent>(Path.Combine("ext", "MMDAccessoryEffect.fx")); EffectMaterialContent effectcontent = new EffectMaterialContent(); effectcontent.Effect = effect; //パラメータコピー foreach (var data in basicinput.OpaqueData) { effectcontent.OpaqueData.Add(data.Key, data.Value); } //テクスチャのコピー if (basicinput.Textures.Count > 0) { foreach (var it in basicinput.Textures) { if (string.IsNullOrEmpty(it.Value.Filename)) continue; if (it.Value.Filename.IndexOf('*') != -1) { string[] files = it.Value.Filename.Split('*'); foreach(var file in files){ if (Path.GetExtension(file) == ".sph" || Path.GetExtension(file) == ".spa") { effectcontent.Textures.Add("Sphere", new ExternalReference<TextureContent>(CreateSpherePath(file))); } else { effectcontent.Textures.Add(it.Key, new ExternalReference<TextureContent>(file)); } } } else if (Path.GetExtension(it.Value.Filename) == ".sph" || Path.GetExtension(it.Value.Filename) == ".spa") { it.Value.Filename = CreateSpherePath(it.Value.Filename); effectcontent.Textures.Add("Sphere", it.Value); } else effectcontent.Textures.Add(it.Key, it.Value); } } //パラメータ設定 effectcontent.OpaqueData.Add("ShaderIndex", ShaderIndex); //データの渡し finalinput = effectcontent; } //事前アルファOff this.PremultiplyTextureAlpha = false; return base.Process(finalinput, context); }
public java.net.URI rewrite(ExternalReference externalReference, String _string) { return new java.net.URI(retrievedUri.resolve(Uri.parse(externalReference.getUri().toString())).ToString()); }
public UriCallbackOption getOption(ExternalReference externalReference, String _string) { return UriCallbackOption.REWRITE; }
protected virtual void ProcessTexture(string key, ExternalReference<TextureContent> texture, SkinnedModelMaterialContent skinnedModelMaterial, ContentProcessorContext context) { if (key.Equals(DiffuseMapKey)) { skinnedModelMaterial.DiffuseMapEnabled = true; skinnedModelMaterial.DiffuseMapContent = base.BuildTexture(key, texture, context); } else if (key.Equals(NormalMapKey)) { skinnedModelMaterial.NormalMapEnabled = true; skinnedModelMaterial.NormalMapContent = base.BuildTexture(key, texture, context); } else if (key.Equals(SpecularMapKey)) { skinnedModelMaterial.SpecularMapEnabled = true; skinnedModelMaterial.SpecularMapContent = base.BuildTexture(key, texture, context); } }
protected override ExternalReference<CompiledEffectContent> BuildEffect(ExternalReference<EffectContent> effect, ContentProcessorContext context) { return context.BuildAsset<EffectContent, CompiledEffectContent>(effect, typeof(MGEffectProcessor).Name); }
/// <summary> /// builds an external reference to a texture /// </summary> internal static ExternalReference<TextureContent> BuildTexture(string file, ContentProcessorContext context) { ExternalReference<Texture2DContent> tex = new ExternalReference<Texture2DContent>(file); tex.Name = Path.GetFileNameWithoutExtension(file); CreateDictionaryIfNecessary(); //string extension = Path.GetExtension(file); //UseBlackAsAlpha = extension.ToLower() == ".bmp"; //if (UseBlackAsAlpha) //{ // TextureProcessor.ColorKeyColor = Color.Black; // TextureProcessor.ColorKeyEnabled = true; //} //else //{ // TextureProcessor.ColorKeyEnabled = false; //} return context.BuildAsset<Texture2DContent, TextureContent>( tex, typeof(TextureProcessor).Name, dictionary, "TextureImporter", null // Passing null lets the content pipeline decide on the default name, which is what we want. ); }
private void loadMaterials(string path) { Dictionary<string, SkinInfo>.Enumerator skins = skin_list.GetEnumerator(); while (skins.MoveNext()) { string key = skins.Current.Key; if (key.IndexOf("_default")>=0) { //load default skin (textures) SkinInfo s = skins.Current.Value; for (int i = 0; i < s.textures_info.Count; ++i) { string material_key = Path.GetFileNameWithoutExtension(s.textures_info[i].texture_name); if (materials_list.ContainsKey(material_key) == false) { string filename = path + "/" + s.textures_info[i].texture_name; if (File.Exists(filename)) { ContentIdentity mtl_file_identity = new ContentIdentity(filename); ExternalReference<TextureContent> Texture = new ExternalReference<TextureContent>( s.textures_info[i].texture_name, mtl_file_identity); Texture.Name = material_key; materials_list.Add(material_key, Texture); } } if (skin_default.ContainsKey(s.textures_info[i].mesh_name) == false) { skin_default.Add(s.textures_info[i].mesh_name, material_key); } } } } }
/// <summary> /// Constructs a new tile instance and initalizes the /// Texture external reference /// </summary> /// <param name="filename">The filename of the texture</param> public TileContent(string filename) { Image = new ExternalReference<TextureContent>(filename); }