Пример #1
0
        public void Apply(  GraphicsDevice graphicsDevice, 
                            EffectParameterCollection parameters,
                            ConstantBuffer[] cbuffers )
        {
			// NOTE: We make the assumption here that the caller has
			// locked the d3dContext for us to use.
            var d3dContext = graphicsDevice._d3dContext;
            if (_pixelShader != null)
            {
                foreach (var sampler in _samplers)
                {
                    var param = parameters[sampler.parameter];
                    var texture = param.Data as Texture;
                    graphicsDevice.Textures[sampler.index] = texture;
                }

                d3dContext.PixelShader.Set(_pixelShader);
            }
            else
            {
                d3dContext.VertexShader.Set(_vertexShader);

                // Set the shader on the device so it can 
                // apply the correct input layout at draw time.
                graphicsDevice._vertexShader = this;
            }

            // Update and set the constants.
            for (var c = 0; c < _cbuffers.Length; c++)
            {
                var cb = cbuffers[_cbuffers[c]];
                cb.Apply(_vertexShader != null, c, parameters);
            }
        }
Пример #2
0
        internal EffectParameter(   EffectParameterClass class_, 
                                    EffectParameterType type, 
                                    string name, 
                                    int rowCount, 
                                    int columnCount,
                                    string semantic, 
                                    EffectAnnotationCollection annotations,
                                    EffectParameterCollection elements,
                                    EffectParameterCollection structMembers,
                                    object data )
		{
            ParameterClass = class_;
            ParameterType = type;

            Name = name;
            Semantic = semantic;
            Annotations = annotations;

            RowCount = rowCount;
			ColumnCount = columnCount;

            Elements = elements;
            StructureMembers = structMembers;

            Data = data;
            StateKey = unchecked(NextStateKey++);
		}
Пример #3
0
 internal Effect(GraphicsDevice device)
 {
     graphicsDevice = device;
     Parameters = new EffectParameterCollection();
     Techniques = new EffectTechniqueCollection();
     CurrentTechnique = new EffectTechnique(this);
 }
 /// <summary>
 /// Creates a new instance of <see cref="XNAEffectParameterCollection"/>.
 /// </summary>
 /// <param name="coll">The XNA effect parameter collection to copy from.</param>
 internal XNAEffectParameterCollection(XFG.EffectParameterCollection coll)
 {
     _params = new List <XNAEffectParameter>(coll.Count);
     for (int i = 0; i < coll.Count; i++)
     {
         _params.Add(new XNAEffectParameter(coll[i]));
     }
 }
Пример #5
0
 public MatricesEffectStructure(EffectParameterCollection parameters)
 {
   this.worldViewProjection = new SemanticMappedMatrix(parameters, "Matrices_WorldViewProjection");
   this.worldInverseTranspose = new SemanticMappedMatrix(parameters, "Matrices_WorldInverseTranspose");
   this.world = new SemanticMappedMatrix(parameters, "Matrices_World");
   this.textureMatrix = new SemanticMappedMatrix(parameters, "Matrices_Texture");
   this.viewProjection = new SemanticMappedMatrix(parameters, "Matrices_ViewProjection");
 }
Пример #6
0
 internal EffectParameter(EffectParameterClass class_, EffectParameterType type, string name, int rowCount, int columnCount, int registerCount, string semantic, EffectAnnotationCollection annotations, EffectParameterCollection elements, EffectParameterCollection structMembers, object data)
 {
   this.ParameterClass = class_;
   this.ParameterType = type;
   this.Name = name;
   this.Semantic = semantic;
   this.Annotations = annotations;
   this.RowCount = rowCount;
   this.ColumnCount = columnCount;
   this.RegisterCount = registerCount;
   this.Elements = elements;
   this.StructureMembers = structMembers;
   this.Data = data;
   this.StateKey = EffectParameter.NextStateKey++;
 }
Пример #7
0
        internal EffectParameter(
			string name,
			string semantic,
			int rowCount,
			int columnCount,
			int elementCount,
			EffectParameterClass parameterClass,
			EffectParameterType parameterType,
			EffectParameterCollection structureMembers,
			EffectAnnotationCollection annotations,
			IntPtr data
		)
        {
            Name = name;
            Semantic = semantic;
            RowCount = rowCount;
            ColumnCount = columnCount;
            if (elementCount > 0)
            {
                List<EffectParameter> elements = new List<EffectParameter>(elementCount);
                for (int i = 0; i < elementCount; i += 1)
                {
                    // FIXME: Probably incomplete? -flibit
                    elements.Add(new EffectParameter(
                        null,
                        null,
                        rowCount,
                        columnCount,
                        0,
                        ParameterClass,
                        parameterType,
                        null, // FIXME: See mojoshader_effects.c:readvalue -flibit
                        null,
                        new IntPtr(
                            data.ToInt64() + (i * rowCount * columnCount)
                        )
                    ));
                }
                Elements = new EffectParameterCollection(elements);
            }
            ParameterClass = parameterClass;
            ParameterType = parameterType;
            StructureMembers = structureMembers;
            Annotations = annotations;
            values = data;
        }
Пример #8
0
        internal EffectParameter(EffectParameter cloneSource)
        {
            // Share all the immutable types.
            ParameterClass = cloneSource.ParameterClass;
            ParameterType = cloneSource.ParameterType;
            Name = cloneSource.Name;
            Semantic = cloneSource.Semantic;
            Annotations = cloneSource.Annotations;
            RowCount = cloneSource.RowCount;
            ColumnCount = cloneSource.ColumnCount;

            // Clone the mutable types.
            Elements = new EffectParameterCollection(cloneSource.Elements);
            StructureMembers = new EffectParameterCollection(cloneSource.StructureMembers);

            // Data is mutable, but a new copy happens during
            // boxing/unboxing so we can just assign it.
            Data = cloneSource.Data;
            StateKey = unchecked(NextStateKey++);
        }
