/// <summary>
        /// Changes all the materials to use our skinned model effect.
        /// </summary>
        protected override MaterialContent ConvertMaterial(MaterialContent material,
                                                           ContentProcessorContext context)
        {
            BasicMaterialContent basicMaterial = material as BasicMaterialContent;

            if (basicMaterial == null)
            {
                throw new InvalidContentException(string.Format(
                                                      "SkinnedModelProcessor only supports BasicMaterialContent, " +
                                                      "but input mesh uses {0}.", material.GetType()));
            }

            EffectMaterialContent effectMaterial = new EffectMaterialContent();

            // Store a reference to our skinned mesh effect.
            string effectPath = Path.GetFullPath("SkinnedModel.fx");

            effectMaterial.Effect = new ExternalReference <EffectContent>(effectPath);

            // Copy texture settings from the input
            // BasicMaterialContent over to our new material.
            if (basicMaterial.Texture != null)
            {
                effectMaterial.Textures.Add("Texture", basicMaterial.Texture);
            }

            // Chain to the base ModelProcessor converter.
            return(base.ConvertMaterial(effectMaterial, context));
        }
Exemple #2
0
        protected override Effect CreateEffect(MaterialContent srcMaterial, bool isSkinned)
        {
            var pbrMaterial = new MaterialContentConverter(srcMaterial, GetTexture);

            var isUnlit = srcMaterial.PreferredShading == "Unlit";

            var effect = isUnlit ? _CreateUnlitEffect(pbrMaterial) : _CreatePBREffect(pbrMaterial);

            if (srcMaterial.Mode == MaterialBlendMode.Blend)
            {
                effect.AlphaBlend = true;
            }

            if (srcMaterial.Mode == MaterialBlendMode.Mask)
            {
                effect.AlphaCutoff = srcMaterial.AlphaCutoff;
            }

            if (effect is PBREffect pbrEffect)
            {
                pbrEffect.NormalMode = srcMaterial.DoubleSided ? GeometryNormalMode.DoubleSided : GeometryNormalMode.Reverse;
            }

            return(effect);
        }
        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 virtual void DoModifyFileOperations(string rootPath, MaterialFileOeprationInfo fileOperation, MaterialContent content)
		{
			var task = new InvokeServiceTask()
			{
				TaskID = UuidHelper.NewUuidString(),
				TaskTitle = string.Format(this.taskTitleTemplate, fileOperation.Material.OriginalName, fileOperation.Material.ID),
			};

			var parameters = new WfServiceOperationParameterCollection
			{
				new WfServiceOperationParameter("rootPath", rootPath),
				new WfServiceOperationParameter("fileOperation", fileOperation.Operation.ToString()),
				new WfServiceOperationParameter("materialConnectionName",
					DbConnectionMappingContext.GetMappedConnectionName(MaterialAdapter.Instance.GetConnectionName())),
				new WfServiceOperationParameter("contentConnectionName",
					DbConnectionMappingContext.GetMappedConnectionName(MaterialContentAdapter.Instance.ConnectionName)),
				new WfServiceOperationParameter("materialId", fileOperation.Material.ID),
				new WfServiceOperationParameter("url", fileOperation.Material.ShowFileUrl)
			};


			task.SvcOperationDefs.Add(new WfServiceOperationDefinition(
					new WfServiceAddressDefinition(WfServiceRequestMethod.Post, null, ResourceUriSettings.GetConfig().Paths[this.resourceUri].Uri.ToString()),
						"DoFileToDocService", parameters, "ReturnValue")
					);

			DbConnectionMappingContext.DoMappingAction(
				DbConnectionMappingContext.GetMappedConnectionName(InvokeServiceTaskAdapter.Instance.ConnectionName),
				InvokeServiceTaskAdapter.Instance.ConnectionName,
				() =>
				{
					InvokeServiceTaskAdapter.Instance.Update(task);
				});
		}
        protected override MaterialContent ConvertMaterial(MaterialContent material,
                                                           ContentProcessorContext context)
        {
            EffectMaterialContent normalMappingMaterial = new EffectMaterialContent();

            normalMappingMaterial.Effect = new ExternalReference <EffectContent>
                                               (Path.Combine("Effects/renderGBuffer.fx"));

            OpaqueDataDictionary processorParameters = new OpaqueDataDictionary();

            processorParameters["ColorKeyColor"]              = this.ColorKeyColor;
            processorParameters["ColorKeyEnabled"]            = this.ColorKeyEnabled;
            processorParameters["TextureFormat"]              = this.TextureFormat;
            processorParameters["GenerateMipmaps"]            = this.GenerateMipmaps;
            processorParameters["ResizeTexturesToPowerOfTwo"] = this.ResizeTexturesToPowerOfTwo;

            // copy the textures in the original material to the new normal mapping
            // material. this way the diffuse texture is preserved. The
            // PreprocessSceneHierarchy function has already added the normal map
            // texture to the Textures collection, so that will be copied as well.
            foreach (KeyValuePair <String, ExternalReference <TextureContent> > texture
                     in material.Textures)
            {
                normalMappingMaterial.Textures.Add(texture.Key, texture.Value);
            }

            // and convert the material using the NormalMappingMaterialProcessor,
            // who has something special in store for the normal map.
            return(context.Convert <MaterialContent, MaterialContent>
                       (normalMappingMaterial, typeof(DeferredMaterialProcessor).Name,
                       processorParameters));
        }
        protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
        {
            var customMaterial = new EffectMaterialContent();
            customMaterial.Effect = new ExternalReference<EffectContent>(effectPath);

            //var basicMaterial = (BasicMaterialContent) material;
            //if (basicMaterial.Texture != null)
            //{
            //    customMaterial.Textures.Add(skyMapKey, basicMaterial.Texture);
            //}

            foreach (var texture in material.Textures)
            {
                customMaterial.Textures.Add(texture.Key, texture.Value);
            }

            var parameters = new OpaqueDataDictionary();
            parameters["ColorKeyColor"] = ColorKeyColor;
            parameters["ColorKeyEnabled"] = ColorKeyEnabled;
            parameters["TextureFormat"] = TextureFormat;
            parameters["GenerateMipmaps"] = GenerateMipmaps;
            parameters["ResizeTexturesToPowerOfTwo"] = ResizeTexturesToPowerOfTwo;

            return context.Convert<MaterialContent, MaterialContent>(
                customMaterial, typeof(MaterialProcessor).Name, parameters);
        }
        /// <summary>
        /// 从数据库得到对象的图片
        /// </summary>
        /// <param name="id"></param>
        /// <param name="propertyName"></param>
        /// <param name="timePoint"></param>
        /// <returns></returns>
        public SchemaObjectPhoto LoadObjectPhoto(string id, string propertyName, DateTime timePoint)
        {
            SchemaObjectPhoto result = null;
            SchemaObjectBase  obj    = SchemaObjectAdapter.Instance.Load(id, timePoint);

            if (obj != null)
            {
                if (obj.Properties.ContainsKey(propertyName))
                {
                    ImageProperty imgInfo = JSONSerializerExecute.Deserialize <ImageProperty>(obj.Properties[propertyName].StringValue);

                    if (imgInfo != null)
                    {
                        MaterialContent mc = MaterialContentAdapter.Instance.Load(builder => builder.AppendItem("CONTENT_ID", imgInfo.ID)).FirstOrDefault();

                        if (mc != null)
                        {
                            result = new SchemaObjectPhoto()
                            {
                                ImageInfo = imgInfo, ContentData = mc.ContentData
                            }
                        }
                        ;
                    }
                }
            }

            return(result);
        }
Exemple #8
0
        protected virtual void ProcessGeometryUsingMaterial(MaterialContent material,
                                                            IEnumerable <GeometryContent> geometryCollection,
                                                            ContentProcessorContext context)
        {
            if (material == null)
            {
                material = new BasicMaterialContent();
            }

            foreach (var geometry in geometryCollection)
            {
                ProcessBasicMaterial(material as BasicMaterialContent, geometry);

                var vertexBuffer   = geometry.Vertices.CreateVertexBuffer();
                var primitiveCount = geometry.Vertices.PositionIndices.Count;
                var parts          = new List <ModelMeshPartContent>
                {
                    new ModelMeshPartContent(vertexBuffer, geometry.Indices, 0, primitiveCount, 0,
                                             primitiveCount / 3)
                };

                var parent = geometry.Parent;
                var bounds = BoundingSphere.CreateFromPoints(geometry.Vertices.Positions);
                _meshes.Add(new ModelMeshContent(parent.Name, geometry.Parent, null, bounds, parts));
            }
        }
Exemple #9
0
        /// <summary>
        /// Converts a <see cref="BasicMaterialContent"/> to an equivalent
        /// <see cref="SkinnedMaterialContent"/>.
        /// </summary>
        /// <param name="material">The <see cref="BasicMaterialContent"/>.</param>
        /// <returns>The <see cref="SkinnedMaterialContent"/>.</returns>
        public static SkinnedMaterialContent ConvertToSkinnedMaterial(MaterialContent material)
        {
            var skinnedMaterial = material as SkinnedMaterialContent;

            if (skinnedMaterial != null)
            {
                return(skinnedMaterial);
            }

            var basicMaterial = material as BasicMaterialContent;

            if (basicMaterial != null)
            {
                skinnedMaterial = new SkinnedMaterialContent
                {
                    Name             = basicMaterial.Name,
                    Identity         = basicMaterial.Identity,
                    Alpha            = basicMaterial.Alpha,
                    DiffuseColor     = basicMaterial.DiffuseColor,
                    EmissiveColor    = basicMaterial.EmissiveColor,
                    SpecularColor    = basicMaterial.SpecularColor,
                    SpecularPower    = basicMaterial.SpecularPower,
                    WeightsPerVertex = null
                };
                skinnedMaterial.Textures.AddRange(basicMaterial.Textures);
                return(skinnedMaterial);
            }

            return(null);
        }
Exemple #10
0
        protected override MaterialContent ConvertMaterial(MaterialContent material,
                                                           ContentProcessorContext context)
        {
            BasicMaterialContent basicMaterial = material as BasicMaterialContent;

            if (basicMaterial == null)
            {
                context.Logger.LogImportantMessage("This mesh doesn't have a valid basic material.");
            }

            // Only process meshs with basic material
            // Otherwise the mesh must be using the correct shader (AnimatedModel.fx)
            if (basicMaterial != null)
            {
                EffectMaterialContent effectMaterial = new EffectMaterialContent();
                effectMaterial.Effect = new ExternalReference <EffectContent>(EFFECTS_PATH +
                                                                              EFFECT_FILENAME);

                // Correct the texture path
                if (basicMaterial.Texture != null)
                {
                    string textureFileName = Path.GetFileName(basicMaterial.Texture.Filename);
                    effectMaterial.Textures.Add("diffuseTexture1",
                                                new ExternalReference <TextureContent>(TEXTURES_PATH + textureFileName));
                }
                return(base.ConvertMaterial(effectMaterial, context));
            }
            else
            {
                return(base.ConvertMaterial(material, context));
            }
        }
        /// <summary>
        /// Creates new material with the new effect file.
        /// </summary>
        public override MaterialContent Process(MaterialContent input,
                                                ContentProcessorContext context)
        {
            if (string.IsNullOrEmpty(customEffect))
                throw new ArgumentException("Custom Effect not set to an effect file");

            // Create a new effect material.
            EffectMaterialContent customMaterial = new EffectMaterialContent();

            // Point the new material at the custom effect file.
            string effectFile = Path.GetFullPath(customEffect);
            customMaterial.Effect = new ExternalReference<EffectContent>(effectFile);

            // Loop over the textures in the current material adding them to
            // the new material.
            foreach (KeyValuePair<string,
                     ExternalReference<TextureContent>> textureContent in input.Textures)
            {
                customMaterial.Textures.Add(textureContent.Key, textureContent.Value);
            }

            // Loop over the opaque data in the current material adding them to
            // the new material.
            foreach (KeyValuePair<string, Object> opaqueData in input.OpaqueData)
            {
                customMaterial.OpaqueData.Add(opaqueData.Key, opaqueData.Value);
            }

            // Call the base material processor to continue the rest of the processing.
            return base.Process(customMaterial, context);
        }
Exemple #12
0
        protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
        {
            OpaqueDataDictionary pparams = new OpaqueDataDictionary( );

            pparams["ColorKeyEnabled"]            = false;
            pparams["GenerateMipmaps"]            = this.GenerateMipmaps;
            pparams["TextureFormat"]              = this.TextureFormat;
            pparams["ResizeTexturesToPowerOfTwo"] = this.ResizeTexturesToPowerOfTwo;
            pparams["PremultiplyTextureAlpha"]    = false;

            string exePath    = Application.ExecutablePath;
            string appDir     = exePath.Replace(Path.GetFileName(exePath), string.Empty);
            string shaderPath = Path.Combine(appDir, DATA_DIR + @"\game.fx");

            EffectMaterialContent vixenMaterial = new EffectMaterialContent( );

            vixenMaterial.Effect         = new ExternalReference <EffectContent>(shaderPath);
            vixenMaterial.CompiledEffect = context.BuildAsset <EffectContent, CompiledEffectContent>(vixenMaterial.Effect, "EffectProcessor");

            foreach (KeyValuePair <string, ExternalReference <TextureContent> > texture in material.Textures)
            {
                switch (texture.Key)
                {
                case C4D_DMAP:
                    vixenMaterial.Textures.Add(KEY_DMAP, texture.Value);
                    break;

                case C4D_NMAP:
                    vixenMaterial.Textures.Add(KEY_NMAP, texture.Value);
                    break;

                case C4D_SMAP:
                    vixenMaterial.Textures.Add(KEY_SMAP, texture.Value);
                    break;

                case C4D_EMAP:
                    vixenMaterial.Textures.Add(KEY_EMAP, texture.Value);
                    break;
                }
            }

            if (!vixenMaterial.Textures.ContainsKey(KEY_DMAP))
            {
                vixenMaterial.Textures[KEY_DMAP] = new ExternalReference <TextureContent>(Path.Combine(appDir, DATA_DIR + @"\dmap.tga"));
            }
            if (!vixenMaterial.Textures.ContainsKey(KEY_NMAP))
            {
                vixenMaterial.Textures[KEY_DMAP] = new ExternalReference <TextureContent>(Path.Combine(appDir, DATA_DIR + @"\nmap.tga"));
            }
            if (!vixenMaterial.Textures.ContainsKey(KEY_SMAP))
            {
                vixenMaterial.Textures[KEY_DMAP] = new ExternalReference <TextureContent>(Path.Combine(appDir, DATA_DIR + @"\smap.tga"));
            }
            if (!vixenMaterial.Textures.ContainsKey(KEY_EMAP))
            {
                vixenMaterial.Textures[KEY_DMAP] = new ExternalReference <TextureContent>(Path.Combine(appDir, DATA_DIR + @"\emap.tga"));
            }

            return(context.Convert <MaterialContent, MaterialContent>(vixenMaterial, typeof(MaterialProcessor).Name, pparams));
        }