Пример #9
0
        public GraphicEffect(GameScene gameScene, SpriteBatch spriteBatch, SpriteFont spriteFont)
        {
            random = new Random();
            bloom = new BloomComponent(gameScene.Game);
            // Look up the resolution and format of our main backbuffer.
            pp = gameScene.Game.GraphicsDevice.PresentationParameters;

            int width = pp.BackBufferWidth;
            int height = pp.BackBufferHeight;
            //width /= 2;
            //height /= 2;

            blurRenderTarget1 = new RenderTarget2D(gameScene.Game.GraphicsDevice, width, height, false, pp.BackBufferFormat, DepthFormat.None);
            blurRenderTarget2 = new RenderTarget2D(gameScene.Game.GraphicsDevice, width, height, false, pp.BackBufferFormat, DepthFormat.None);
            distortionRenderTarget = new RenderTarget2D(gameScene.Game.GraphicsDevice, width, height, false, pp.BackBufferFormat, DepthFormat.None);
            rippleRenderTarget = new RenderTarget2D(gameScene.Game.GraphicsDevice, width, height, false, pp.BackBufferFormat, DepthFormat.None);
            afterUnderWaterTexture = new RenderTarget2D(gameScene.Game.GraphicsDevice, width, height, false, pp.BackBufferFormat, DepthFormat.None);
            afterBloomTexture = new RenderTarget2D(gameScene.Game.GraphicsDevice, width, height, false, pp.BackBufferFormat, DepthFormat.None);
            afterEffectsRenderTarget = new RenderTarget2D(gameScene.Game.GraphicsDevice, width, height, false, pp.BackBufferFormat, DepthFormat.None);

            underWaterEffect = gameScene.Game.Content.Load<Effect>("Shaders/UnderWater");
            screenTransitionEffect = gameScene.Game.Content.Load<Effect>("Shaders/ScreenTransition");
            edgeDetectionEffect = gameScene.Game.Content.Load<Effect>("Shaders/EdgeDetectionEffect");
            customBlurEffect = gameScene.Game.Content.Load<Effect>("Shaders/CustomBlur");
            distortionEffect = gameScene.Game.Content.Load<Effect>("Shaders/DistortionEffect");
            rippleEffect = gameScene.Game.Content.Load<Effect>("Shaders/RippleEffect");

            edgeDetectionParameters = edgeDetectionEffect.Parameters;
            edgeDetectionEffect.CurrentTechnique = edgeDetectionEffect.Techniques["EdgeDetect"];

            waveParam = rippleEffect.Parameters["wave"];
            distortionParam = rippleEffect.Parameters["distortion"];
            centerCoordParam = rippleEffect.Parameters["centerCoord"];

            this.spriteBatch = spriteBatch;
            this.spriteFont = spriteFont;
        }
Пример #10
0
        /// <summary>
        /// Recursively determines whether the specified collection of effect parameters contains 
        /// <see cref="Parameter"/>.
        /// </summary>
        /// <param name="parameterCollection">The effect parameter collection.</param>
        /// <param name="isField">
        /// <see langword="true"/> if <see cref="Parameter"/> is the member of a struct; otherwise
        /// <see langword="false"/>.
        /// </param>
        /// <returns>
        /// <see langword="true"/> if <paramref name="parameterCollection"/> contains 
        /// <see cref="Parameter"/>; otherwise, <see langword="false"/>.
        /// </returns>
        private bool ContainsParameter(EffectParameterCollection parameterCollection, out bool isField)
        {
            // Compare with parameters in parameterCollection.
              foreach (EffectParameter parameter in parameterCollection)
              {
            if (parameter == Parameter)
            {
              // Wanted parameter is an item of parameterCollection.
              isField = false;
              return true;
            }
              }

              // Recursively compare with all array elements.
              foreach (EffectParameter parameter in parameterCollection)
              {
            if (parameter.Elements.Count > 0)
            {
              // Current parameter in parameterCollection is an array.
              // -> Recursively check elements of array.
              if (ContainsParameter(parameter.Elements, out isField))
              {
            // Wanted parameter is contained in array.
            return true;
              }
            }
              }

              // Recursively compare with all struct members.
              foreach (EffectParameter parameter in parameterCollection)
              {
            if (parameter.ParameterClass == EffectParameterClass.Struct)
            {
              // Current parameter in parameterCollection is a struct.
              // -> Recursively check members of struct.
              bool dummy;
              if (ContainsParameter(parameter.StructureMembers, out dummy))
              {
            // Wanted parameter is a member of the struct.
            isField = true;
            return true;
              }
            }
              }

              isField = false;
              return false;
        }
Пример #11
0
        private unsafe void INTERNAL_parseEffectStruct()
        {
            MojoShader.MOJOSHADER_effect* effectPtr = (MojoShader.MOJOSHADER_effect*) glEffect.EffectData;

            // Set up Parameters
            MojoShader.MOJOSHADER_effectParam* paramPtr = (MojoShader.MOJOSHADER_effectParam*) effectPtr->parameters;
            List<EffectParameter> parameters = new List<EffectParameter>();
            for (int i = 0; i < effectPtr->param_count; i += 1)
            {
                MojoShader.MOJOSHADER_effectParam param = paramPtr[i];
                if (	param.value.value_type == MojoShader.MOJOSHADER_symbolType.MOJOSHADER_SYMTYPE_VERTEXSHADER ||
                    param.value.value_type == MojoShader.MOJOSHADER_symbolType.MOJOSHADER_SYMTYPE_PIXELSHADER	)
                {
                    // Skip shader objects...
                    continue;
                }
                else if (	param.value.value_type >= MojoShader.MOJOSHADER_symbolType.MOJOSHADER_SYMTYPE_SAMPLER &&
                        param.value.value_type <= MojoShader.MOJOSHADER_symbolType.MOJOSHADER_SYMTYPE_SAMPLERCUBE	)
                {
                    string textureName = String.Empty;
                    MojoShader.MOJOSHADER_effectSamplerState* states = (MojoShader.MOJOSHADER_effectSamplerState*) param.value.values;
                    for (int j = 0; j < param.value.value_count; j += 1)
                    {
                        if (	states[j].value.value_type >= MojoShader.MOJOSHADER_symbolType.MOJOSHADER_SYMTYPE_TEXTURE &&
                            states[j].value.value_type <= MojoShader.MOJOSHADER_symbolType.MOJOSHADER_SYMTYPE_TEXTURECUBE	)
                        {
                            MojoShader.MOJOSHADER_effectObject *objectPtr = (MojoShader.MOJOSHADER_effectObject*) effectPtr->objects;
                            int* index = (int*) states[j].value.values;
                            textureName = Marshal.PtrToStringAnsi(objectPtr[*index].mapping.name);
                            break;
                        }
                    }
                    /* Because textures have to be declared before the sampler,
                     * we can assume that it will always be in the list by the
                     * time we get to this point.
                     * -flibit
                     */
                    for (int j = 0; j < parameters.Count; j += 1)
                    {
                        if (textureName.Equals(parameters[j].Name))
                        {
                            samplerMap[Marshal.PtrToStringAnsi(param.value.name)] = parameters[j];
                            break;
                        }
                    }
                    continue;
                }
                parameters.Add(new EffectParameter(
                    Marshal.PtrToStringAnsi(param.value.name),
                    Marshal.PtrToStringAnsi(param.value.semantic),
                    (int) param.value.row_count,
                    (int) param.value.column_count,
                    (int) param.value.element_count,
                    XNAClass[(int) param.value.value_class],
                    XNAType[(int) param.value.value_type],
                    null, // FIXME: See mojoshader_effects.c:readvalue -flibit
                    INTERNAL_readAnnotations(
                        param.annotations,
                        param.annotation_count
                    ),
                    param.value.values
                ));
            }
            Parameters = new EffectParameterCollection(parameters);

            // Set up Techniques
            MojoShader.MOJOSHADER_effectTechnique* techPtr = (MojoShader.MOJOSHADER_effectTechnique*) effectPtr->techniques;
            List<EffectTechnique> techniques = new List<EffectTechnique>(effectPtr->technique_count);
            for (int i = 0; i < techniques.Capacity; i += 1)
            {
                MojoShader.MOJOSHADER_effectTechnique tech = techPtr[i];

                // Set up Passes
                MojoShader.MOJOSHADER_effectPass* passPtr = (MojoShader.MOJOSHADER_effectPass*) tech.passes;
                List<EffectPass> passes = new List<EffectPass>((int) tech.pass_count);
                for (int j = 0; j < passes.Capacity; j += 1)
                {
                    MojoShader.MOJOSHADER_effectPass pass = passPtr[j];
                    passes.Add(new EffectPass(
                        Marshal.PtrToStringAnsi(pass.name),
                        INTERNAL_readAnnotations(
                            pass.annotations,
                            pass.annotation_count
                        ),
                        this,
                        (uint) j
                    ));
                }

                techniques.Add(new EffectTechnique(
                    Marshal.PtrToStringAnsi(tech.name),
                    (IntPtr) (techPtr + i),
                    new EffectPassCollection(passes),
                    INTERNAL_readAnnotations(
                        tech.annotations,
                        tech.annotation_count
                    )
                ));
            }
            Techniques = new EffectTechniqueCollection(techniques);
        }