Exemple #13
0
        /// <summary>
        /// Extract any defines we need from the original material, like alphaMasked, fresnel, reflection, etc, and pass it into
        /// the opaque data
        /// </summary>
        /// <param name="lppMaterial"></param>
        /// <param name="material"></param>
        /// <param name="context"></param>
        private void ExtractDefines(EffectMaterialContent lppMaterial, MaterialContent material, ContentProcessorContext context)
        {
            string defines = "";

            if (material.OpaqueData.ContainsKey("alphaMasked") && material.OpaqueData["alphaMasked"].ToString() == "True")
            {
                context.Logger.LogMessage("Alpha masked material found");
                lppMaterial.OpaqueData.Add("AlphaReference", (float)material.OpaqueData["AlphaReference"]);
                defines += "ALPHA_MASKED;";
            }

            if (material.OpaqueData.ContainsKey("reflectionEnabled") && material.OpaqueData["reflectionEnabled"].ToString() == "True")
            {
                context.Logger.LogMessage("Reflection enabled");
                defines += "REFLECTION_ENABLED;";
            }

            if (_isSkinned)
            {
                context.Logger.LogMessage("Skinned mesh found");
                defines += "SKINNED_MESH;";
            }

            if (material.OpaqueData.ContainsKey("dualLayerEnabled") && material.OpaqueData["dualLayerEnabled"].ToString() == "True")
            {
                context.Logger.LogMessage("Dual layer material found");
                defines += "DUAL_LAYER;";
            }

            if (!String.IsNullOrEmpty(defines))
            {
                lppMaterial.OpaqueData.Add("Defines", defines);
            }
        }
		public override void SaveMaterialContent(MaterialContent content)
		{
			if (content.ContentData == null)
				SaveMaterialContentFromFile(content);
			else
				SaveMaterialContentFromData(content);
		}
Exemple #15
0
        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));
        }
        protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
        {
            MaterialData mat = incomingMaterials.Single(m => m.Name == material.Name);

            EffectMaterialContent emc = new EffectMaterialContent();
            emc.Effect = new ExternalReference<EffectContent>(Path.Combine(contentPath, mat.CustomEffect));
            emc.Name = material.Name;
            emc.Identity = material.Identity;

            foreach (KeyValuePair<String, ExternalReference<TextureContent>> texture in material.Textures)
            {
                if (texture.Key == "Texture")
                {
                    emc.Textures.Add(texture.Key, texture.Value);
                }
                else
                {
                    context.Logger.LogWarning(null, material.Identity, "There were some other textures referenced by the model, but we can't properly assign them to the correct effect parameter.");
                }
            }

            foreach (EffectParam ep in mat.EffectParams)
            {
                if (ep.Category == EffectParamCategory.OpaqueData)
                {
                    emc.OpaqueData.Add(ep.Name, ep.Value);
                }
                else if (ep.Category == EffectParamCategory.Texture)
                {
                    emc.Textures.Add(ep.Name, new ExternalReference<TextureContent>((string)(ep.Value)));
                }
            }

            return base.ConvertMaterial(emc, context);
        }
Exemple #17
0
        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);
            }
        }
        protected override MaterialContent ConvertMaterial(
            MaterialContent material,
            ContentProcessorContext context)
        {
            EffectMaterialContent deferredShadingMaterial = new EffectMaterialContent();

            deferredShadingMaterial.Effect = new ExternalReference <EffectContent>
                                                 (effectDirectory + "RenderGBuffer.fx");

            // copy the textures in the original material to the new normal mapping
            // material, if they are relevant to our renderer. The
            // LookUpTextures function has added the normal map and specular map
            // textures to the Textures collection, so that will be copied as well.
            foreach (KeyValuePair <String, ExternalReference <TextureContent> > texture
                     in material.Textures)
            {
                if ((texture.Key == "Texture") ||
                    (texture.Key == "NormalMap") ||
                    (texture.Key == "SpecularMap"))
                {
                    deferredShadingMaterial.Textures.Add(texture.Key, texture.Value);
                }
            }

            return(context.Convert <MaterialContent, MaterialContent>(deferredShadingMaterial, typeof(MaterialProcessor).Name));
        }
Exemple #19
0
        /// <summary>
        /// Creates new material with the new effect file.
        /// </summary>
        public override MaterialContent Process(MaterialContent input,
                                                ContentProcessorContext context)
        {
            if (string.IsNullOrEmpty(customEffect))
            {
                throw new ArgumentException("Custom Effect not set to an effect file");
            }

            // Create a new effect material.
            EffectMaterialContent customMaterial = new EffectMaterialContent();

            // Point the new material at the custom effect file.
            string effectFile = Path.GetFullPath(customEffect);

            customMaterial.Effect = new ExternalReference <EffectContent>(effectFile);

            // Loop over the textures in the current material adding them to
            // the new material.
            foreach (KeyValuePair <string,
                                   ExternalReference <TextureContent> > textureContent in input.Textures)
            {
                customMaterial.Textures.Add(textureContent.Key, textureContent.Value);
            }

            // Loop over the opaque data in the current material adding them to
            // the new material.
            foreach (KeyValuePair <string, Object> opaqueData in input.OpaqueData)
            {
                customMaterial.OpaqueData.Add(opaqueData.Key, opaqueData.Value);
            }

            // Call the base material processor to continue the rest of the processing.
            return(base.Process(customMaterial, context));
        }
Exemple #20
0
        protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
        {
            var myMaterial = new EffectMaterialContent();

            var effectPath = Path.GetFullPath("Effect/Phong.fx");
            myMaterial.Effect = new ExternalReference<EffectContent>(effectPath);

            // マテリアル名をエフェクトに渡す(TODO: これ渡せてないなあ・・・)
            Console.WriteLine("Material name : " + material.Name);
            myMaterial.Effect.Name = material.Name;

            if (material is BasicMaterialContent)
            {
                var basicMaterial = (BasicMaterialContent)material;

                myMaterial.OpaqueData.Add("DiffuseColor", basicMaterial.DiffuseColor);
                myMaterial.OpaqueData.Add("Alpha", basicMaterial.Alpha);
                myMaterial.OpaqueData.Add("EmissiveColor", basicMaterial.EmissiveColor);
                myMaterial.OpaqueData.Add("SpecularColor", basicMaterial.SpecularColor);
                myMaterial.OpaqueData.Add("SpecularPower", 4.0f);
            }
            else if (material is EffectMaterialContent)
            {
                var effectMaterial = (EffectMaterialContent)material;
            }
            else
            {
                throw new Exception("unknown material");
            }

            return base.ConvertMaterial(myMaterial, context);
        }
Exemple #21
0
        /// <summary>
        /// Converts a <see cref="BasicMaterialContent"/> to an equivalent
        /// <see cref="SkinnedMaterialContent"/>.
        /// </summary>
        /// <param name="material">The <see cref="BasicMaterialContent"/>.</param>
        /// <returns>The <see cref="SkinnedMaterialContent"/>.</returns>
        public static SkinnedMaterialContent ConvertToSkinnedMaterial(MaterialContent material)
        {
            var skinnedMaterial = material as SkinnedMaterialContent;
              if (skinnedMaterial != null)
            return skinnedMaterial;

              var basicMaterial = material as BasicMaterialContent;
              if (basicMaterial != null)
              {
            skinnedMaterial = new SkinnedMaterialContent
            {
              Name = basicMaterial.Name,
              Identity = basicMaterial.Identity,
              Alpha = basicMaterial.Alpha,
              DiffuseColor = basicMaterial.DiffuseColor,
              EmissiveColor = basicMaterial.EmissiveColor,
              SpecularColor = basicMaterial.SpecularColor,
              SpecularPower = basicMaterial.SpecularPower,
              WeightsPerVertex = null
            };
            skinnedMaterial.Textures.AddRange(basicMaterial.Textures);
            return skinnedMaterial;
              }

              return null;
        }
        /// <summary>
        /// Changes all the materials to use our skinned model effect.
        /// </summary>
        protected override MaterialContent ConvertMaterial(MaterialContent material,
                                                        ContentProcessorContext context)
        {
            BasicMaterialContent basicMaterial = material as BasicMaterialContent;

            if (basicMaterial == null)
            {
                throw new InvalidContentException(string.Format(
                    "InstancedSkinnedModelProcessor only supports BasicMaterialContent, " +
                    "but input mesh uses {0}.", material.GetType()));
            }

            EffectMaterialContent effectMaterial = new EffectMaterialContent();

            // Store a reference to our skinned mesh effect.
            string effectPath = Path.GetFullPath("SkinnedModelInstancing.fx");

            effectMaterial.Effect = new ExternalReference<EffectContent>(effectPath);

            // Copy texture settings from the input
            // BasicMaterialContent over to our new material.
            if (basicMaterial.Texture != null)
                effectMaterial.Textures.Add("Texture", basicMaterial.Texture);

            // Chain to the base ModelProcessor converter.
            return base.ConvertMaterial(effectMaterial, context);
        }
        /// <summary>
        /// Converts a material.
        /// </summary>
        public override MaterialContent Process(MaterialContent input,
                                                ContentProcessorContext context)
        {
            // Create a new effect material.
            EffectMaterialContent customMaterial = new EffectMaterialContent();

            // Point the new material at our custom effect file.
            string effectFile = Path.GetFullPath("Shaders/ShipEffect.fx");

            customMaterial.Effect = new ExternalReference <EffectContent>(effectFile);

            // Copy texture data across from the original material.
            BasicMaterialContent basicMaterial = (BasicMaterialContent)input;

            if (basicMaterial.Texture != null)
            {
                customMaterial.Textures.Add("DiffuseTexture", basicMaterial.Texture);
                customMaterial.OpaqueData.Add("TextureEnabled", true);
            }

            // Add in the Normal and Specular maps
            string normalTexture   = basicMaterial.Texture.Filename.Replace("_c", "_n");
            string specularTexture = basicMaterial.Texture.Filename.Replace("_c", "_s");
            string emissiveTexture = basicMaterial.Texture.Filename.Replace("_c", "_i");

            customMaterial.Textures.Add("SpecularTexture",
                                        new ExternalReference <TextureContent>(specularTexture));
            customMaterial.Textures.Add("NormalTexture",
                                        new ExternalReference <TextureContent>(normalTexture));
            customMaterial.Textures.Add("EmissiveTexture",
                                        new ExternalReference <TextureContent>(emissiveTexture));

            // Chain to the base material processor.
            return(base.Process(customMaterial, context));
        }
Exemple #24
0
        /// <summary>
        /// Converts a material.
        /// </summary>
        public override MaterialContent Process(MaterialContent input,
                                                ContentProcessorContext context)
        {
            // Create a new effect material.
            EffectMaterialContent customMaterial = new EffectMaterialContent();

            // Point the new material at our custom effect file.
            string effectFile = Path.GetFullPath("EnvironmentMap.fx");

            customMaterial.Effect = new ExternalReference <EffectContent>(effectFile);

            // Copy texture data across from the original material.
            BasicMaterialContent basicMaterial = (BasicMaterialContent)input;

            if (basicMaterial.Texture != null)
            {
                customMaterial.Textures.Add("Texture", basicMaterial.Texture);
                customMaterial.OpaqueData.Add("TextureEnabled", true);
            }

            // Add the reflection texture.
            string envmap = Path.GetFullPath(EnvironmentMap);

            customMaterial.Textures.Add("EnvironmentMap",
                                        new ExternalReference <TextureContent>(envmap));

            // Chain to the base material processor.
            return(base.Process(customMaterial, context));
        }
Exemple #25
0
        private void ExtractTextures(EffectMaterialContent lppMaterial, MaterialContent material)
        {
            foreach (KeyValuePair <String, ExternalReference <TextureContent> > texture
                     in material.Textures)
            {
                if (texture.Key.ToLower().Equals("diffusemap") || texture.Key.ToLower().Equals("texture"))
                {
                    lppMaterial.Textures.Add(DiffuseMapKey, texture.Value);
                }
                if (texture.Key.ToLower().Equals("normalmap"))
                {
                    lppMaterial.Textures.Add(NormalMapKey, texture.Value);
                }
                if (texture.Key.ToLower().Equals("specularmap"))
                {
                    lppMaterial.Textures.Add(SpecularMapKey, texture.Value);
                }
                if (texture.Key.ToLower().Equals("emissivemap") || texture.Key.ToLower().Equals("emissive"))
                {
                    lppMaterial.Textures.Add(EmissiveMapKey, texture.Value);
                }

                if (texture.Key.ToLower().Equals("seconddiffusemap"))
                {
                    lppMaterial.Textures.Add(SecondDiffuseMapKey, texture.Value);
                }
                if (texture.Key.ToLower().Equals("secondnormalmap"))
                {
                    lppMaterial.Textures.Add(SecondNormalMapKey, texture.Value);
                }
                if (texture.Key.ToLower().Equals("secondspecularmap"))
                {
                    lppMaterial.Textures.Add(SecondSpecularMapKey, texture.Value);
                }

                if (texture.Key.ToLower().Equals("reflectionmap"))
                {
                    lppMaterial.Textures.Add(ReflectionMapKey, texture.Value);
                }
            }

            ExternalReference <TextureContent> externalRef;

            if (!lppMaterial.Textures.TryGetValue(DiffuseMapKey, out externalRef))
            {
                lppMaterial.Textures[DiffuseMapKey] = new ExternalReference <TextureContent>("textures/default_diffuse.tga");
            }
            if (!lppMaterial.Textures.TryGetValue(NormalMapKey, out externalRef))
            {
                lppMaterial.Textures[NormalMapKey] = new ExternalReference <TextureContent>("textures/default_normal.tga");
            }
            if (!lppMaterial.Textures.TryGetValue(SpecularMapKey, out externalRef))
            {
                lppMaterial.Textures[SpecularMapKey] = new ExternalReference <TextureContent>("textures/default_specular.tga");
            }
            if (!lppMaterial.Textures.TryGetValue(EmissiveMapKey, out externalRef))
            {
                lppMaterial.Textures[EmissiveMapKey] = new ExternalReference <TextureContent>("textures/default_emissive.tga");
            }
        }
        /// <summary>
        /// Converts a material.
        /// </summary>
        public override MaterialContent Process(MaterialContent input,
                                                ContentProcessorContext context)
        {
            // Create a new effect material.
            EffectMaterialContent customMaterial = new EffectMaterialContent();

            // Point the new material at our custom effect file.
            string effectFile = Path.GetFullPath("Effects\\PreEffects\\TexturingEffect.fx");

            customMaterial.Effect = new ExternalReference<EffectContent>(effectFile);

            // Copy texture data across from the original material.
            BasicMaterialContent basicMaterial = (BasicMaterialContent)input;

            if (basicMaterial.Texture != null)
            {
                customMaterial.Textures.Add("DefaultTexture", basicMaterial.Texture);
                customMaterial.OpaqueData.Add("TextureEnabled", true);
            }

            // Add the reflection texture.
            //string envmap = Path.GetFullPath(EnvironmentMap);

            //customMaterial.Textures.Add("EnvironmentMap",
                                        //new ExternalReference<TextureContent>(envmap));

            // Chain to the base material processor.
            return base.Process(customMaterial, context);
        }
        protected override MaterialContent Convert(Assimp.Material srcMaterial)
        {
            var dstMaterial = new MaterialContent();

            dstMaterial.Name = srcMaterial.Name;

            dstMaterial.DoubleSided = srcMaterial.HasTwoSided;
            dstMaterial.Mode        = srcMaterial.BlendMode == Assimp.BlendMode.Default ? MaterialBlendMode.Opaque : MaterialBlendMode.Blend;
            dstMaterial.AlphaCutoff = 0.5f;

            if (srcMaterial.IsPBRMaterial)
            {
                dstMaterial.PreferredShading = "MetallicRoughness";
                SetTexture(dstMaterial, "Normals", srcMaterial.PBR.TextureNormalCamera);
                SetTexture(dstMaterial, "BaseColor", srcMaterial.PBR.TextureBaseColor);
                SetTexture(dstMaterial, "MetallicRoughness", srcMaterial.PBR.TextureMetalness);
                SetTexture(dstMaterial, "Emissive", srcMaterial.PBR.TextureEmissionColor);
            }
            else
            {
                dstMaterial.PreferredShading = "MetallicRoughness";
                SetTexture(dstMaterial, "BaseColor", srcMaterial.TextureDiffuse);
            }

            return(dstMaterial);
        }