Пример #12
0
using System;
Пример #13
0
        private static EffectParameterCollection ReadParameters(BinaryReader reader)
        {
            var collection = new EffectParameterCollection();
            var count      = (int)reader.ReadByte();

            if (count == 0)
            {
                return(collection);
            }

            for (var i = 0; i < count; i++)
            {
                var class_ = (EffectParameterClass)reader.ReadByte();
                var type   = (EffectParameterType)reader.ReadByte();

                var name        = reader.ReadString();
                var semantic    = reader.ReadString();
                var annotations = ReadAnnotations(reader);

                var rowCount    = (int)reader.ReadByte();
                var columnCount = (int)reader.ReadByte();

                var elements      = ReadParameters(reader);
                var structMembers = ReadParameters(reader);

                object data = null;
                if (elements.Count == 0 && structMembers.Count == 0)
                {
                    switch (type)
                    {
                    case EffectParameterType.Bool:
                    case EffectParameterType.Int32:
                    {
                        var buffer = new int[rowCount * columnCount];
                        for (var j = 0; j < buffer.Length; j++)
                        {
                            buffer[j] = reader.ReadInt32();
                        }
                        data = buffer;
                        break;
                    }

                    case EffectParameterType.Single:
                    {
                        var buffer = new float[rowCount * columnCount];
                        for (var j = 0; j < buffer.Length; j++)
                        {
                            buffer[j] = reader.ReadSingle();
                        }
                        data = buffer;
                        break;
                    }

                    case EffectParameterType.String:
                        throw new NotImplementedException();
                    }
                    ;
                }

                var param = new EffectParameter(
                    class_, type, name, rowCount, columnCount, semantic,
                    annotations, elements, structMembers, data);

                collection.Add(param);
            }

            return(collection);
        }
Пример #14
0
 private EffectParameterCollection ReadParameters(BinaryReader reader)
 {
   EffectParameterCollection parameterCollection = new EffectParameterCollection();
   int num = (int) reader.ReadByte();
   if (num == 0)
     return parameterCollection;
   for (int index1 = 0; index1 < num; ++index1)
   {
     EffectParameterClass class_ = (EffectParameterClass) reader.ReadByte();
     EffectParameterType type = (EffectParameterType) reader.ReadByte();
     string name = reader.ReadString();
     string semantic = reader.ReadString();
     EffectAnnotationCollection annotations = Effect.ReadAnnotations(reader);
     int rowCount = (int) reader.ReadByte();
     int columnCount = (int) reader.ReadByte();
     int registerCount = this.version >= 5 ? (int) reader.ReadByte() : rowCount;
     EffectParameterCollection elements = this.ReadParameters(reader);
     EffectParameterCollection structMembers = this.ReadParameters(reader);
     object data = (object) null;
     if (elements.Count == 0 && structMembers.Count == 0)
     {
       switch (type)
       {
         case EffectParameterType.Bool:
         case EffectParameterType.Int32:
         case EffectParameterType.Single:
           float[] numArray = new float[rowCount * columnCount];
           for (int index2 = 0; index2 < numArray.Length; ++index2)
             numArray[index2] = reader.ReadSingle();
           data = (object) numArray;
           break;
         case EffectParameterType.String:
           throw new NotImplementedException();
       }
     }
     EffectParameter effectParameter = new EffectParameter(class_, type, name, rowCount, columnCount, registerCount, semantic, annotations, elements, structMembers, data);
     parameterCollection.Add(effectParameter);
   }
   return parameterCollection;
 }