Exemple #28
0
        private void Upload(MaterialContent data)
        {
            data.ContentID = UuidHelper.NewUuidString();
            string sql = ORMapping.GetInsertSql(data, TSqlBuilder.Instance);

            DbHelper.RunSql(db => db.ExecuteNonQuery(CommandType.Text, sql), "UAT");
        }
        /// <summary>
        /// Converts an input material to use our custom InstancedModel effect.
        /// </summary>
        MaterialContent ProcessMaterial(MaterialContent material)
        {
            // Have we already processed this material?
            if (!processedMaterials.ContainsKey(material))
            {
                // If not, process it now.
                EffectMaterialContent instancedMaterial = new EffectMaterialContent();

                // Set the material to use our custom instancing effect.
                instancedMaterial.Effect = new ExternalReference <EffectContent>(
                    "InstancedModel.fx", rootNode.Identity);

                // Copy across the texture setting from the input material.
                if (!material.Textures.ContainsKey("Texture"))
                {
                    throw new InvalidContentException(
                              "Material has no texture, but the InstancedModel " +
                              "effect does not support untextured materials.");
                }

                instancedMaterial.Textures.Add("Texture", material.Textures["Texture"]);

                // Chain to the built-in MaterialProcessor, which will
                // build the effect and texture referenced by this material.
                processedMaterials[material] =
                    context.Convert <MaterialContent,
                                     MaterialContent>(instancedMaterial,
                                                      "MaterialProcessor");
            }

            return(processedMaterials[material]);
        }
Exemple #30
0
        protected override MaterialContent ConvertMaterial(MaterialContent material,
                                                           ContentProcessorContext context)
        {
            EffectMaterialContent lppMaterial = new EffectMaterialContent();

            OpaqueDataDictionary processorParameters = new OpaqueDataDictionary();

            processorParameters["ColorKeyColor"]              = this.ColorKeyColor;
            processorParameters["ColorKeyEnabled"]            = false;
            processorParameters["TextureFormat"]              = this.TextureFormat;
            processorParameters["GenerateMipmaps"]            = this.GenerateMipmaps;
            processorParameters["ResizeTexturesToPowerOfTwo"] = this.ResizeTexturesToPowerOfTwo;
            processorParameters["PremultiplyTextureAlpha"]    = false;
            processorParameters["ColorKeyEnabled"]            = false;

            lppMaterial.Effect         = new ExternalReference <EffectContent>(_customFx.Length == 0 ? "shaders/LPPMainEffect.fx" : _customFx);
            lppMaterial.CompiledEffect = context.BuildAsset <EffectContent, CompiledEffectContent>(lppMaterial.Effect, "EffectProcessor");

            // copy the textures in the original material to the new lpp
            // material
            ExtractTextures(lppMaterial, material);
            //extract the extra parameters
            ExtractDefines(lppMaterial, material, context);

            // and convert the material using the NormalMappingMaterialProcessor,
            // who has something special in store for the normal map.
            return(context.Convert <MaterialContent, MaterialContent>
                       (lppMaterial, typeof(LightPrePassMaterialProcessor).Name, processorParameters));
        }
Exemple #31
0
        protected override MaterialContent Convert(SharpGLTF.Schema2.Material srcMaterial)
        {
            var dstMaterial = new MaterialContent();

            dstMaterial.Name = srcMaterial.Name;
            dstMaterial.Tag  = _TagConverter?.Invoke(srcMaterial);

            dstMaterial.DoubleSided = srcMaterial.DoubleSided;

            dstMaterial.AlphaCutoff = srcMaterial.AlphaCutoff;
            switch (srcMaterial.Alpha)
            {
            case SharpGLTF.Schema2.AlphaMode.OPAQUE: dstMaterial.Mode = MaterialBlendMode.Opaque; break;

            case SharpGLTF.Schema2.AlphaMode.MASK: dstMaterial.Mode = MaterialBlendMode.Mask; break;

            case SharpGLTF.Schema2.AlphaMode.BLEND: dstMaterial.Mode = MaterialBlendMode.Blend; break;
            }

            if (srcMaterial.Unlit)
            {
                dstMaterial.PreferredShading = "Unlit";
            }
            else if (srcMaterial.FindChannel("SpecularGlossiness") != null)
            {
                dstMaterial.PreferredShading = "SpecularGlossiness";
            }
            else if (srcMaterial.FindChannel("MetallicRoughness") != null)
            {
                dstMaterial.PreferredShading = "MetallicRoughness";
            }

            foreach (var srcChannel in srcMaterial.Channels)
            {
                var dstChannel = dstMaterial.UseChannel(srcChannel.Key);

                dstChannel.Value = ParamToArray(srcChannel);

                if (srcChannel.Texture != null)
                {
                    var imgData = srcChannel.Texture.PrimaryImage.Content.Content.ToArray();

                    var texContent = new ImageContent(imgData);

                    dstChannel.TextureIndex = UseTexture(texContent);
                    dstChannel.Sampler      = ToXna(srcChannel.Texture.Sampler);
                }
                else
                {
                    dstChannel.Sampler = SamplerStateContent.CreateDefault();
                }


                dstChannel.VertexIndexSet = srcChannel.TextureCoordinate;
                dstChannel.Transform      = (srcChannel.TextureTransform?.Matrix ?? System.Numerics.Matrix3x2.Identity).ToXna();
            }

            return(dstMaterial);
        }
        protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
        {
            string effectFile = this.effectFileName;

            if (string.IsNullOrEmpty(effectFile))
            {
                if (string.IsNullOrEmpty(this.normalMapTexture))
                {
                    if (string.IsNullOrEmpty(this.diffuseTexture))
                    {
                        effectFile = "Effects\\DefaultSolidColor.fx";
                    }
                    else
                    {
                        effectFile = "Effects\\Default.fx";
                    }
                }
                else
                {
                    effectFile = "Effects\\DefaultNormalMap.fx";
                }
            }

            EffectMaterialContent normalMappingMaterial = new EffectMaterialContent();

            normalMappingMaterial.Effect = new ExternalReference <EffectContent>(Path.Combine(directory, effectFile));

            OpaqueDataDictionary processorParameters = new OpaqueDataDictionary();

            processorParameters["ColorKeyColor"]              = this.ColorKeyColor;
            processorParameters["ColorKeyEnabled"]            = this.ColorKeyEnabled;
            processorParameters["TextureFormat"]              = this.TextureFormat;
            processorParameters["PremultiplyTextureAlpha"]    = this.PremultiplyTextureAlpha;
            processorParameters["PremultiplyVertexColors"]    = this.PremultiplyVertexColors;
            processorParameters["GenerateMipmaps"]            = this.GenerateMipmaps;
            processorParameters["ResizeTexturesToPowerOfTwo"] = this.ResizeTexturesToPowerOfTwo;

            // copy the textures in the original material to the new normal mapping
            // material. this way the diffuse texture is preserved. The
            // PreprocessSceneHierarchy function has already added the normal map
            // texture to the Textures collection, so that will be copied as well.
            foreach (KeyValuePair <String, ExternalReference <TextureContent> > texture in material.Textures)
            {
                normalMappingMaterial.Textures.Add(texture.Key, texture.Value);
            }

            if (!string.IsNullOrEmpty(diffuseTexture))
            {
                normalMappingMaterial.Textures.Add("DiffuseTexture", new ExternalReference <TextureContent>(Path.Combine(directory, diffuseTexture)));
            }

            // and convert the material using the NormalMappingMaterialProcessor,
            // who has something special in store for the normal map.
#if MONOGAME
            return(context.Convert <MaterialContent, MaterialContent>(normalMappingMaterial, typeof(MGMaterialProcessor).Name, processorParameters));
#else
            return(context.Convert <MaterialContent, MaterialContent>(normalMappingMaterial, typeof(MaterialProcessor).Name, processorParameters));
#endif
        }
 public TerrainModelContentBuilder(int patchSize, HeightMapContent heightMap, MaterialContent material, int detailTextureTiling, int horizontalScale)
 {
     _patchSize = patchSize;
     _heightMap = heightMap;
     _material = material;
     _detailTextureTiling = detailTextureTiling;
     _horizontalScale = horizontalScale;
 }
        /// <summary>
        /// Converts a single piece of input geometry into our instanced format.
        /// </summary>
        void ProcessGeometry(GeometryContent geometry)
        {
            int indexCount  = geometry.Indices.Count;
            int vertexCount = geometry.Vertices.VertexCount;

            // Validate that the number of vertices is suitable for instancing.
            if (vertexCount > ushort.MaxValue)
            {
                throw new InvalidContentException(
                          string.Format("Geometry contains {0} vertices: " +
                                        "this is too many to be instanced.", vertexCount));
            }

            if (vertexCount > ushort.MaxValue / 8)
            {
                context.Logger.LogWarning(null, rootNode.Identity,
                                          "Geometry contains {0} vertices: " +
                                          "this will only allow it to be instanced " +
                                          "{1} times per batch. A model with fewer " +
                                          "vertices would be more efficient.",
                                          vertexCount, ushort.MaxValue / vertexCount);
            }

            // Validate that the vertex channels we are going to use to pass
            // through our instancing data aren't already in use.
            VertexChannelCollection vertexChannels = geometry.Vertices.Channels;

            for (int i = 1; i <= 4; i++)
            {
                if (vertexChannels.Contains(VertexChannelNames.TextureCoordinate(i)))
                {
                    throw new InvalidContentException(
                              string.Format("Model already contains data for texture " +
                                            "coordinate channel {0}, but instancing " +
                                            "requires this channel for its own use.", i));
                }
            }

            // Flatten the flexible input vertex channel data into
            // a simple GPU style vertex buffer byte array.
            VertexBufferContent vertexBufferContent;

            VertexElement[] vertexElements;

            geometry.Vertices.CreateVertexBuffer(out vertexBufferContent,
                                                 out vertexElements,
                                                 context.TargetPlatform);

            int vertexStride = VertexDeclaration.GetVertexStrideSize(vertexElements, 0);

            // Convert the input material.
            MaterialContent material = ProcessMaterial(geometry.Material);

            // Add the new piece of geometry to our output model.
            outputModel.AddModelPart(indexCount, vertexCount, vertexStride,
                                     vertexElements, vertexBufferContent,
                                     geometry.Indices, material);
        }