Пример #15
0
		public virtual void Apply (GraphicsDevice graphicsDevice,
							int program, 
							EffectParameterCollection parameters,
							ConstantBuffer[] cbuffers)
		{									
			var textures = graphicsDevice.Textures;
			var samplerStates = graphicsDevice.SamplerStates;

			if (ShaderType == ShaderType.FragmentShader) {
				// Activate the textures.
				foreach (var sampler in _samplers) {
					// Set the sampler texture slot.
					//
					// TODO: This seems like it only needs to be done once!
					//
					var loc = GL.GetUniformLocation (program, sampler.name);
					GL.Uniform1 (loc, sampler.index);

					// TODO: Fix Volume samplers!
					// (are they really broken?)
					if (sampler.type == SamplerType.SamplerVolume)
						throw new NotImplementedException ();

					Texture tex = null;
					if (sampler.parameter >= 0) {
						var textureParameter = parameters [sampler.parameter];
						tex = textureParameter.Data as Texture;
					}

					if (tex == null) {
						//texutre 0 will be set in drawbatch :/
						if (sampler.index == 0)
							continue;

						//are smapler indexes always normal texture indexes?
						tex = (Texture)textures [sampler.index];
					}

					if (tex != null) {
						tex.glTextureUnit = ((TextureUnit)((int)TextureUnit.Texture0 + sampler.index));
						tex.Activate ();						
						samplerStates [sampler.index].Activate (tex.glTarget, tex.LevelCount > 1);
					}
				}
			}

			// Update and set the constants.
			for (var c = 0; c < _cbuffers.Length; c++) {
				var cb = cbuffers [_cbuffers [c]];
				cb.Apply (program, parameters);
			}

			if (ShaderType == ShaderType.VertexShader) {
				// Apply vertex shader fix:
				// The following two lines are appended to the end of vertex shaders
				// to account for rendering differences between OpenGL and DirectX:
				//
				// gl_Position.y = gl_Position.y * posFixup.y;
				// gl_Position.xy += posFixup.zw * gl_Position.ww;
				//
				// (the following paraphrased from wine, wined3d/state.c and wined3d/glsl_shader.c)
				//
				// - We need to flip along the y-axis in case of offscreen rendering.
				// - D3D coordinates refer to pixel centers while GL coordinates refer
				//   to pixel corners.
				// - D3D has a top-left filling convention. We need to maintain this
				//   even after the y-flip mentioned above.
				// In order to handle the last two points, we translate by
				// (63.0 / 128.0) / VPw and (63.0 / 128.0) / VPh. This is equivalent to
				// translating slightly less than half a pixel. We want the difference to
				// be large enough that it doesn't get lost due to rounding inside the
				// driver, but small enough to prevent it from interfering with any
				// anti-aliasing.
				//
				// OpenGL coordinates specify the center of the pixel while d3d coords specify
				// the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
				// 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
				// contains 1.0 to allow a mad.
	
				_posFixup [0] = 1.0f;
				_posFixup [1] = 1.0f;
				_posFixup [2] = (63.0f / 64.0f) / graphicsDevice.Viewport.Width;
				_posFixup [3] = -(63.0f / 64.0f) / graphicsDevice.Viewport.Height;
				//If we have a render target bound (rendering offscreen)
				if (graphicsDevice.GetRenderTargets ().Length > 0) {
					//flip vertically
					_posFixup [1] *= -1.0f;
					_posFixup [3] *= -1.0f;
				}
				var posFixupLoc = GL.GetUniformLocation (program, "posFixup"); // TODO: Look this up on link!
				GL.Uniform4 (posFixupLoc, 1, _posFixup);
			}
		}
Пример #16
0
        protected Effect(GraphicsDevice graphicsDevice, Effect cloneSource)
        {
            Parameters = new EffectParameterCollection();
            Techniques = new EffectTechniqueCollection();

            if (graphicsDevice == null)
            {
                throw new ArgumentNullException("Graphics Device Cannot Be Null");
            }
            this.graphicsDevice = graphicsDevice;
        }
Пример #17
0
        internal EffectParameter(
            string name,
            string semantic,
            int rowCount,
            int columnCount,
            int elementCount,
            EffectParameterClass parameterClass,
            EffectParameterType parameterType,
            EffectParameterCollection structureMembers,
            EffectAnnotationCollection annotations,
            IntPtr data,
            uint dataSizeBytes
            )
        {
            if (data == IntPtr.Zero)
            {
                throw new ArgumentNullException("data");
            }

            Name        = name;
            Semantic    = semantic ?? string.Empty;
            RowCount    = rowCount;
            ColumnCount = columnCount;
            if (elementCount > 0)
            {
                int curOffset = 0;
                List <EffectParameter> elements = new List <EffectParameter>(elementCount);
                for (int i = 0; i < elementCount; i += 1)
                {
                    EffectParameterCollection elementMembers = null;
                    if (structureMembers != null)
                    {
                        List <EffectParameter> memList = new List <EffectParameter>();
                        for (int j = 0; j < structureMembers.Count; j += 1)
                        {
                            int memElems = 0;
                            if (structureMembers[j].Elements != null)
                            {
                                memElems = structureMembers[j].Elements.Count;
                            }
                            int memSize = structureMembers[j].RowCount * 4;
                            if (memElems > 0)
                            {
                                memSize *= memElems;
                            }
                            memList.Add(new EffectParameter(
                                            structureMembers[j].Name,
                                            structureMembers[j].Semantic,
                                            structureMembers[j].RowCount,
                                            structureMembers[j].ColumnCount,
                                            memElems,
                                            structureMembers[j].ParameterClass,
                                            structureMembers[j].ParameterType,
                                            null,                     // FIXME: Nested structs! -flibit
                                            structureMembers[j].Annotations,
                                            new IntPtr(data.ToInt64() + curOffset),
                                            (uint)memSize * 4
                                            ));
                            curOffset += memSize * 4;
                        }
                        elementMembers = new EffectParameterCollection(memList);
                    }
                    // FIXME: Probably incomplete? -flibit
                    elements.Add(new EffectParameter(
                                     null,
                                     null,
                                     rowCount,
                                     columnCount,
                                     0,
                                     ParameterClass,
                                     parameterType,
                                     elementMembers,
                                     null,
                                     new IntPtr(
                                         data.ToInt64() + (i * rowCount * 16)
                                         ),
                                     // FIXME: Not obvious to me how to compute this -kg
                                     0
                                     ));
                }
                Elements = new EffectParameterCollection(elements);
            }
            ParameterClass   = parameterClass;
            ParameterType    = parameterType;
            StructureMembers = structureMembers;
            Annotations      = annotations;
            values           = data;
            valuesSizeBytes  = dataSizeBytes;
        }
Пример #18
0
        public virtual void Apply(GraphicsDevice graphicsDevice,
                                  int program,
                                  EffectParameterCollection parameters,
                                  ConstantBuffer[] cbuffers)
        {
            var textures      = graphicsDevice.Textures;
            var samplerStates = graphicsDevice.SamplerStates;

            if (ShaderType == ShaderType.FragmentShader)
            {
                // Activate the textures.
                foreach (var sampler in _samplers)
                {
                    // Set the sampler texture slot.
                    //
                    // TODO: This seems like it only needs to be done once!
                    //
                    var loc = GL.GetUniformLocation(program, sampler.name);
                    GL.Uniform1(loc, sampler.index);

                    // TODO: Fix Volume samplers!
                    // (are they really broken?)
                    if (sampler.type == SamplerType.SamplerVolume)
                    {
                        throw new NotImplementedException();
                    }

                    Texture tex = null;
                    if (sampler.parameter >= 0)
                    {
                        var textureParameter = parameters [sampler.parameter];
                        tex = textureParameter.Data as Texture;
                    }

                    if (tex == null)
                    {
                        //texutre 0 will be set in drawbatch :/
                        if (sampler.index == 0)
                        {
                            continue;
                        }

                        //are smapler indexes always normal texture indexes?
                        tex = (Texture)textures [sampler.index];
                    }

                    if (tex != null)
                    {
                        tex.glTextureUnit = ((TextureUnit)((int)TextureUnit.Texture0 + sampler.index));
                        tex.Activate();
                        samplerStates [sampler.index].Activate(tex.glTarget, tex.LevelCount > 1);
                    }
                }
            }

            // Update and set the constants.
            for (var c = 0; c < _cbuffers.Length; c++)
            {
                var cb = cbuffers [_cbuffers [c]];
                cb.Apply(program, parameters);
            }

            if (ShaderType == ShaderType.VertexShader)
            {
                // Apply vertex shader fix:
                // The following two lines are appended to the end of vertex shaders
                // to account for rendering differences between OpenGL and DirectX:
                //
                // gl_Position.y = gl_Position.y * posFixup.y;
                // gl_Position.xy += posFixup.zw * gl_Position.ww;
                //
                // (the following paraphrased from wine, wined3d/state.c and wined3d/glsl_shader.c)
                //
                // - We need to flip along the y-axis in case of offscreen rendering.
                // - D3D coordinates refer to pixel centers while GL coordinates refer
                //   to pixel corners.
                // - D3D has a top-left filling convention. We need to maintain this
                //   even after the y-flip mentioned above.
                // In order to handle the last two points, we translate by
                // (63.0 / 128.0) / VPw and (63.0 / 128.0) / VPh. This is equivalent to
                // translating slightly less than half a pixel. We want the difference to
                // be large enough that it doesn't get lost due to rounding inside the
                // driver, but small enough to prevent it from interfering with any
                // anti-aliasing.
                //
                // OpenGL coordinates specify the center of the pixel while d3d coords specify
                // the corner. The offsets are stored in z and w in posFixup. posFixup.y contains
                // 1.0 or -1.0 to turn the rendering upside down for offscreen rendering. PosFixup.x
                // contains 1.0 to allow a mad.

                _posFixup [0] = 1.0f;
                _posFixup [1] = 1.0f;
                _posFixup [2] = (63.0f / 64.0f) / graphicsDevice.Viewport.Width;
                _posFixup [3] = -(63.0f / 64.0f) / graphicsDevice.Viewport.Height;
                //If we have a render target bound (rendering offscreen)
                if (graphicsDevice.GetRenderTargets().Length > 0)
                {
                    //flip vertically
                    _posFixup [1] *= -1.0f;
                    _posFixup [3] *= -1.0f;
                }
                var posFixupLoc = GL.GetUniformLocation(program, "posFixup");                  // TODO: Look this up on link!
                GL.Uniform4(posFixupLoc, 1, _posFixup);
            }
        }
Пример #19
0
 protected override void ApplyPhysicsParamaters(EffectParameterCollection parameters)
 {
     parameters["GravityY"].SetValue(-.0984f);
 }
Пример #20
0
 public MaterialEffectStructure(EffectParameterCollection parameters)
 {
   this.diffuse = new SemanticMappedVector3(parameters, "Material_Diffuse");
   this.opacity = new SemanticMappedSingle(parameters, "Material_Opacity");
 }
Пример #21
0
		private static EffectParameterCollection ReadParameters(BinaryReader reader)
		{
			var collection = new EffectParameterCollection();
			var count = (int)reader.ReadByte();			if (count == 0)				return collection;
			for (var i = 0; i < count; i++)
			{
				var class_ = (EffectParameterClass)reader.ReadByte();				var type = (EffectParameterType)reader.ReadByte();
				var name = reader.ReadString();
				var semantic = reader.ReadString();
				var annotations = ReadAnnotations(reader);
				var rowCount = (int)reader.ReadByte();
				var columnCount = (int)reader.ReadByte();

				var elements = ReadParameters(reader);
				var structMembers = ReadParameters(reader);

				object data = null;
				if (elements.Count == 0 && structMembers.Count == 0)
				{
					switch (type)
					{						case EffectParameterType.Bool:						case EffectParameterType.Int32:							{								var buffer = new int[rowCount * columnCount];								for (var j = 0; j < buffer.Length; j++)									buffer[j] = reader.ReadInt32();								data = buffer;								break;							}
						case EffectParameterType.Single:
							{
								var buffer = new float[rowCount * columnCount];
								for (var j = 0; j < buffer.Length; j++)									buffer[j] = reader.ReadSingle();								data = buffer;								break;							}
						case EffectParameterType.String:
							throw new NotImplementedException();
					};				}
				var param = new EffectParameter(
					class_, type, name, rowCount, columnCount, semantic, 
					annotations, elements, structMembers, data);

				collection.Add(param);
			}

			return collection;
		}
Пример #22
0
        /// <summary>
        /// Clone the source into this existing object.
        /// </summary>
        /// <remarks>
        /// Note this is not overloaded in derived classes on purpose.  This is
        /// only a reason this exists is for caching effects.
        /// </remarks>
        /// <param name="cloneSource">The source effect to clone from.</param>
        private void Clone(Effect cloneSource)
        {
            Debug.Assert(_isClone, "Cannot clone into non-cloned effect!");

            // Copy the mutable members of the effect.
            Parameters = new EffectParameterCollection(cloneSource.Parameters);
            Techniques = new EffectTechniqueCollection(this, cloneSource.Techniques);

            // Make a copy of the immutable constant buffers.
            ConstantBuffers = new ConstantBuffer[cloneSource.ConstantBuffers.Length];
            for (var i = 0; i < cloneSource.ConstantBuffers.Length; i++)
                ConstantBuffers[i] = new ConstantBuffer(cloneSource.ConstantBuffers[i]);

            // Find and set the current technique.
            for (var i = 0; i < cloneSource.Techniques.Count; i++)
            {
                if (cloneSource.Techniques[i] == cloneSource.CurrentTechnique)
                {
                    CurrentTechnique = Techniques[i];
                    break;
                }
            }

            // Take a reference to the original shader list.
            _shaderList = cloneSource._shaderList;
        }
Пример #23
0
        public bool IsDisposed = false; // GG TODO this should be hooked up along with the rest of the Disposable interface

        //GG EDIT
        private void Init(String assetName, String body, GraphicsDevice graphicsDevice)
        {
            _name = assetName;
            if (graphicsDevice == null)
            {
                throw new ArgumentNullException("Graphics Device Cannot Be Null");
            }
            this.graphicsDevice = graphicsDevice;

            program_handle = GL.CreateProgram();

            Parameters = new EffectParameterCollection();
            Techniques = new EffectTechniqueCollection();

            InitVertexShader("DEFAULT_VERTEX", GGShader.DEFAULT_VERTEX);
            InitFragmentShader(assetName, body);

            GL.AttachShader(program_handle, vertex_handle);
            GL.AttachShader(program_handle, fragment_handle);
            GL.LinkProgram(program_handle);

            int actUnis = 0;

            Parameters._parameters.Clear();
            List <int> texes = new List <int>();

            GL.GetProgram(program_handle, ProgramParameter.ActiveUniforms, out actUnis);
            for (int x = 0; x < actUnis; x++)
            {
                int length, size;
                ActiveUniformType type;
                StringBuilder     name = new StringBuilder(100);
                GL.GetActiveUniform(program_handle, x, 100, out length, out size, out type, name);
                String fixedName = name.ToString();

                int location = GL.GetUniformLocation(program_handle, fixedName);
                if (fixedName.EndsWith("[0]"))
                {
                    fixedName = fixedName.Substring(0, fixedName.Length - 3);
                }
                Console.WriteLine("{0}: {1} {2} {3}", location, fixedName, type, size);
                EffectParameter efp = new EffectParameter(this, fixedName, location, type.ToString(), length, size);
                if (type == ActiveUniformType.Sampler2D)
                {
                    texes.Add(location);
                }

                Parameters._parameters.Add(efp.Name, efp);

                List <EffectParameter> _textureMappings = new List <EffectParameter>();

                if (efp.ParameterType == EffectParameterType.Texture2D)
                {
                    _textureMappings.Add(efp);
                }
            }
            texes.Sort();
            texture_locations = texes.ToArray();

            position_index = GL.GetAttribLocation(program_handle, "a_Position");
            color_index    = GL.GetAttribLocation(program_handle, "a_Color");
            texCoord_index = GL.GetAttribLocation(program_handle, "a_TexCoord");

            CurrentTechnique           = new EffectTechnique(this);
            CurrentTechnique.Passes[0] = new EffectPass(CurrentTechnique);
        }