Exemple #35
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="effect">Effect content</param>
 public Material(MaterialContent effect)
 {
     this.EmissiveColor = effect.EmissionColor;
     this.AmbientColor  = effect.AmbientColor;
     this.DiffuseColor  = effect.DiffuseColor;
     this.SpecularColor = effect.SpecularColor;
     this.Shininess     = effect.Shininess;
     this.IsTransparent = effect.IsTransparent;
 }
 internal SkinnedModelMeshContent(int numVertices, int numTriangles, VertexBufferContent vertices,
     IndexCollection indices, MaterialContent material)
 {
     this.numVertices = numVertices;
     this.numTriangles = numTriangles;
     this.vertices = vertices;
     this.indices = indices;
     this.material = material;
 }
Exemple #37
0
        private void InitializeEmitter()
        {
            MaterialContent mat = MaterialContent.Default;

            mat.EmissionColor = Color.White;

            GeometryUtil.CreateSphere(
                0.1f, 16, 5,
                out Vector3[] v, out Vector3[] n, out Vector2[] uv, out uint[] ix);
        public override MaterialContent Process(MaterialContent input, ContentProcessorContext context)
        {
            if (context.Parameters.ContainsKey("Defines"))
                context.Parameters.Remove("Defines");
            if (input.OpaqueData.ContainsKey("Defines"))
                context.Parameters.Add("Defines", input.OpaqueData["Defines"]);

            return base.Process(input, context);
        }
        private static MeshContent CreateBasicMesh(MaterialContent material)
        {
            var builder = MeshBuilder.StartMesh("Mesh1");

            builder.SetMaterial(material);
            CreatePositions(builder);
            AddVertices(builder);
            return(builder.FinishMesh());
        }
Exemple #40
0
        private string FindTexture(MeshContent mesh, MaterialContent material, params string[] possibleKeys)
        {
            foreach (var key in possibleKeys)
            {
                // search in existing material textures
                foreach (var item in material.Textures)
                {
                    if (item.Key.ToLowerInvariant() == key)
                    {
                        return(item.Value.Filename);
                    }
                }

                // search in material opaque data
                foreach (var item in material.OpaqueData)
                {
                    if (item.Key.ToLowerInvariant() == key && item.Value.GetType() == typeof(string))
                    {
                        var file = item.Value as string;
                        if (!Path.IsPathRooted(file))
                        {
                            file = Path.Combine(directory, file);
                        }

                        return(file);
                    }
                }

                // search in mesh opaque data
                foreach (var item in mesh.OpaqueData)
                {
                    if (item.Key.ToLowerInvariant() == key && item.Value.GetType() == typeof(string))
                    {
                        var file = item.Value as string;
                        if (!Path.IsPathRooted(file))
                        {
                            file = Path.Combine(directory, file);
                        }

                        return(file);
                    }
                }
            }

            // try and find the file in the meshs' directory
            foreach (var key in possibleKeys)
            {
                foreach (var file in Directory.EnumerateFiles(directory, mesh.Name + "_" + key + ".*", SearchOption.AllDirectories))
                {
                    return(file);
                }
            }

            // cant find anything
            return(null);
        }
		public override void SaveMaterialContent(MaterialContent content)
		{
			SourceFileInfo.NullCheck("SourceFileInfo");
			DestFileInfo.NullCheck("DestFileInfo");

			if (CheckSourceFileExists)
				ExceptionHelper.FalseThrow(SourceFileInfo.Exists, string.Format(Resource.FileNotFound, SourceFileInfo.Name));

			MoveFile(SourceFileInfo, DestFileInfo);
		}
        public MaterialContent CreateMaterial(ContentProcessorContext context, Dictionary <string, object> parameters)
        {
            MaterialContent content = new MaterialContent()
            {
                Name = _name
            };

            int i = 0;

            foreach (PassTemplate template in _passes)
            {
                MaterialContent.Pass pass = new MaterialContent.Pass(string.IsNullOrEmpty(template.Name) ? string.Format("{0}_Pass_{1}", _name, i) : template.Name);
                pass.VertexShaderSources.AddRange(template.VertexShaders.Select(s => new ExternalReferenceContent <ShaderSourceContent>(s)));
                pass.FragmentShaderSources.AddRange(template.FragmentShaders.Select(s => new ExternalReferenceContent <ShaderSourceContent>(s)));

                foreach (UniformDefinition def in template.Variables)
                {
                    UniformValueContent value = null;
                    object o;
                    if (!parameters.TryGetValue(def.Name, out o))
                    {
                        foreach (string name in def.Aliases)
                        {
                            if (parameters.TryGetValue(name, out o))
                            {
                                break;
                            }
                        }
                    }
                    if (o != null)
                    {
                        value = GetAsUniformValueContent(def.Type, def.Name, o, context);
                    }

                    if (value == null) // no match, or not able to convert to uniform type
                    {
                        value = def.Value;
                    }

                    pass.Parameters[def.Name] = value;
                }

                foreach (UniformDefinition def in template.Constants)
                {
                    pass.Parameters[def.Name] = def.Value;
                }

                pass.ComparisonParameters = template.ComparisonParameters;

                i++;
                content.Passes.Add(pass);
            }

            return(content);
        }
Exemple #43
0
 private string FindSpecularTexture(MeshContent mesh, MaterialContent material)
 {
     if (string.IsNullOrEmpty(SpecularTexture))
     {
         return(FindTexture(mesh, material, "specularmap", "specular", "spec", "s") ?? "null_specular.tga");
     }
     else
     {
         return(Path.Combine(directory, SpecularTexture));
     }
 }
Exemple #44
0
        MaterialContent ProcessMaterial(MaterialContent material)
        {
            // Have we already processed this material?
            if (!processedMaterials.ContainsKey(material))
            {
                // If not, process it now.
                processedMaterials[material] = context.Convert <MaterialContent, MaterialContent>(material, "MaterialProcessor");
            }

            return(processedMaterials[material]);
        }
		public static void Save(MaterialContent content)
		{
			IMaterialContentPersistManager manager = MaterialContentSettings.GetConfig().PersistManager;
			string path = GetUploadRootPath("ImageUploadRootPath");
			string fileName = Path.Combine(path + @"Temp\", content.FileName);

			if (manager is FileMaterialContentPersistManager)
				manager.DestFileInfo = new System.IO.FileInfo(Path.Combine(path, content.FileName));

			manager.SourceFileInfo = new System.IO.FileInfo(fileName);
			manager.SaveMaterialContent(content);
		}
        public override MaterialContent Process(MaterialContent input, ContentProcessorContext context)
        {
            SkinnedModelMaterialContent skinnedModelMaterialContent = new SkinnedModelMaterialContent();

            // Processes all textures
            ProcessTextures(input, skinnedModelMaterialContent, context);

            // Processes surface material
            ProcessMaterial(input, skinnedModelMaterialContent, context);

            return skinnedModelMaterialContent;
        }
        /// <summary>
        /// Use our custom material processor
        /// to convert selected materials in this model.
        /// </summary>
        protected override MaterialContent ConvertMaterial(MaterialContent material,
                                                         ContentProcessorContext context)
        {
            if (CustomMaterialProcessor == "")
                return base.ConvertMaterial(material, context);

            OpaqueDataDictionary processorParameters = new OpaqueDataDictionary();
            processorParameters.Add("Section", section);

            return context.Convert<MaterialContent, MaterialContent>(material,
                                                CustomMaterialProcessor,
                                                processorParameters);
        }
        /// <summary>
        /// Override the ConvertMaterial method to apply our custom InstancedModel.fx shader.
        /// </summary>
        protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
        {
            EffectMaterialContent newMaterial = new EffectMaterialContent();
            newMaterial.Effect = new ExternalReference<EffectContent>("SKraftShader.fx", rootIdentity);

            BasicMaterialContent basicMaterial = material as BasicMaterialContent;
            if ((basicMaterial != null) && (basicMaterial.Texture != null))
            {
                newMaterial.Textures.Add("Texture", basicMaterial.Texture);
            }

            return base.ConvertMaterial(newMaterial, context);
        }
        private static MaterialContent PrepareMaterialContent(string contentID, string relativeID)
        {
            MaterialContent content = new MaterialContent();

            content.ContentID = contentID;
            content.RelativeID = relativeID;
            content.Class = "MaterialTest";

            string data = string.Format("Have a good day '{0}'!", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            content.ContentData = Encoding.UTF8.GetBytes(data);

            return content;
        }
        /// <summary>
        /// Use our custom EnvironmentMappedMaterialProcessor
        /// to convert all the materials on this model.
        /// </summary>
        protected override MaterialContent ConvertMaterial(MaterialContent material,
                                                         ContentProcessorContext context)
        {
            OpaqueDataDictionary processorParameters = new OpaqueDataDictionary();
            processorParameters["ColorKeyColor"] = ColorKeyColor;
            processorParameters["ColorKeyEnabled"] = ColorKeyEnabled;
            processorParameters["TextureFormat"] = TextureFormat;
            processorParameters["GenerateMipmaps"] = GenerateMipmaps;
            processorParameters["ResizeTexturesToPowerOfTwo"] =
                ResizeTexturesToPowerOfTwo;

            return context.Convert<MaterialContent, MaterialContent>(material,
                "TankModelMaterialProcessor", processorParameters);
        }
 protected virtual DRMaterialContent OnConvertMaterial(MaterialContent material, ContentProcessorContext context)
 {
     //var processorParameters = new OpaqueDataDictionary
       //{
       //  { "ColorKeyColor", ColorKeyColor },
       //  { "ColorKeyEnabled", ColorKeyEnabled },
       //  { "GenerateMipmaps", GenerateMipmaps },
       //  { "PremultiplyTextureAlpha", PremultiplyTextureAlpha },
       //  { "ResizeTexturesToPowerOfTwo", ResizeTexturesToPowerOfTwo },
       //  { "TextureFormat", TextureFormat },
       //  { "DefaultEffectType", DefaultEffectType },
       //  { "DefaultEffectFile", DefaultEffectFile },
       //};
       return context.Convert<MaterialContent, DRMaterialContent>(material, typeof(DRMaterialProcessor).Name/*, processorParameters*/);
 }
        /// <summary>
        /// Use the CustomEffectMaterialProcessor for all of the materials in the model.
        /// We pass the processor parameter along to the material processor for the 
        /// effect file name.
        /// </summary>
        protected override MaterialContent ConvertMaterial(MaterialContent material, 
                                                        ContentProcessorContext context)
        {
            OpaqueDataDictionary processorParameters = new OpaqueDataDictionary();
            processorParameters.Add("CustomEffect", customEffect);
            processorParameters["ColorKeyColor"] = this.ColorKeyColor;
            processorParameters["ColorKeyEnabled"] = this.ColorKeyEnabled;
            processorParameters["TextureFormat"] = this.TextureFormat;
            processorParameters["GenerateMipmaps"] = this.GenerateMipmaps;
            processorParameters["ResizeTexturesToPowerOfTwo"] = 
                                                        this.ResizeTexturesToPowerOfTwo;

            return context.Convert<MaterialContent, MaterialContent>(material, 
                                  "CustomEffectMaterialProcessor", processorParameters);
        }
        protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
        {
            var customMaterial = new EffectMaterialContent();
            var effectPath = Path.GetFullPath(effectFilename);
            customMaterial.Effect = new ExternalReference<EffectContent>(effectPath);

            var parameters = new OpaqueDataDictionary();
            parameters["ColorKeyColor"] = ColorKeyColor;
            parameters["ColorKeyEnabled"] = ColorKeyEnabled;
            parameters["TextureFormat"] = TextureFormat;
            parameters["GenerateMipmaps"] = GenerateMipmaps;
            parameters["ResizeTexturesToPowerOfTwo"] = ResizeTexturesToPowerOfTwo;

            return context.Convert<MaterialContent, MaterialContent>(
                customMaterial, typeof(MaterialProcessor).Name, parameters);
        }
		private void SaveMaterialContentFromData(MaterialContent content)
		{
			content.FileSize = content.ContentData.Length;

			using (TransactionScope scope = TransactionScopeFactory.Create())
			{
				using (MemoryStream stream = new MemoryStream(content.ContentData))
				{
					MaterialContentAdapter.Instance.Update(content, stream);

					TransactionScopeFactory.AttachCommittedAction(new Action<TransactionEventArgs>(Current_TransactionCompleted), false);
				}

				scope.Complete();
			}
		}
        public override MaterialContent Process(MaterialContent input, ContentProcessorContext context)
        {
            // Create a new material effect
            EffectMaterialContent customMaterial = new EffectMaterialContent();

            // Access the input as a basic material
            BasicMaterialContent basicMaterial = (BasicMaterialContent)input;

            // If Texture is null, we are not using texture mapping. Otherwise, we are
            if (skinned)
            {
                string effectFile = Path.GetFullPath("SkinnedEffect.fx");
                customMaterial.Effect = new ExternalReference<EffectContent>(effectFile);

                customMaterial.Textures.Add("Texture", basicMaterial.Texture);
                section = 1;
            }
            else if (basicMaterial.Texture == null)
            {
                // I don't know why, but sometimes you get an invalid material.  So,
                // I just let the base processor handle it.
                if (basicMaterial.DiffuseColor == null)
                    return base.Process(input, context);

                string effectFile = Path.GetFullPath("PhibesEffect1.fx");
                customMaterial.Effect = new ExternalReference<EffectContent>(effectFile);
                customMaterial.OpaqueData.Add("DiffuseColor", basicMaterial.DiffuseColor);
            }
            else
            {
                string effectFile = Path.GetFullPath("PhibesEffect2.fx");
                customMaterial.Effect = new ExternalReference<EffectContent>(effectFile);

                customMaterial.Textures.Add("Texture", basicMaterial.Texture);
            }

            customMaterial.OpaqueData.Add("Light1Location", LightInfo(section, 0));
            customMaterial.OpaqueData.Add("Light1Color", LightInfo(section, 1));
            customMaterial.OpaqueData.Add("Light2Location", LightInfo(section, 2));
            customMaterial.OpaqueData.Add("Light2Color", LightInfo(section, 3));
            customMaterial.OpaqueData.Add("Light3Location", LightInfo(section, 4));
            customMaterial.OpaqueData.Add("Light3Color", LightInfo(section, 5));

            // Chain to the base material processor.
            return base.Process(customMaterial, context);
        }
        protected override MaterialContent ConvertMaterial(MaterialContent material,
           ContentProcessorContext context)
        {
            EffectMaterialContent lppMaterial = new EffectMaterialContent();

            OpaqueDataDictionary processorParameters = new OpaqueDataDictionary();
            processorParameters["ColorKeyColor"] = this.ColorKeyColor;
            processorParameters["ColorKeyEnabled"] = this.ColorKeyEnabled;
            processorParameters["TextureFormat"] = this.TextureFormat;
            processorParameters["GenerateMipmaps"] = this.GenerateMipmaps;
            processorParameters["ResizeTexturesToPowerOfTwo"] = this.ResizeTexturesToPowerOfTwo;
            processorParameters["PremultiplyTextureAlpha"] = false;
            processorParameters["ColorKeyEnabled"] = false;

            lppMaterial.Effect = new ExternalReference<EffectContent>("shaders/LPPMainEffect.fx");
            lppMaterial.CompiledEffect = context.BuildAsset<EffectContent, CompiledEffectContent>(lppMaterial.Effect, "EffectProcessor");

            //extract the extra parameters
            ExtractDefines(lppMaterial, material, context);

            // copy the textures in the original material to the new normal mapping
            // material. this way the diffuse texture is preserved. The
            // PreprocessSceneHierarchy function has already added the normal map
            // texture to the Textures collection, so that will be copied as well.
            foreach (KeyValuePair<String, ExternalReference<TextureContent>> texture
                in material.Textures)
            {
                lppMaterial.Textures.Add(texture.Key, texture.Value);
            }

            try
            {
                lppMaterial.OpaqueData.Add("DiffuseColor", new Vector4((Vector3)material.OpaqueData["DiffuseColor"], (float)material.OpaqueData["Alpha"]));
                lppMaterial.OpaqueData.Add("SpecularColor", material.OpaqueData["SpecularColor"]);
                lppMaterial.OpaqueData.Add("SpecularPower", material.OpaqueData["SpecularPower"]);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            // and convert the material using the NormalMappingMaterialProcessor,
            // who has something special in store for the normal map.
            return context.Convert<MaterialContent, MaterialContent>
                (lppMaterial, typeof(LightPrePassMaterialProcessor).Name, processorParameters);
        }
		protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context) {
			BasicMaterialContent basicMaterialContent = material as BasicMaterialContent;
			bool texture = basicMaterialContent != null;
			if (texture) {
				EffectMaterialContent effectMaterialContent = new EffectMaterialContent();
				string fullPath = Path.GetFullPath("SkinnedModel.fx");
				effectMaterialContent.Effect = new ExternalReference<EffectContent>(fullPath);
				texture = basicMaterialContent.Texture == null;
				if (!texture) {
					effectMaterialContent.Textures.Add("Texture", basicMaterialContent.Texture);
				}
				MaterialContent materialContent = base.ConvertMaterial(effectMaterialContent, context);
				return materialContent;
			} else {
				throw new InvalidContentException(string.Format("SkinnedModelProcessor only supports BasicMaterialContent, but input mesh uses {0}.", material.GetType()));
			}
		}
		protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
		{
			if (string.IsNullOrEmpty(StitchedEffect))
				throw new Exception("Stitched Effect property must be set for StitchUp Model Processor.");

			string fullPath = Path.GetFullPath(Path.Combine(new FileInfo(material.Identity.SourceFilename).DirectoryName, StitchedEffect));
			context.AddDependency(fullPath);

			EffectMaterialContent effectMaterial = new EffectMaterialContent
			{
				CompiledEffect = context.BuildAsset<StitchedEffectContent, CompiledEffectContent>(new ExternalReference<StitchedEffectContent>(fullPath), typeof(StitchedEffectProcessor).Name),
				Identity = material.Identity,
				Name = material.Name
			};

			return effectMaterial;
		}
        /// <summary>
        /// Helper function used by the CustomModelProcessor
        /// to add new ModelPart information.
        /// </summary>
        public void AddModelPart( int triangleCount, int vertexCount, int vertexStride,
            VertexElement[] vertexElements,
            VertexBufferContent vertexBufferContent,
            IndexCollection indexCollection,
            MaterialContent materialContent)
        {
            ModelPart modelPart = new ModelPart();

              modelPart.TriangleCount = triangleCount;
              modelPart.VertexCount = vertexCount;
              modelPart.VertexStride = vertexStride;
              modelPart.VertexElements = vertexElements;
              modelPart.VertexBufferContent = vertexBufferContent;
              modelPart.IndexCollection = indexCollection;
              modelPart.MaterialContent = materialContent;

              modelParts.Add( modelPart );
        }
		public void UpdateMaterialContent()
		{
			const string template = "Hello world !";

			MaterialContent content = new MaterialContent();

			content.ContentID = UuidHelper.NewUuidString();
			content.RelativeID = UuidHelper.NewUuidString();
			content.ContentData = PrepareSimpleData(template);

			MaterialContentAdapter.Instance.Update(content);

			MaterialContentCollection contentLoaded = MaterialContentAdapter.Instance.Load(builder => builder.AppendItem("CONTENT_ID", content.ContentID));

			Assert.IsTrue(contentLoaded.Count > 0);

			string dataRead = Encoding.UTF8.GetString(contentLoaded[0].ContentData);

			Assert.AreEqual(template, dataRead);
		}