Пример #24
0
 internal EffectParameter(
     string name,
     string semantic,
     int rowCount,
     int columnCount,
     int elementCount,
     EffectParameterClass parameterClass,
     EffectParameterType parameterType,
     EffectParameterCollection structureMembers,
     EffectAnnotationCollection annotations,
     IntPtr data
     )
 {
     Name        = name;
     Semantic    = semantic;
     RowCount    = rowCount;
     ColumnCount = columnCount;
     if (elementCount > 0)
     {
         int curOffset = 0;
         List <EffectParameter> elements = new List <EffectParameter>(elementCount);
         for (int i = 0; i < elementCount; i += 1)
         {
             EffectParameterCollection elementMembers = null;
             if (structureMembers != null)
             {
                 List <EffectParameter> memList = new List <EffectParameter>();
                 for (int j = 0; j < structureMembers.Count; j += 1)
                 {
                     int memElems = 0;
                     if (structureMembers[j].Elements != null)
                     {
                         memElems = structureMembers[j].Elements.Count;
                     }
                     memList.Add(new EffectParameter(
                                     structureMembers[j].Name,
                                     structureMembers[j].Semantic,
                                     structureMembers[j].RowCount,
                                     structureMembers[j].ColumnCount,
                                     memElems,
                                     structureMembers[j].ParameterClass,
                                     structureMembers[j].ParameterType,
                                     null,                     // FIXME: Nested structs! -flibit
                                     structureMembers[j].Annotations,
                                     new IntPtr(data.ToInt64() + curOffset)
                                     ));
                     int memSize = structureMembers[j].RowCount * 4;
                     if (memElems > 0)
                     {
                         memSize *= memElems;
                     }
                     curOffset += memSize * 4;
                 }
                 elementMembers = new EffectParameterCollection(memList);
             }
             // FIXME: Probably incomplete? -flibit
             elements.Add(new EffectParameter(
                              null,
                              null,
                              rowCount,
                              columnCount,
                              0,
                              ParameterClass,
                              parameterType,
                              elementMembers,
                              null,
                              new IntPtr(
                                  data.ToInt64() + (i * rowCount * 16)
                                  )
                              ));
         }
         Elements = new EffectParameterCollection(elements);
     }
     ParameterClass   = parameterClass;
     ParameterType    = parameterType;
     StructureMembers = structureMembers;
     Annotations      = annotations;
     values           = data;
 }
Пример #25
0
		internal void ReadEffect(BinaryReader reader)
		{
			var effectPass = new EffectPass(this, "Pass", null, null, BlendState.AlphaBlend, DepthStencilState.Default, RasterizerState.CullNone, new EffectAnnotationCollection());
			effectPass._shaderProgram = new ShaderProgram(reader.ReadBytes((int)reader.BaseStream.Length));
			var shaderProgram = effectPass._shaderProgram;
			Parameters = new EffectParameterCollection();
			for (int i = 0; i < shaderProgram.UniformCount; i++)
			{	
			    Parameters.Add(EffectParameterForUniform(shaderProgram, i));
			}
			
			#warning Hacks for BasicEffect as we don't have these parameters yet
            Parameters.Add (new EffectParameter(
                EffectParameterClass.Vector, EffectParameterType.Single, "SpecularColor",
                3, 1, "float3",
                new EffectAnnotationCollection(), new EffectParameterCollection(), new EffectParameterCollection(), new float[3]));
            Parameters.Add (new EffectParameter(
                EffectParameterClass.Scalar, EffectParameterType.Single, "SpecularPower",
                1, 1, "float",
                new EffectAnnotationCollection(), new EffectParameterCollection(), new EffectParameterCollection(), 0.0f));
            Parameters.Add (new EffectParameter(
                EffectParameterClass.Vector, EffectParameterType.Single, "FogVector",
                4, 1, "float4",
                new EffectAnnotationCollection(), new EffectParameterCollection(), new EffectParameterCollection(), new float[4]));
            Parameters.Add (new EffectParameter(
                EffectParameterClass.Vector, EffectParameterType.Single, "DiffuseColor",
                4, 1, "float4",
                new EffectAnnotationCollection(), new EffectParameterCollection(), new EffectParameterCollection(), new float[4]));
            
            Techniques = new EffectTechniqueCollection();
            var effectPassCollection = new EffectPassCollection();
            effectPassCollection.Add(effectPass);
            Techniques.Add(new EffectTechnique(this, "Name", effectPassCollection, new EffectAnnotationCollection()));
       
            ConstantBuffers = new ConstantBuffer[0];
            
            CurrentTechnique = Techniques[0];
        }
Пример #26
0
        public void Update(EffectParameterCollection parameters)
        {
            // TODO:  We should be doing some sort of dirty state 
            // testing here.
            //
            // It should let us skip all parameter updates if
            // nothing has changed.  It should not be per-parameter
            // as that is why you should use multiple constant
            // buffers.

            // If our state key becomes larger than the 
            // next state key then the keys have rolled 
            // over and we need to reset.
            if (_stateKey > EffectParameter.NextStateKey)
                _stateKey = 0;
            
            for (var p = 0; p < _parameters.Length; p++)
            {
                var index = _parameters[p];
                var param = parameters[index];

                if (param.StateKey < _stateKey)
                    continue;

                var offset = _offsets[p];
                _dirty = true;

                SetParameter(offset, param);
            }

            _stateKey = EffectParameter.NextStateKey;
        }
Пример #27
0
 public void Update(EffectParameterCollection parameters)
 {
   if (this._stateKey > EffectParameter.NextStateKey)
     this._stateKey = 0UL;
   for (int index1 = 0; index1 < this._parameters.Length; ++index1)
   {
     int index2 = this._parameters[index1];
     EffectParameter effectParameter = parameters[index2];
     if (effectParameter.StateKey >= this._stateKey)
     {
       int offset = this._offsets[index1];
       this._dirty = true;
       this.SetParameter(offset, effectParameter);
     }
   }
   this._stateKey = EffectParameter.NextStateKey;
 }
Пример #28
0
 internal EffectParameter(EffectParameterClass class_, EffectParameterType type, string name, int rowCount, int columnCount, int registerCount, string semantic, EffectAnnotationCollection annotations, EffectParameterCollection elements, EffectParameterCollection structMembers, object data)
 {
     this.ParameterClass   = class_;
     this.ParameterType    = type;
     this.Name             = name;
     this.Semantic         = semantic;
     this.Annotations      = annotations;
     this.RowCount         = rowCount;
     this.ColumnCount      = columnCount;
     this.RegisterCount    = registerCount;
     this.Elements         = elements;
     this.StructureMembers = structMembers;
     this.Data             = data;
     this.StateKey         = EffectParameter.NextStateKey++;
 }
Пример #29
0
        internal Effect(GraphicsDevice aGraphicsDevice)
        {
            if (aGraphicsDevice == null)
            {
                throw new ArgumentNullException("Graphics Device Cannot Be Null");
            }
            this.graphicsDevice = aGraphicsDevice;

            Parameters = new EffectParameterCollection();
            Techniques = new EffectTechniqueCollection();
            CurrentTechnique = new EffectTechnique(this);
        }
Пример #30
0
 protected virtual void ApplyPhysicsParamaters(EffectParameterCollection parameters)
 {
 }
Пример #31
0
        internal EffectParameter(
			string name,
			string semantic,
			int rowCount,
			int columnCount,
			int elementCount,
			EffectParameterClass parameterClass,
			EffectParameterType parameterType,
			EffectParameterCollection structureMembers,
			EffectAnnotationCollection annotations,
			IntPtr data
		)
        {
            Name = name;
            Semantic = semantic;
            RowCount = rowCount;
            ColumnCount = columnCount;
            if (elementCount > 0)
            {
                int curOffset = 0;
                List<EffectParameter> elements = new List<EffectParameter>(elementCount);
                for (int i = 0; i < elementCount; i += 1)
                {
                    EffectParameterCollection elementMembers = null;
                    if (structureMembers != null)
                    {
                        List<EffectParameter> memList = new List<EffectParameter>();
                        for (int j = 0; j < structureMembers.Count; j += 1)
                        {
                            int memElems = 0;
                            if (structureMembers[j].Elements != null)
                            {
                                memElems = structureMembers[j].Elements.Count;
                            }
                            memList.Add(new EffectParameter(
                                structureMembers[j].Name,
                                structureMembers[j].Semantic,
                                structureMembers[j].RowCount,
                                structureMembers[j].ColumnCount,
                                memElems,
                                structureMembers[j].ParameterClass,
                                structureMembers[j].ParameterType,
                                null, // FIXME: Nested structs! -flibit
                                structureMembers[j].Annotations,
                                new IntPtr(data.ToInt64() + curOffset)
                            ));
                            int memSize = structureMembers[j].RowCount * structureMembers[j].ColumnCount;
                            if (memElems > 0)
                            {
                                memSize *= memElems;
                            }
                            curOffset += memSize * 4;
                        }
                        elementMembers = new EffectParameterCollection(memList);
                    }
                    // FIXME: Probably incomplete? -flibit
                    elements.Add(new EffectParameter(
                        null,
                        null,
                        rowCount,
                        columnCount,
                        0,
                        ParameterClass,
                        parameterType,
                        elementMembers,
                        null,
                        new IntPtr(
                            data.ToInt64() + (i * 4 * rowCount * columnCount)
                        )
                    ));
                }
                Elements = new EffectParameterCollection(elements);
            }
            ParameterClass = parameterClass;
            ParameterType = parameterType;
            StructureMembers = structureMembers;
            Annotations = annotations;
            values = data;
        }
Пример #32
0
 public FogEffectStructure(EffectParameterCollection parameters)
 {
   this.fogType = new SemanticMappedInt32(parameters, "Fog_Type");
   this.fogColor = new SemanticMappedVector3(parameters, "Fog_Color");
   this.fogDensity = new SemanticMappedSingle(parameters, "Fog_Density");
 }
Пример #33
0
        internal EffectParameter(Effect parent, string paramName, int paramIndex, int userIndex, int uniformLocation,
                                 string paramSType, int paramLength, int numOfElements)
        {
            _parentEffect = parent;

            internalIndex      = paramIndex;
            internalLength     = paramLength;
            this.numOfElements = numOfElements;

            this.userIndex       = userIndex;
            this.uniformLocation = uniformLocation;

            elements = new EffectParameterCollection();

            // Check if the parameter is an array
            if (numOfElements > 1)
            {
                // We have to strip off the [0] at the end so that the
                // parameter can be references with just the name with no
                // index specifications
                if (paramName.EndsWith("[0]"))
                {
                    paramName = paramName.Remove(paramName.Length - 3);
                }
            }

            name = paramName;

            switch (paramSType)
            {
            case "Float":
                paramType    = EffectParameterType.Single;
                paramClass   = EffectParameterClass.Scalar;
                rowCount     = 1;
                colCount     = 1;
                _cachedValue = 0.0f;
                break;

            case "FloatVec2":
                paramType    = EffectParameterType.Single;
                paramClass   = EffectParameterClass.Vector;
                rowCount     = 1;
                colCount     = 2;
                _cachedValue = MonoMac.OpenGL.Vector2.Zero;
                break;

            case "FloatVec3":
                paramType    = EffectParameterType.Single;
                paramClass   = EffectParameterClass.Vector;
                rowCount     = 1;
                colCount     = 3;
                _cachedValue = MonoMac.OpenGL.Vector3.Zero;
                break;

            case "FloatVec4":
                paramType    = EffectParameterType.Single;
                paramClass   = EffectParameterClass.Vector;
                rowCount     = 1;
                colCount     = 4;
                _cachedValue = MonoMac.OpenGL.Vector4.Zero;
                break;

            case "Sampler2D":
                paramType  = EffectParameterType.Texture2D;
                paramClass = EffectParameterClass.Object;
                rowCount   = 0;
                colCount   = 0;
                break;

            case "FloatMat4":
                paramType    = EffectParameterType.Single;
                paramClass   = EffectParameterClass.Matrix;
                rowCount     = 4;
                colCount     = 4;
                _cachedValue = MonoMac.OpenGL.Matrix4.Identity;
                break;
            }

            if (numOfElements > 1)
            {
                // Setup our elements
                for (int x = 0; x < numOfElements; x++)
                {
                    EffectParameter ep = new EffectParameter(parent, name, paramIndex, userIndex, uniformLocation,
                                                             paramType, paramClass, rowCount, colCount, _cachedValue, paramLength);
                    elements._parameters.Add(ep.Name + "[" + x + "]", ep);
                }
            }
        }
Пример #34
0
        /// <summary>
        /// Helper for loading and initializing the particle effect.
        /// </summary>
        void LoadParticleEffect()
        {
            Effect effect = content.Load<Effect>("Shaders/ParticleEffect");

            // If we have several particle systems, the content manager will return
            // a single shared effect instance to them all. But we want to preconfigure
            // the effect with parameters that are specific to this particular
            // particle system. By cloning the effect, we prevent one particle system
            // from stomping over the parameter settings of another.

            particleEffect = effect.Clone();

            parameters = particleEffect.Parameters;

            // Look up shortcuts for parameters that change every frame.
            effectViewParameter = parameters["View"];
            effectProjectionParameter = parameters["Projection"];
            effectViewportScaleParameter = parameters["ViewportScale"];
            effectTimeParameter = parameters["CurrentTime"];

            // Set the values of parameters that do not change.
            parameters["Duration"].SetValue((float)settings.Duration.TotalSeconds);
            parameters["DurationRandomness"].SetValue(settings.DurationRandomness);
            parameters["Gravity"].SetValue(settings.Gravity);
            parameters["EndVelocity"].SetValue(settings.EndVelocity);
            parameters["MinColor"].SetValue(settings.MinColor.ToVector4());
            parameters["MaxColor"].SetValue(settings.MaxColor.ToVector4());

            parameters["RotateSpeed"].SetValue(
                new Vector2(settings.MinRotateSpeed, settings.MaxRotateSpeed));

            parameters["StartSize"].SetValue(
                new Vector2(settings.MinStartSize, settings.MaxStartSize));

            parameters["EndSize"].SetValue(
                new Vector2(settings.MinEndSize, settings.MaxEndSize));

            // Load the particle texture, and set it onto the effect.
            Texture2D texture = content.Load<Texture2D>(settings.TextureName);

            parameters["Texture"].SetValue(texture);
        }
Пример #35
0
		internal void ReadEffect(BinaryReader reader)
		{
			var effectPass = new EffectPass(this, "Pass", null, null, null, DepthStencilState.Default, RasterizerState.CullNone, EffectAnnotationCollection.Empty);
			effectPass._shaderProgram = new ShaderProgram(reader.ReadBytes((int)reader.BaseStream.Length));
			var shaderProgram = effectPass._shaderProgram;
            
            EffectParameter[] parametersArray = new EffectParameter[shaderProgram.UniformCount+4];
			for (int i = 0; i < shaderProgram.UniformCount; i++)
			{	
                parametersArray[i]= EffectParameterForUniform(shaderProgram, i);
			}
			
			#warning Hacks for BasicEffect as we don't have these parameters yet
            parametersArray[shaderProgram.UniformCount] = new EffectParameter(
                EffectParameterClass.Vector, EffectParameterType.Single, "SpecularColor",
                3, 1, "float3",EffectAnnotationCollection.Empty, EffectParameterCollection.Empty, EffectParameterCollection.Empty, new float[3]);
            parametersArray[shaderProgram.UniformCount+1] = new EffectParameter(
                EffectParameterClass.Scalar, EffectParameterType.Single, "SpecularPower",
                1, 1, "float",EffectAnnotationCollection.Empty, EffectParameterCollection.Empty, EffectParameterCollection.Empty, 0.0f);
            parametersArray[shaderProgram.UniformCount+2] = new EffectParameter(
                EffectParameterClass.Vector, EffectParameterType.Single, "FogVector",
                4, 1, "float4",EffectAnnotationCollection.Empty, EffectParameterCollection.Empty, EffectParameterCollection.Empty, new float[4]);
            parametersArray[shaderProgram.UniformCount+3] = new EffectParameter(
                EffectParameterClass.Vector, EffectParameterType.Single, "DiffuseColor",
                4, 1, "float4",EffectAnnotationCollection.Empty, EffectParameterCollection.Empty, EffectParameterCollection.Empty, new float[4]);

            Parameters = new EffectParameterCollection(parametersArray);
                       
            EffectPass []effectsPassArray = new EffectPass[1];
            effectsPassArray[0] = effectPass;
            var effectPassCollection = new EffectPassCollection(effectsPassArray);            
            
            EffectTechnique []effectTechniqueArray = new EffectTechnique[1]; 
            effectTechniqueArray[0] = new EffectTechnique(this, "Name", effectPassCollection, EffectAnnotationCollection.Empty);
            Techniques = new EffectTechniqueCollection(effectTechniqueArray);
            
            ConstantBuffers = new ConstantBuffer[0];            
            CurrentTechnique = Techniques[0];
        }
Пример #36
0
        private static EffectParameterCollection ReadParameters(BinaryReader reader)
        {
            var collection = new EffectParameterCollection();
            var count      = (int)reader.ReadByte();

            if (count == 0)
            {
                return(collection);
            }

            for (var i = 0; i < count; i++)
            {
                var class_      = (EffectParameterClass)reader.ReadByte();
                var type        = (EffectParameterType)reader.ReadByte();
                var name        = reader.ReadString();
                var semantic    = reader.ReadString();
                var annotations = ReadAnnotations(reader);
                var rowCount    = (int)reader.ReadByte();
                var columnCount = (int)reader.ReadByte();

                var elements      = ReadParameters(reader);
                var structMembers = ReadParameters(reader);

                object data = null;
                if (elements.Count == 0 && structMembers.Count == 0)
                {
                    switch (type)
                    {
                    case EffectParameterType.Bool:
                    case EffectParameterType.Int32:
#if DIRECTX
                        // Under DirectX we properly store integers and booleans
                        // in an integer type.
                        //
                        // MojoShader on the otherhand stores everything in float
                        // types which is why this code is disabled under OpenGL.
                    {
                        var buffer = new int[rowCount * columnCount];
                        for (var j = 0; j < buffer.Length; j++)
                        {
                            buffer[j] = reader.ReadInt32();
                        }
                        data = buffer;
                        break;
                    }
#endif

                    case EffectParameterType.Single:
                    {
                        var buffer = new float[rowCount * columnCount];
                        for (var j = 0; j < buffer.Length; j++)
                        {
                            buffer[j] = reader.ReadSingle();
                        }
                        data = buffer;
                        break;
                    }

                    case EffectParameterType.String:
                        throw new NotImplementedException();
                    }
                }
                var param = new EffectParameter(
                    class_, type, name, rowCount, columnCount, semantic,
                    annotations, elements, structMembers, data);

                collection.Add(param);
            }

            return(collection);
        }