示例#1
0
		/// <summary>
		/// Bitmaps to texture.
		/// </summary>
		/// <param name="bmp">The BMP.</param>
		/// <param name="texture">The texture.</param>
		public unsafe static void BitmapToTexture(Bitmap bitmap, Texture texture)
		{

			var bmp = bitmap.Clone(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.PixelFormat.Format32bppArgb);

			var bitmapData = bmp.LockBits(
				new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
				ImageLockMode.ReadOnly,
				bmp.PixelFormat);

			HardwarePixelBuffer buffer = texture.GetBuffer();
			buffer.Lock(Axiom.Graphics.BufferLocking.Discard);
			PixelBox pixelBox = buffer.CurrentLock;

			UInt32* texData = (UInt32*)pixelBox.Data;
			UInt32* mapData = (UInt32*)bitmapData.Scan0;

			var height = Math.Min(pixelBox.Height, bmp.Height);
			var width = Math.Min(pixelBox.Width, bmp.Width);

			for (var y = 0; y < height; ++y)
				for (var x = 0; x < width; ++x)
					texData[pixelBox.RowPitch * y + x] = mapData[bitmapData.Stride / 4 * y + x];

			buffer.Unlock();
			bmp.UnlockBits(bitmapData);

		}
示例#2
0
 /// <summary>
 /// Load an alternate image into the scene for the given texture name.
 /// Future movies that play should look for this texture and unload it
 /// if it exists.
 /// </summary>
 /// <param name="name">
 /// The name of the texture to replace.
 /// </param>
 /// <param name="file">
 /// The name of the file in the Textures directory to display.
 /// </param>
 /// <returns>
 /// True if the texture was created, false if it wasn't.
 /// </returns>
 public static bool ShowAltImage(string name, string file)
 {
     Axiom.Core.Texture texture = TextureManager.Instance.GetByName(name);
     if (texture != null)
     {
         if (texture.IsLoaded)
         {
             texture.Unload();
         }
         TextureManager.Instance.Remove(name);
     }
     try
     {
         Axiom.Media.Image img = Axiom.Media.Image.FromFile(file);
         if (img != null)
         {
             texture = TextureManager.Instance.LoadImage(name, img);
             return(texture != null);
         }
     }
     catch (Exception e)
     {
         LogUtil.ExceptionLog.ErrorFormat("Exception: {0}", e);
         return(false);
     }
     return(false);
 }
		/// <summary>
		/// 
		/// </summary>
		protected override void SetupContent()
		{
			this.ptex = TextureManager.Instance.CreateManual( "DynaTex", ResourceGroupManager.DefaultResourceGroupName,
			                                                  TextureType.ThreeD, 64, 64, 64, 0, Media.PixelFormat.A8R8G8B8,
			                                                  TextureUsage.Default, null );

			SceneManager.AmbientLight = new ColorEx( 0.6f, 0.6f, 0.6f );
			SceneManager.SetSkyBox( true, "Examples/MorningSkyBox", 50 );

			Light light = SceneManager.CreateLight( "VolumeTextureSampleLight" );
			light.Diffuse = new ColorEx( 0.75f, 0.75f, 0.80f );
			light.Specular = new ColorEx( 0.9f, 0.9f, 1 );
			light.Position = new Vector3( -100, 80, 50 );
			SceneManager.RootSceneNode.AttachObject( light );

			// Create volume renderable
			this.snode = SceneManager.RootSceneNode.CreateChildSceneNode( Vector3.Zero );

			this.vrend = new VolumeRendable( 32, 750, "DynaTex" );
			this.snode.AttachObject( this.vrend );

			this.trend = new ThingRendable( 90, 32, 7.5f );
			this.trend.Material = (Material)MaterialManager.Instance.GetByName( "Examples/VTDarkStuff" );
			this.trend.Material.Load();
			this.snode.AttachObject( this.trend );

			this.fnode = SceneManager.RootSceneNode.CreateChildSceneNode();
			Entity head = SceneManager.CreateEntity( "head", "ogrehead.mesh" );
			this.fnode.AttachObject( head );

			Animation anim = SceneManager.CreateAnimation( "OgreTrack", 10 );
			anim.InterpolationMode = InterpolationMode.Spline;

			NodeAnimationTrack track = anim.CreateNodeTrack( 0, this.fnode );
			TransformKeyFrame key = track.CreateNodeKeyFrame( 0 );
			key.Translate = new Vector3( 0, -15, 0 );
			key = track.CreateNodeKeyFrame( 5 );
			key.Translate = new Vector3( 0, 15, 0 );
			key = track.CreateNodeKeyFrame( 10 );
			key.Translate = new Vector3( 0, -15, 0 );
			this.animState = SceneManager.CreateAnimationState( "OgreTrack" );
			this.animState.IsEnabled = true;

			this.globalReal = 0.4f;
			this.globalImag = 0.6f;
			this.globalTheta = 0.0f;

			CreateControls();

			DragLook = true;

			Generate();
		}
示例#4
0
 public Movie()
 {
     id = Manager.GetNewIdentifier();
     name = null;
     path = null;
     textureName = null;
     texture = null;
     videoSize = Size.Empty;
     textureSize = Size.Empty;
     ps = PLAY_STATE.INIT;
     altImage = null;
     altImageShown = false;
 }
示例#5
0
 public static bool HideAltImage(string name)
 {
     Axiom.Core.Texture texture = TextureManager.Instance.GetByName(name);
     if (texture != null)
     {
         if (texture.IsLoaded)
         {
             texture.Unload();
         }
         TextureManager.Instance.Remove(name);
         return(true);
     }
     return(false);
 }
示例#6
0
        private void SaveToDisk( Texture tp, string filename )
        {
          // Declare buffer
            int buffSize = tp.Width * tp.Height * tp.Depth * 4;
            byte[] data = new byte[buffSize];
          

          // Setup Image with correct settings
          Image i = new Image();
          i.FromDynamicImage(data, tp.Width, tp.Height, tp.Depth,tp.Format);
          
          // Copy Texture buffer contents to image buffer
          HardwarePixelBuffer buf = tp.GetBuffer();      
          PixelBox destBox = i.GetPixelBox(0,0);
          buf.BlitToMemory(destBox);
          
          // Save to disk!
          i.Save( @"C:\" + filename );
        }
示例#7
0
        public override void CreateScene()
        {
            RenderSystemCapabilities caps = Root.Instance.RenderSystem.HardwareCapabilities;
            if ( !caps.HasCapability( Capabilities.Texture3D ) )
            {
                throw new NotSupportedException( "Your card does not support 3d textures, so you can not run this Demo. Sorry!" );
            }
            mPTex = TextureManager.Instance.CreateManual( "DynaTex", "General", TextureType.ThreeD, 64, 64, 64, 0, PixelFormat.A8R8G8B8, TextureUsage.Default, this );
            Generate();
            //SaveToDisk( mPTex, "julia.dds" );
            scene.AmbientLight = new ColorEx( 0.6f, 0.6f, 0.6f );
            scene.SetSkyBox( true, "Examples/MorningSkyBox", 50 );

            Light l = scene.CreateLight( "MainLight" );
            l.Diffuse = new ColorEx( 0.75f, 0.75f, 0.80f );
            l.Specular = new ColorEx( 0.9f, 0.9f, 1 );
            l.Position = new Vector3( -100, 80, 50 );
            scene.RootSceneNode.AttachObject( l );
            SceneNode snode = scene.RootSceneNode.CreateChildSceneNode( Vector3.Zero );
            VolumeRenderable vrend = new VolumeRenderable( 32, 750f, "VolumeTexture.dds" );
            snode.AttachObject( vrend );
            camera.LookAt( snode.Position );
        }
示例#8
0
        //Was used to generate mipmaps, which is no longer supported for non-RenderTarget textures.
        //private XFG.TextureFilter GetBestFilterMethod()
        //{
        //    // those MUST be initialized !!!
        //    Debug.Assert( _device != null );
        //    Debug.Assert( _texture != null );

        //    XFG.GraphicsDeviceCapabilities.FilterCaps filterCaps;
        //    // Minification filter is used for mipmap generation
        //    // Pick the best one supported for this tex type
        //    switch ( this.TextureType )
        //    {
        //        case TextureType.OneD: // Same as 2D
        //        case TextureType.TwoD:
        //            filterCaps = _devCaps.TextureFilterCapabilities;
        //            break;
        //        case TextureType.ThreeD:
        //            filterCaps = _devCaps.VertexTextureFilterCapabilities;
        //            break;
        //        case TextureType.CubeMap:
        //            filterCaps = _devCaps.CubeTextureFilterCapabilities;
        //            break;
        //        default:
        //            return XFG.TextureFilter.Point;
        //    }
        //    if ( filterCaps.SupportsMinifyGaussianQuad )
        //        return XFG.TextureFilter.GaussianQuad;
        //    if ( filterCaps.SupportsMinifyPyramidalQuad )
        //        return XFG.TextureFilter.PyramidalQuad;
        //    if ( filterCaps.SupportsMinifyAnisotropic )
        //        return XFG.TextureFilter.Anisotropic;
        //    if ( filterCaps.SupportsMinifyLinear )
        //        return XFG.TextureFilter.Linear;
        //    if ( filterCaps.SupportsMinifyPoint )
        //        return XFG.TextureFilter.Point;
        //    return XFG.TextureFilter.Point;
        //}

        /// <summary>
        ///
        /// </summary>
        /// <param name="usage"></param>
        /// <param name="type"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        //private bool CanAutoGenMipMaps( XFG.TextureUsage srcUsage, XFG.ResourceType srcType, XFG.SurfaceFormat srcFormat )
        //{
        //    Debug.Assert( _device != null );
        //    if ( _device.GraphicsDeviceCapabilities.DriverCapabilities.CanAutoGenerateMipMap )
        //    {
        //        // make sure we can do it!
        //        return _device.CreationParameters.Adapter.CheckDeviceFormat( XFG.DeviceType.Hardware,
        //            _device.CreationParameters.Adapter.CurrentDisplayMode.Format, //rahhh
        //             Microsoft.Xna.Framework.Graphics.TextureUsage.AutoGenerateMipMap,
        //              Microsoft.Xna.Framework.Graphics.QueryUsages.None,
        //               srcType, srcFormat );
        //    }
        //    return false;
        //}

        public void CopyToTexture(Texture target)
        {
            //not tested for rendertargetCube yet
            //texture.texture.Save("test.jpg", XFG.ImageFileFormat.Dds);
            var texture = (XnaTexture)target;

            if (target.TextureType == TextureType.TwoD)
            {
                _device.SetRenderTarget(null);
                _normTexture     = (renderTarget);
                texture._texture = _normTexture;
            }
            else if (target.TextureType == TextureType.CubeMap)
            {
                /* Alright RenderTarget2D inheritence path: Texture-Texture2D->RenderTarget2D
                 * ......RenderTargetCube inheritance path: Texture-TextureCube->RenderTargetCube
                 * ??
                 */
                //not sure if this much (un)boxing will work, but we didn't even use this in Xna 3.1 anyway,
                //I'm going to let it slide for now -DoubleA
                texture._cubeTexture = ((Microsoft.Xna.Framework.Graphics.Texture)renderTarget) as TextureCube;
                texture._texture     = _cubeTexture;
            }
        }
示例#9
0
        public override void SetVertexTexture( int stage, Texture texture )
        {
            if ( texture == null )
            {
                if ( _texStageDesc[ stage ].vertexTex != null )
                {
                    var result = ActiveD3D9Device.SetTexture( ( (int)VertexTextureSampler.Sampler0 ) + stage, null );
                    if ( result.IsFailure )
                    {
                        throw new AxiomException( "Unable to disable vertex texture '{0}' in D3D9.", stage );
                    }
                }
                _texStageDesc[ stage ].vertexTex = null;
            }
            else
            {
                var dt = (D3DTexture)texture;
                // note used
                dt.Touch();

                var ptex = dt.DXTexture;

                if ( _texStageDesc[ stage ].vertexTex != ptex )
                {
                    var result = ActiveD3D9Device.SetTexture(((int)VertexTextureSampler.Sampler0) + stage, ptex);
                    if ( result.IsFailure )
                    {
                        throw new AxiomException("Unable to set vertex texture '{0}' in D3D9.", dt.Name);
                    }
                }
                _texStageDesc[ stage ].vertexTex = ptex;
            }
        }
示例#10
0
		//Was used to generate mipmaps, which is no longer supported for non-RenderTarget textures.
		//private XFG.TextureFilter GetBestFilterMethod()
		//{
		//    // those MUST be initialized !!!
		//    Debug.Assert( _device != null );
		//    Debug.Assert( _texture != null );

		//    XFG.GraphicsDeviceCapabilities.FilterCaps filterCaps;
		//    // Minification filter is used for mipmap generation
		//    // Pick the best one supported for this tex type
		//    switch ( this.TextureType )
		//    {
		//        case TextureType.OneD: // Same as 2D
		//        case TextureType.TwoD:
		//            filterCaps = _devCaps.TextureFilterCapabilities;
		//            break;
		//        case TextureType.ThreeD:
		//            filterCaps = _devCaps.VertexTextureFilterCapabilities;
		//            break;
		//        case TextureType.CubeMap:
		//            filterCaps = _devCaps.CubeTextureFilterCapabilities;
		//            break;
		//        default:
		//            return XFG.TextureFilter.Point;
		//    }
		//    if ( filterCaps.SupportsMinifyGaussianQuad )
		//        return XFG.TextureFilter.GaussianQuad;
		//    if ( filterCaps.SupportsMinifyPyramidalQuad )
		//        return XFG.TextureFilter.PyramidalQuad;
		//    if ( filterCaps.SupportsMinifyAnisotropic )
		//        return XFG.TextureFilter.Anisotropic;
		//    if ( filterCaps.SupportsMinifyLinear )
		//        return XFG.TextureFilter.Linear;
		//    if ( filterCaps.SupportsMinifyPoint )
		//        return XFG.TextureFilter.Point;
		//    return XFG.TextureFilter.Point;
		//}

		/// <summary>
		///
		/// </summary>
		/// <param name="usage"></param>
		/// <param name="type"></param>
		/// <param name="format"></param>
		/// <returns></returns>
		//private bool CanAutoGenMipMaps( XFG.TextureUsage srcUsage, XFG.ResourceType srcType, XFG.SurfaceFormat srcFormat )
		//{
		//    Debug.Assert( _device != null );
		//    if ( _device.GraphicsDeviceCapabilities.DriverCapabilities.CanAutoGenerateMipMap )
		//    {
		//        // make sure we can do it!
		//        return _device.CreationParameters.Adapter.CheckDeviceFormat( XFG.DeviceType.Hardware,
		//            _device.CreationParameters.Adapter.CurrentDisplayMode.Format, //rahhh
		//             Microsoft.Xna.Framework.Graphics.TextureUsage.AutoGenerateMipMap,
		//              Microsoft.Xna.Framework.Graphics.QueryUsages.None,
		//               srcType, srcFormat );
		//    }
		//    return false;
		//}

		public void CopyToTexture( Texture target )
		{
			//not tested for rendertargetCube yet
			//texture.texture.Save("test.jpg", XFG.ImageFileFormat.Dds);
			var texture = (XnaTexture)target;

			if ( target.TextureType == TextureType.TwoD )
			{
				_device.SetRenderTarget( null );
				_normTexture = ( renderTarget );
				texture._texture = _normTexture;
			}
			else if ( target.TextureType == TextureType.CubeMap )
			{
				/* Alright RenderTarget2D inheritence path: Texture-Texture2D->RenderTarget2D
				 * ......RenderTargetCube inheritance path: Texture-TextureCube->RenderTargetCube
				 * ??
				 */
				//not sure if this much (un)boxing will work, but we didn't even use this in Xna 3.1 anyway,
				//I'm going to let it slide for now -DoubleA
				texture._cubeTexture = ( (Microsoft.Xna.Framework.Graphics.Texture)renderTarget ) as TextureCube;
				texture._texture = _cubeTexture;
			}
		}
示例#11
0
        public override void SetTexture( int stage, bool enabled, Texture texture )
        {
            var dxTexture = (D3DTexture)texture;

            if ( enabled && dxTexture != null )
            {
                // note used
                dxTexture.Touch();

                var ptex = dxTexture.DXTexture;
                if ( _texStageDesc[ stage ].tex != ptex )
                {
                    ActiveD3D9Device.SetTexture( stage, ptex );

                    // set stage description
                    _texStageDesc[ stage ].tex = ptex;
                    _texStageDesc[ stage ].texType = D3DHelper.ConvertEnum( dxTexture.TextureType );
                }
                SetSamplerState( GetSamplerId( stage ), SamplerState.SrgbTexture, dxTexture.HardwareGammaEnabled );
            }
            else
            {
                if ( _texStageDesc[ stage ].tex != null )
                {
                    ActiveD3D9Device.SetTexture(stage, null);
                }

                
                SetTextureStageState( stage, TextureStage.ColorOperation, TextureOperation.Disable );

                // set stage description to defaults
                _texStageDesc[ stage ].tex = null;
                _texStageDesc[ stage ].autoTexCoordType = TexCoordCalcMethod.None;
                _texStageDesc[ stage ].coordIndex = 0;
                _texStageDesc[ stage ].texType = D3DTextureType.Normal;
            }
        }
示例#12
0
		public override void CreateScene()
		{
			// Create dynamic texture
			ptex = TextureManager.Instance.CreateManual( "DynaTex", ResourceGroupManager.DefaultResourceGroupName, TextureType.TwoD, reactorExtent - 2, reactorExtent - 2, 0, PixelFormat.A8R8G8B8, TextureUsage.DynamicWriteOnly );
			buffer = ptex.GetBuffer( 0, 0 );

			// Set ambient light
			scene.AmbientLight = new ColorEx( 0.6F, 0.6F, 0.6F );
			scene.SetSkyBox( true, "SkyBox/Space", 50 );

			//mRoot->getRenderSystem()->clearFrameBuffer(FBT_COLOUR, ColourValue(255,255,255,0));

			// Create a light
			Light l = scene.CreateLight( "MainLight" );
			l.Diffuse = new ColorEx( 0.75F, 0.75F, 0.80F );
			l.Specular = new ColorEx( 0.9F, 0.9F, 1F );
			l.Position = new Vector3( -100, 80, 50 );
			scene.RootSceneNode.AttachObject( l );


			Entity planeEnt = scene.CreateEntity( "TexPlane1", PrefabEntity.Plane );
			// Give the plane a texture
			planeEnt.MaterialName = "Examples/DynaTest";

			SceneNode node = scene.RootSceneNode.CreateChildSceneNode( new Vector3( -100, -40, -100 ) );
			node.AttachObject( planeEnt );
			node.Scale = new Vector3( 3.0f, 3.0f, 3.0f );

			// Create objects
			SceneNode blaNode = scene.RootSceneNode.CreateChildSceneNode( new Vector3( -200, 0, 50 ) );
			Entity ent2 = scene.CreateEntity( "knot", "knot.mesh" );
			ent2.MaterialName = "Examples/DynaTest4";
			blaNode.AttachObject( ent2 );

			blaNode = scene.RootSceneNode.CreateChildSceneNode( new Vector3( 200, -90, 50 ) );
			ent2 = scene.CreateEntity( "knot2", "knot.mesh" );
			ent2.MaterialName = "Examples/DynaTest2";
			blaNode.AttachObject( ent2 );
			blaNode = scene.RootSceneNode.CreateChildSceneNode( new Vector3( -110, 200, 50 ) );

			// Cloaked fish
			ent2 = scene.CreateEntity( "knot3", "fish.mesh" );
			ent2.MaterialName = "Examples/DynaTest3";
			swim = ent2.GetAnimationState( "swim" );
			swim.IsEnabled = true;
			blaNode.AttachObject( ent2 );
			blaNode.Scale = new Vector3( 50.0f, 50.0f, 50.0f );

			LogManager.Instance.Write( "HardwarePixelBuffer {0} {1} {2} ", buffer.Width, buffer.Height, buffer.Depth );

			buffer.Lock( BufferLocking.Normal );
			PixelBox pb = buffer.CurrentLock;

			LogManager.Instance.Write( "PixelBox {0} {1} {2} {3} {4} {5} {6}", pb.Width, pb.Height, pb.Depth, pb.RowPitch, pb.SlicePitch, pb.Data, pb.Format );
			buffer.Unlock();

			// show GUI
			overlay = OverlayManager.Instance.GetByName( "Example/DynTexOverlay" );
			overlay.Show();
		}
        private void UpdateMaterialBrush()
        {
            // build the brush texture with a 1 pixel wide border around it so that
            // we can use texture address clamping to constrain the texture to just
            // the brush area.
            byte[] tmpBrush = new byte[32 * 32];
            //byte[] tmpBrush = new byte[( brushWidth + 2 ) * ( brushWidth + 2 )];

            for (int z = 0; z < brushWidth; z++)
            {
                for (int x = 0; x < brushWidth; x++)
                {
                    tmpBrush[x + 1 + ( ( z + 1 ) * 32 )] = (byte)Math.Round(brush[x,z] * taper[x,z] * 255f);
                }
            }

            Image brushImg = Image.FromDynamicImage(tmpBrush, 32, 32, PixelFormat.A8);

            if (brushTexture != null)
            {
                brushTexture.Dispose();
            }
            brushTexture = TextureManager.Instance.LoadImage("HEDBrushTexture", brushImg);
            material.GetTechnique(0).GetPass(1).GetTextureUnitState(1).SetTextureName("HEDBrushTexture");
        }
        public int InitializeDevice(IntPtr dwUserID, ref VMR9AllocationInfo lpAllocInfo, ref int lpNumBuffers)
        {
            lock (this)
            {
                log.InfoFormat("DirectShowCodec[{0}]: {1}x{2} : {3} / {4} / {5} / {6} / 0x{7:x}", ID,
                               lpAllocInfo.dwWidth, lpAllocInfo.dwHeight,
                               FourCCToStr(lpAllocInfo.Format),
                               adapterInfo.CurrentDisplayMode.Format,
                               lpAllocInfo.MinBuffers,
                               (Pool)lpAllocInfo.Pool,
                               lpAllocInfo.dwFlags);

                Axiom.Media.PixelFormat texFormat = D3DHelper.ConvertEnum(adapterInfo.CurrentDisplayMode.Format);
                Format format = (Format)lpAllocInfo.Format;

                // if format is YUV ? (note : 0x30303030 = "    ")
                if (lpAllocInfo.Format > 0x30303030)
                {
                    // NV12 textures appear not to play correctly; when using them with an
                    // offscreen surface, they only show the first frame or so.  Doing this
                    // should cause it to renegotiate to RGB.
                    //
                    // New and improved: YV12 seems to have the same problem.
                    if (
                        (lpAllocInfo.Format == StrToFourCC("NV12")) ||
                        (lpAllocInfo.Format == StrToFourCC("YV12"))
                        )
                    {
                        // XXXMLM - this may cause us to pop an external window
                        log.WarnFormat("DirectShowCodec[{0}]: Rejecting {1} format", ID, FourCCToStr(lpAllocInfo.Format));
                        return D3DERR_INVALIDCALL;
                    }

                    // Check if the hardware support format conversion from this YUV format to the RGB desktop format
                    if (!D3D.Manager.CheckDeviceFormatConversion(creationParameters.AdapterOrdinal, creationParameters.DeviceType,
                        (Format)lpAllocInfo.Format, adapterInfo.CurrentDisplayMode.Format))
                    {
                        // If not, refuse this format!
                        // The VMR9 will propose other formats supported by the downstream filter output pin.
                        log.WarnFormat("DirectShowCodec[{0}]: Cannot convert between formats", ID);
                        return D3DERR_INVALIDCALL;
                    }
                }
                try
                {
                    IDirect3DDevice9* unmanagedDevice = device.UnmanagedComPointer;
                    IntPtr hMonitor = D3D.Manager.GetAdapterMonitor(adapterInfo.Adapter);

                    // Give our Direct3D device to the VMR9 filter
                    try
                    {
                        IVMRSurfaceAllocatorNotify9 notify9 = vmrSurfaceAllocatorNotify;
                        vmrSurfaceAllocatorNotify.SetD3DDevice((IntPtr)unmanagedDevice, hMonitor);
                    }
                    catch (InvalidCastException e)
                    {
                        // It turns out that if this function is called from the
                        // decoder thread, the hr return value of the SetD3DDevice
                        // call will be E_INVALIDCAST.  However, if we've already
                        // notified the allocator notify interface of the device,
                        // the rest of this function will happen correctly.  So
                        // only throw the exception if we haven't notified the
                        // device yet.
                        if ((IntPtr)unmanagedDevice != notifiedDevice)
                        {
                            throw e;
                        }
                    }
                    notifiedDevice = (IntPtr)unmanagedDevice;

                    videoSize = new Size(lpAllocInfo.dwWidth, lpAllocInfo.dwHeight);
                    videoRectangle = new Rectangle(Point.Empty, videoSize);

                    // Always do power of two sized textures
                    lpAllocInfo.dwWidth = Manager.NextPowerOfTwo(lpAllocInfo.dwWidth);
                    lpAllocInfo.dwHeight = Manager.NextPowerOfTwo(lpAllocInfo.dwHeight);

                    textureSize = new Size(lpAllocInfo.dwWidth, lpAllocInfo.dwHeight);

                    // Just in case
                    DeleteSurfaces();

                    // if format is YUV ?
                    if (lpAllocInfo.Format > 0x30303030)
                    {
                        log.InfoFormat("DirectShowCodec[{0}]: Creating offscreen surface ({1}x{2})",
                                       ID, lpAllocInfo.dwWidth, lpAllocInfo.dwHeight);

                        // An offscreen surface must be created
                        lpAllocInfo.dwFlags |= VMR9SurfaceAllocationFlags.OffscreenSurface;

                        // Create it
                        try
                        {
                            // ATI and nVidia both fail this call when created with YUV, so ask for
                            // an RGB texture first if we can get away with it.
                            if ((lpAllocInfo.dwFlags & VMR9SurfaceAllocationFlags.RGBDynamicSwitch) != 0)
                            {
                                videoSurface = device.CreateOffscreenPlainSurface(lpAllocInfo.dwWidth, lpAllocInfo.dwHeight,
                                    adapterInfo.CurrentDisplayMode.Format, (Pool)lpAllocInfo.Pool);
                            }
                            else
                            {
                                videoSurface = device.CreateOffscreenPlainSurface(lpAllocInfo.dwWidth, lpAllocInfo.dwHeight,
                                    (Format)lpAllocInfo.Format, (Pool)lpAllocInfo.Pool);
                            }
                        }
                        catch
                        {
                            log.WarnFormat("Failed to create {0} surface", (Format)lpAllocInfo.Format);
                            return D3DERR_INVALIDCALL;
                        }
                        // And get it unmanaged pointer
                        unmanagedSurface = videoSurface.UnmanagedComPointer;

                        axiomTexture = TextureManager.Instance.GetByName(textureName);
                        if (axiomTexture != null)
                        {
                            log.InfoFormat("DirectShowCodec[{0}]: Removing old texture \"{1}\"",
                                ID, textureName);
                            axiomTexture.Unload();

                            axiomTexture.TextureType = TextureType.TwoD;
                            axiomTexture.Width = lpAllocInfo.dwWidth;
                            axiomTexture.Height = lpAllocInfo.dwHeight;
                            axiomTexture.NumMipMaps = 0;
                            axiomTexture.Format = texFormat;
                            axiomTexture.Usage = TextureUsage.RenderTarget;
                            axiomTexture.CreateInternalResources();
                        }
                        else
                        {
                            axiomTexture = TextureManager.Instance.CreateManual(
                                textureName,
                                TextureType.TwoD,
                                lpAllocInfo.dwWidth, lpAllocInfo.dwHeight,
                                0, // no mip maps
                                texFormat, // from the display
                                TextureUsage.RenderTarget);
                        }
                        if (axiomTexture is D3DTexture)
                        {
                            D3DTexture d3t = (D3DTexture)axiomTexture;
                            if (d3t.DXTexture is D3D.Texture)
                            {
                                privateTexture = (D3D.Texture)d3t.DXTexture;
                            }
                            else
                            {
                                throw new Exception("D3D texture could not get DX texture");
                            }
                        }
                        else
                        {
                            throw new Exception("D3D Texture failed to create");
                        }

                        // Get the MipMap surface 0 for the copy (see PresentImage)
                        privateSurface = privateTexture.GetSurfaceLevel(0);
                        device.ColorFill(privateSurface, new Rectangle(0, 0, lpAllocInfo.dwWidth, lpAllocInfo.dwHeight), Color.Black);

                        // This code path need a surface copy
                        needCopy = true;
                    }
                    else
                    {
                        log.InfoFormat("DirectShowCodec[{0}]: Creating texture surface ({1}x{2})",
                                       ID, lpAllocInfo.dwWidth, lpAllocInfo.dwHeight);

                        // in RGB pixel format
                        //lpAllocInfo.dwFlags |= VMR9SurfaceAllocationFlags.TextureSurface;

                        //Surface s = device.CreateRenderTarget();

                        axiomTexture = TextureManager.Instance.GetByName(textureName);
                        if (axiomTexture != null)
                        {
                            log.InfoFormat("DirectShowCodec[{0}]: Removing old texture \"{1}\"",
                                ID, textureName);
                            axiomTexture.Unload();

                            axiomTexture.TextureType = TextureType.TwoD;
                            axiomTexture.Width = lpAllocInfo.dwWidth;
                            axiomTexture.Height = lpAllocInfo.dwHeight;
                            axiomTexture.NumMipMaps = 0;
                            axiomTexture.Format = texFormat;
                            axiomTexture.Usage = TextureUsage.RenderTarget;
                            axiomTexture.CreateInternalResources();
                        }
                        else
                        {
                            axiomTexture = TextureManager.Instance.CreateManual(
                                textureName,
                                TextureType.TwoD,
                                lpAllocInfo.dwWidth, lpAllocInfo.dwHeight,
                                0, // no mip maps
                                texFormat, // from the display
                                TextureUsage.RenderTarget);
                        }
                        if (axiomTexture is D3DTexture)
                        {
                            D3DTexture d3t = (D3DTexture)axiomTexture;
                            if (d3t.DXTexture is D3D.Texture)
                            {
                                privateTexture = (D3D.Texture)d3t.DXTexture;
                            }
                        }
                        else
                        {
                            throw new Exception("D3D Texture failed to create");
                        }

                        // And get the MipMap surface 0 for the VMR9 filter
                        privateSurface = privateTexture.GetSurfaceLevel(0);
                        unmanagedSurface = privateSurface.UnmanagedComPointer;
                        device.ColorFill(privateSurface, new Rectangle(0, 0, lpAllocInfo.dwWidth, lpAllocInfo.dwHeight), Color.Black);

                        // This code path don't need a surface copy.
                        // The client appllication use the same texture the VMR9 filter use.
                        needCopy = false;
                    }

                    // This allocator only support 1 buffer.
                    // Notify the VMR9 filter
                    lpNumBuffers = 1;
                }

                catch (DirectXException e)
                {
                    // A Direct3D error can occure : Notify it to the VMR9 filter
                    LogUtil.ExceptionLog.ErrorFormat("Caught DirectX Exception: {0}", e.ToString());
                    return e.ErrorCode;
                }
                catch (Exception e)
                {
                    // Or else, notify a more general error
                    LogUtil.ExceptionLog.ErrorFormat("Caught Exception: {0}", e.ToString());
                    return E_FAIL;
                }

                // This allocation is a success
                return 0;
            }
        }
示例#15
0
		protected override void unload()
		{
			if ( this._material != null )
			{
				MaterialManager.Instance.Remove( this._material );
				this._material.Unload();
				this._material = null;
			}

			if ( this._texture != null )
			{
				TextureManager.Instance.Remove( this._texture );
				this._texture.Unload();
				this._texture = null;
			}
		}
 /// <summary>
 ///   Set up a texture and region that will be used for the hardware cursor.
 /// </summary>
 /// <param name="texture"></param>
 /// <param name="section"></param>
 public void SetCursor(Texture texture, System.Drawing.Rectangle section)
 {
     SetCursor(texture, section, new System.Drawing.Point(0, 0));
 }
 /// <summary>
 ///   Set up a texture and region that will be used for the hardware cursor.
 /// </summary>
 /// <param name="texture"></param>
 /// <param name="section"></param>
 /// <param name="hotSpot"></param>
 public abstract void SetCursor(Texture texture, System.Drawing.Rectangle section, System.Drawing.Point hotSpot);
示例#18
0
		/// <summary>
		/// Set the texture pointer for a given frame (internal use only!).
		/// </summary>
		internal void SetTexture( Texture texptr, int frame )
		{
			throw new System.NotImplementedException();
			//assert( frame < mFramePtrs.size() );
			//mFramePtrs[ frame ] = texptr;
		}
示例#19
0
		public override void SetTexture( int stage, bool enabled, Texture texture )
		{
			var glTexture = (GLTexture)texture;
			var lastTextureType = textureTypes[ stage ];

            if (!ActivateGLTextureUnit(stage))
                return;

			// enable and bind the texture if necessary
			if ( enabled )
			{
				if ( glTexture != null )
				{
					textureTypes[ stage ] = glTexture.GLTextureType;
				}
				else
				{
					// assume 2D
					textureTypes[ stage ] = Gl.GL_TEXTURE_2D;
				}

				if ( lastTextureType != textureTypes[ stage ] && lastTextureType != 0 )
				{
					if ( stage < _fixedFunctionTextureUnits )
					{
						Gl.glDisable( lastTextureType );
					}
				}

				if ( stage < _fixedFunctionTextureUnits )
				{
					Gl.glEnable( textureTypes[ stage ] );
				}

				if ( glTexture != null )
				{
					Gl.glBindTexture( textureTypes[ stage ], glTexture.TextureID );
				}
				else
				{
					Gl.glBindTexture( textureTypes[ stage ], ( (GLTextureManager)textureManager ).WarningTextureId );
				}
			}
			else
			{
				if ( stage < _fixedFunctionTextureUnits )
				{
					if ( lastTextureType != 0 )
					{
						Gl.glDisable( textureTypes[ stage ] );
					}
					Gl.glTexEnvf( Gl.GL_TEXTURE_ENV, Gl.GL_TEXTURE_ENV_MODE, Gl.GL_MODULATE );
				}

                // bind zero texture
                Gl.glBindTexture(Gl.GL_TEXTURE_2D, 0); 
			}
			ActivateGLTextureUnit( 0 );
		}
示例#20
0
		/*
		 * System::Void JointPositionOverlay::copyBitmapToTexture()
{
  // Lock the texture buffer so we can write to it

  Ogre::HardwarePixelBufferSharedPtr buffer = mTexture->getBuffer ();
  buffer->lock(Ogre::HardwareBuffer::HBL_DISCARD);
  const Ogre::PixelBox &pb = buffer->getCurrentLock();
  Ogre::uint32 *texData = static_cast<Ogre::uint32*>(pb.data);


  // Lock the bitmap buffer so we can read from it

  System::Drawing::Imaging::BitmapData^ bmd = 
    mBitmap->LockBits(
      System::Drawing::Rectangle(0, 0, mBitmap->Width, mBitmap->Height),
      System::Drawing::Imaging::ImageLockMode::ReadOnly, 
      System::Drawing::Imaging::PixelFormat::Format32bppArgb);
  Ogre::uint32* mapData = static_cast<Ogre::uint32*>(bmd->Scan0.ToPointer());


  // Now copy the data between buffers

  size_t height = std::min (pb.getHeight(), (size_t)bmd->Height);
  size_t width = std::min(pb.getWidth(), (size_t)bmd->Width);
  for(size_t y=0; y<height; ++y) 
    for(size_t x=0; x<width; ++x) 
      texData[pb.rowPitch*y + x] = mapData[bmd->Stride/4 * y + x];


  // Unlock the buffers again

  mBitmap->UnlockBits(bmd);
  buffer->unlock();
}
		 * 
		 * 
		 * 
		 */

		/// <summary>
		/// Creates the dynamic texture and material.
		/// </summary>
		/// <param name="TextureName">Name of the texture.</param>
		/// <param name="MaterialName">Name of the material.</param>
		/// <param name="textureHeight">Height of the texture.</param>
		/// <param name="textureWidth">Width of the texture.</param>
		/// <param name="texture">The texture.</param>
		/// <param name="material">The material.</param>
		public static void CreateDynamicTextureAndMaterial(string TextureName, string MaterialName, int textureWidth, int textureHeight, out Texture texture, out Material material)
		{
			texture = TextureManager.Instance.CreateManual(TextureName,
						ResourceGroupManager.DefaultResourceGroupName,
						TextureType.TwoD, textureWidth, textureHeight, 0,
						Axiom.Media.PixelFormat.A8R8G8B8, TextureUsage.DynamicWriteOnlyDiscardable);


			material = (Material)MaterialManager.Instance.Create(MaterialName,
						ResourceGroupManager.DefaultResourceGroupName);

			material.GetTechnique(0).GetPass(0).CreateTextureUnitState(TextureName);


		}
 /// <summary>
 ///		Sets the texture for the current frame (internal use only!).
 /// </summary>
 public void SetTexturePtr(Texture tex)
 {
     SetTexturePtr(tex, currentFrame);
 }
 /// <summary>
 ///		Sets the texture pointer for a given frame (internal use only!).
 /// </summary>
 public void SetTexturePtr(Texture tex, int frame)
 {
     Debug.Assert(frame < numFrames);
     frameTextures[frame] = tex;
 }
        public void Initialize(Window window)
        {
            m_window = window;

            InitializeOculus();

            InitializeGloves();

            // Create the root object
            m_root = new Root("GlovesLog.log");

            // Configure the render system
            SetRenderingSystem();

            // Create render window
            m_renderWindow = m_root.Initialize(true);

            // Loads the resources
            ResourceGroupManager.Instance.AddResourceLocation("media", "Folder", true);
            ResourceGroupManager.Instance.InitializeAllResourceGroups();

            // Create the screen manager
            m_sceneManager = m_root.CreateSceneManager(SceneType.Generic);

            InitializeCameras();

            InitializeViewports();

            InitializeLight();

            // Create material to render ClEye camera input
            m_axiomMaterial = MaterialManager.Instance.Create("dynamicResource", "Materials") as Material;

            // Create texture to render the CLEye camera input to
            m_texture = TextureManager.Instance.CreateManual("DynamicTexture",
                                                             ResourceGroupManager.DefaultResourceGroupName,
                                                             TextureType.TwoD, 640, 480, 2, PixelFormat.R8G8B8,
                                                             TextureUsage.RenderTarget);

            // Set the cameras in the scene
            SceneNode cameraNode = m_sceneManager.RootSceneNode.CreateChildSceneNode("CameraNode", new Vector3(0, 0, 0));

            cameraNode.AttachObject(m_camera[0]);
            cameraNode.AttachObject(m_camera[1]);

            InitializeEntities();

            // Initialize the material that will draw the camera input
            m_axiomMaterial.GetTechnique(0).GetPass(0).CreateTextureUnitState("DynamicTexture");
            m_axiomMaterial.GetTechnique(0).GetPass(0).DepthCheck      = false;
            m_axiomMaterial.GetTechnique(0).GetPass(0).DepthWrite      = false;
            m_axiomMaterial.GetTechnique(0).GetPass(0).LightingEnabled = false;

            // Initialize the rectangle input onto which the camera input will be rendered
            m_rect = new Rectangle2D(true);
            //m_rect.SetCorners(-1.15f, 1.0f, 1.15f, -1.0f);
            m_rect.SetCorners(-0.85f, 0.7f, 0.85f, -0.7f);
            m_rect.Material         = m_axiomMaterial;
            m_rect.RenderQueueGroup = RenderQueueGroupID.Background;
            SceneNode node = m_sceneManager.RootSceneNode.CreateChildSceneNode("Background");

            node.AttachObject(m_rect);

            // Set the function to the FrameStarted event
            m_root.FrameStarted += FrameStarted;

            InitializeCLEyeCameras();

            // Not recording
            m_record = false;

            // Not loading from file
            m_renderFromFile = false;

            // Initialize the gloves capture  string arrays
            m_gloveCaptureL    = new string[30];
            m_gloveCaptureL[0] = "Left Glove Capture";
            m_gloveCaptureL[1] = "\r\n";

            m_gloveCaptureR    = new string[30];
            m_gloveCaptureR[0] = "Right Glove Capture";
            m_gloveCaptureR[1] = "\r\n";
        }
        // Delete surfaces...
        private void DeleteSurfaces()
        {
            lock (this)
            {
                if (privateTexture != null)
                {
                    privateTexture.Dispose();
                    privateTexture = null;
                }

                if (privateSurface != null)
                {
                    privateSurface.Dispose();
                    privateSurface = null;
                }

                if (videoSurface != null)
                {
                    videoSurface.Dispose();
                    videoSurface = null;
                }
                axiomTexture = null;
            }
        }
示例#25
0
		private void _addTextureDebugOverlay( TrayLocation loc, Texture tex, int i )
		{
			_addTextureDebugOverlay( loc, tex.Name, i );
		}
示例#26
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="stage"></param>
		/// <param name="enabled"></param>
		/// <param name="texture"></param>
		public override void SetTexture( int stage, bool enabled, Texture texture )
		{
			GLESConfig.GlCheckError( this );

			// TODO We need control texture types?????

			GLESTexture tex = texture as GLESTexture;

			if ( !ActivateGLTextureUnit( stage ) )
				return;

			if ( enabled )
			{
				if ( tex != null )
				{
					// note used
					tex.Touch();
				}
				OpenGL.Enable( All.Texture2D );
				GLESConfig.GlCheckError( this );
				// Store the number of mipmaps
				_textureMipmapCount = tex.MipmapCount;

				if ( tex != null )
				{
					OpenGL.BindTexture( All.Texture2D, tex.TextureID );
					GLESConfig.GlCheckError( this );
				}
				else
				{
					OpenGL.BindTexture( All.Texture2D, ( (GLESTextureManager)textureManager ).WarningTextureID );
					GLESConfig.GlCheckError( this );
				}
			}//end if enabled
			else
			{
				OpenGL.Enable( All.Texture2D );
				OpenGL.Disable( All.Texture2D );
				GLESConfig.GlCheckError( this );

				OpenGL.TexEnv( All.TextureEnv, All.TextureEnvMode, (int)All.Modulate );
				GLESConfig.GlCheckError( this );

				// bind zero texture
				OpenGL.BindTexture( All.Texture2D, 0 );
				GLESConfig.GlCheckError( this );
			}

			ActivateGLTextureUnit( 0 );
		}
示例#27
0
		protected override void load()
		{
			// clarabie - nov 18, 2008
			// modified this to check for an existing material instead of always
			// creating a new one. Allows more flexibility, but also specifically allows us to
			// solve the problem of XNA not having fixed function support

			this._material = (Material)MaterialManager.Instance.GetByName( "Fonts/" + _name );

			if ( this._material == null )
			{
				// create a material for this font
				this._material = (Material)MaterialManager.Instance.Create( "Fonts/" + _name, Group );

				TextureUnitState unitState = null;
				var blendByAlpha = false;

				if ( this._fontType == FontType.TrueType )
				{
#if !( XBOX || XBOX360 )
					// create the font bitmap on the fly
					createTexture();

					// a texture layer was added in CreateTexture
					unitState = this._material.GetTechnique( 0 ).GetPass( 0 ).GetTextureUnitState( 0 );

					blendByAlpha = true;
#endif
				}
				else
				{
					// load this texture
					// TODO In general, modify any methods like this that throw their own exception rather than returning null, so the caller can decide how to handle a missing resource.

					this._texture = TextureManager.Instance.Load( Source, Group, TextureType.TwoD, 0 );

					blendByAlpha = texture.HasAlpha;
					// pre-created font images
					unitState = Material.GetTechnique( 0 ).GetPass( 0 ).CreateTextureUnitState( Source );
				}

				// Make sure material is aware of colour per vertex.
				this._material.GetTechnique( 0 ).GetPass( 0 ).VertexColorTracking = TrackVertexColor.Diffuse;

				if ( unitState != null )
				{
					// Clamp to avoid fuzzy edges
					unitState.SetTextureAddressingMode( TextureAddressing.Clamp );
					// Allow min/mag filter, but no mip
					unitState.SetTextureFiltering( FilterOptions.Linear, FilterOptions.Linear, FilterOptions.None );
				}

				// set up blending mode
				if ( blendByAlpha )
				{
					this._material.SetSceneBlending( SceneBlendType.TransparentAlpha );
				}
				else
				{
					// assume black background here
					this._material.SetSceneBlending( SceneBlendType.Add );
				}
			}
		}
		/// <summary>
		/// Helper method to render a composite map.
		/// </summary>
		/// <param name="size"> The requested composite map size</param>
		/// <param name="rect"> The region of the composite map to update, in image space</param>
		/// <param name="mat">The material to use to render the map</param>
		/// <param name="destCompositeMap"></param>
		public virtual void RenderCompositeMap( int size, Rectangle rect, Material mat, Texture destCompositeMap )
		{
			//return;
			if ( this.mCompositeMapSM == null )
			{
				//dedicated SceneManager

				this.mCompositeMapSM = Root.Instance.CreateSceneManager( SceneType.ExteriorClose,
				                                                         "TerrainMaterialGenerator_SceneManager" );
				float camDist = 100;
				float halfCamDist = camDist*0.5f;
				this.mCompositeMapCam = this.mCompositeMapSM.CreateCamera( "TerrainMaterialGenerator_Camera" );
				this.mCompositeMapCam.Position = new Vector3( 0, 0, camDist );
				//mCompositeMapCam.LookAt(Vector3.Zero);
				this.mCompositeMapCam.ProjectionType = Projection.Orthographic;
				this.mCompositeMapCam.Near = 10;
				this.mCompositeMapCam.Far = 999999*3;
				//mCompositeMapCam.AspectRatio = camDist / camDist;
				this.mCompositeMapCam.SetOrthoWindow( camDist, camDist );
				// Just in case material relies on light auto params
				this.mCompositeMapLight = this.mCompositeMapSM.CreateLight( "TerrainMaterialGenerator_Light" );
				this.mCompositeMapLight.Type = LightType.Directional;

				RenderSystem rSys = Root.Instance.RenderSystem;
				float hOffset = rSys.HorizontalTexelOffset/(float)size;
				float vOffset = rSys.VerticalTexelOffset/(float)size;

				//setup scene
				this.mCompositeMapPlane = this.mCompositeMapSM.CreateManualObject( "TerrainMaterialGenerator_ManualObject" );
				this.mCompositeMapPlane.Begin( mat.Name, OperationType.TriangleList );
				this.mCompositeMapPlane.Position( -halfCamDist, halfCamDist, 0 );
				this.mCompositeMapPlane.TextureCoord( 0 - hOffset, 0 - vOffset );
				this.mCompositeMapPlane.Position( -halfCamDist, -halfCamDist, 0 );
				this.mCompositeMapPlane.TextureCoord( 0 - hOffset, 1 - vOffset );
				this.mCompositeMapPlane.Position( halfCamDist, -halfCamDist, 0 );
				this.mCompositeMapPlane.TextureCoord( 1 - hOffset, 1 - vOffset );
				this.mCompositeMapPlane.Position( halfCamDist, halfCamDist, 0 );
				this.mCompositeMapPlane.TextureCoord( 1 - hOffset, 0 - vOffset );
				this.mCompositeMapPlane.Quad( 0, 1, 2, 3 );
				this.mCompositeMapPlane.End();
				this.mCompositeMapSM.RootSceneNode.AttachObject( this.mCompositeMapPlane );
			} //end if

			// update
			this.mCompositeMapPlane.SetMaterialName( 0, mat.Name );
			this.mCompositeMapLight.Direction = TerrainGlobalOptions.LightMapDirection;
			this.mCompositeMapLight.Diffuse = TerrainGlobalOptions.CompositeMapDiffuse;
			this.mCompositeMapSM.AmbientLight = TerrainGlobalOptions.CompositeMapAmbient;


			//check for size change (allow smaller to be reused)
			if ( this.mCompositeMapRTT != null && size != this.mCompositeMapRTT.Width )
			{
				TextureManager.Instance.Remove( this.mCompositeMapRTT );
				this.mCompositeMapRTT = null;
			}
			if ( this.mCompositeMapRTT == null )
			{
				this.mCompositeMapRTT = TextureManager.Instance.CreateManual( this.mCompositeMapSM.Name + "/compRTT",
				                                                              ResourceGroupManager.DefaultResourceGroupName,
				                                                              TextureType.TwoD, size, size, 0, PixelFormat.BYTE_RGBA,
				                                                              TextureUsage.RenderTarget );

				RenderTarget rtt = this.mCompositeMapRTT.GetBuffer().GetRenderTarget();
				// don't render all the time, only on demand
				rtt.IsAutoUpdated = false;
				Viewport vp = rtt.AddViewport( this.mCompositeMapCam );
				// don't render overlays
				vp.ShowOverlays = false;
			}

			// calculate the area we need to update
			float vpleft = (float)rect.Left/(float)size;
			float vptop = (float)rect.Top/(float)size;
			float vpright = (float)rect.Right/(float)size;
			float vpbottom = (float)rect.Bottom/(float)size;
			float vpwidth = (float)rect.Width/(float)size;
			float vpheight = (float)rect.Height/(float)size;

			RenderTarget rtt2 = this.mCompositeMapRTT.GetBuffer().GetRenderTarget();
			Viewport vp2 = rtt2.GetViewport( 0 );
			this.mCompositeMapCam.SetWindow( vpleft, vptop, vpright, vpbottom );
			rtt2.Update();
			vp2.Update();
			// We have an RTT, we want to copy the results into a regular texture
			// That's because in non-update scenarios we don't want to keep an RTT
			// around. We use a single RTT to serve all terrain pages which is more
			// efficient.
			var box = new BasicBox( (int)rect.Left, (int)rect.Top, (int)rect.Right, (int)rect.Bottom );
			destCompositeMap.GetBuffer().Blit( this.mCompositeMapRTT.GetBuffer(), box, box );
		}
示例#29
0
        public WangMap(int width, int height)
        {
            Width = width * 4;
            Height = height * 4;
            _subHeight = height;
            _subWidth = width;

            // start off with generating tile "12"
            // which has red top red left and green bottom green right
            // thus it can have ompletley random side edges

            _map = new byte[height * width * 4 * 4, 2];
            var basetile = new byte[height * width, 1];
#if !InvariantVersion

            #region Simple Version

            var constraints = new byte[8][];
            constraints[0] = new byte[_subWidth];  // top red
            constraints[1] = new byte[_subWidth];  // top green
            constraints[2] = new byte[_subHeight]; // left red
            constraints[3] = new byte[_subHeight]; // left green
            constraints[4] = new byte[_subHeight]; // right red
            constraints[5] = new byte[_subHeight]; // right green
            constraints[6] = new byte[_subWidth];  // bottom red
            constraints[7] = new byte[_subWidth];  // bottom green

            // generate tile 12
            WangHelper.GenerateTile(_subWidth, _subHeight, _rand, basetile, null, null, null, null);
            Upload(basetile, 12);

            // copy constraints
            for (var x = 0; x < _subWidth; x++)
            {
                constraints[6][x] = basetile[x,0];
                constraints[1][x] = basetile[(_subHeight - 1)*_subWidth + x,0];
            }

            for (var y = 0; y < _subHeight; y++)
            {
                constraints[4][y] = basetile[y*_subWidth,0];
                constraints[3][y] = basetile[y*_subWidth + _subWidth - 1,0];  
            }

            // generate tile 3
            WangHelper.GenerateTile(_subWidth, _subHeight, _rand, basetile,
                constraints[3], constraints[4],
                constraints[1], constraints[6]);
            Upload(basetile, 3);

            // copy constraints
            for (var x = 0; x < _subWidth; x++)
            {
                constraints[7][x] = basetile[x,0];
                constraints[0][x] = basetile[(_subHeight - 1) * _subWidth + x,0];
            }

            for (var y = 0; y < _subHeight; y++)
            {
                constraints[5][y] = basetile[y * _subWidth,0];
                constraints[2][y] = basetile[y * _subWidth + _subWidth - 1,0];
            }

            for (var map = 0; map < 16; map++)
            {
                if ((map == 12) || (map == 3))
                    continue; // skip the base tile

                //                                        red              green
                var top =  ((map & (int)WangHelper.Bit.Top) == 0)      ? constraints[0] : constraints[1];
                var left = ((map & (int)WangHelper.Bit.Left) == 0)     ? constraints[2] : constraints[3];
                var right = ((map & (int)WangHelper.Bit.Right) == 0)   ? constraints[4] : constraints[5];
                var bottom = ((map & (int)WangHelper.Bit.Bottom) == 0) ? constraints[6] : constraints[7];
                    
                WangHelper.GenerateTile(_subWidth, _subHeight, _rand, 
                    basetile, left, right, top, bottom);
                Upload(basetile, map);
            }

            #endregion

#else

            // this is a far more restrictive version that is invariant under rotations

            #region Invariant version

            if (height != width)
                throw new Exception("Width must be same as height for invariant map");

            var constraints = new byte[2][];
            constraints[0] = new byte[_subWidth]; // red
            constraints[1] = new byte[_subWidth]; // green

#if MirrorInvariant

            for (var i = 0; i < _subWidth / 2; i++)
            {
                var rnd = (byte)((_rand.Next() & 0x1) * 0xF);

                constraints[0][i] = rnd;
                constraints[0][_subWidth - i - 1] = rnd;
                rnd = (byte)((_rand.Next() & 0x1) * 0xF);

                constraints[1][i] = rnd;
                constraints[1][_subWidth - i - 1] = rnd;
            }

#else

            for (var i = 0; i < _subWidth; i++)
            {
                constraints[0][i] = (byte)((_rand.Next() & 0x1) * 0xF);
                constraints[1][i] = (byte)((_rand.Next() & 0x1) * 0xF);
            }

#endif

            for (var map = 0; map < 16; map++)
            {
                var top = ((map & (int)WangHelper.Bit.Top) == 0) ? constraints[0] : constraints[1];
                var left = ((map & (int)WangHelper.Bit.Left) == 0) ? constraints[0] : constraints[1];
                var right = ((map & (int)WangHelper.Bit.Right) == 0) ? constraints[0] : constraints[1];
                var bottom = ((map & (int)WangHelper.Bit.Bottom) == 0) ? constraints[0] : constraints[1];

                WangHelper.GenerateTile(_subWidth, _subHeight, _rand,
                                        basetile, left, right, top, bottom);

                Upload(basetile, map);
            }

            #endregion

#endif

            WangHelper.GenerateIndices(_map);


            var tex = TextureManager.Instance.CreateManual("WangMap",
                                                           ResourceGroupManager.DefaultResourceGroupName,
                                                           TextureType.TwoD, Width, Height, 0, PixelFormat.BYTE_LA);
            using (var buf = tex.GetBuffer())
            {
                AsTexture = tex;
                var box = buf.Lock(new BasicBox(0, 0, Width, Height), BufferLocking.Normal);

                var idx = 0;

                

                

                for (var y = 0; y < Height; y++)
                {
                    IntPtr scanLine;
                    switch (tex.Format)
                    {
                        case PixelFormat.BYTE_LA:
                            scanLine = box.Data + y * box.RowPitch * 2;
                            for (var x = 0; x < Width; x++)
                            {
                                Marshal.WriteByte(scanLine, 0, _map[idx, 0]);
                                Marshal.WriteByte(scanLine, 1, _map[idx, 1]);

                                scanLine += 2;
                                idx++;
                            }
                            break;

                        case PixelFormat.A8R8G8B8:
                            scanLine = box.Data + y * box.RowPitch * 4;
                            for (var x = 0; x < Width; x++)
                            {
                                Marshal.WriteByte(scanLine, 0, _map[idx, 0]);
                                Marshal.WriteByte(scanLine, 1, _map[idx, 0]);
                                Marshal.WriteByte(scanLine, 2, _map[idx, 0]);
                                Marshal.WriteByte(scanLine, 3, _map[idx, 1]);

                                scanLine += 4;
                                idx++;
                            }
                            break;

                        default:
                            throw new AxiomException("Axiom does not support a proper texture format!");
                    }
                }

                buf.Unlock();
            }

        }
		public void Dispose()
		{
			if ( this.mProfiles != null )
			{
				this.mProfiles.Clear();
				this.mProfiles = null;
			}
			if ( this.mCompositeMapRTT != null && TextureManager.Instance != null )
			{
				TextureManager.Instance.Remove( this.mCompositeMapRTT );
				this.mCompositeMapRTT = null;
			}
			if ( this.mCompositeMapSM != null && Root.Instance != null )
			{
				// will also delete cam and objects etc
				Root.Instance.DestroySceneManager( this.mCompositeMapSM );
				this.mCompositeMapSM = null;
				this.mCompositeMapCam = null;
				this.mCompositeMapPlane = null;
				this.mCompositeMapLight = null;
			}
		}
 public TouchedPage(PageCoord coord, Texture mask)
 {
     this.coord = coord;
     this.mask = mask;
 }
示例#32
0
        static void BuildShadeMask()
        {
            int pageSize = TerrainManager.Instance.PageSize;
            byte[] byteMask = new byte[pageSize * pageSize];

            // fill the mask with 128, which is the 100% value
            for (int i = 0; i < pageSize * pageSize; i++)
            {
                byteMask[i] = 128;
            }

            // create the random number generator
            Random rand = new Random(1234);

            // create a number of "blobs"
            for (int i = 0; i < 200; i++)
            {
                // starting point for this blob
                int x = rand.Next(pageSize);
                int y = rand.Next(pageSize);

                // value for this blob
                int valueRange = 32;
                byte value = (byte)rand.Next(128-valueRange, 128+valueRange);

                // number of points in this blob
                int n = rand.Next(10, 500);

                while (n >= 0)
                {
                    if (byteMask[x + y * pageSize] == 128)
                    {
                        n--;
                        byteMask[x + y * pageSize] = value;
                    }

                    // move in a random direction
                    int dir = rand.Next(8);
                    switch (dir)
                    {
                        case 0:
                            x++;
                            break;
                        case 1:
                            x--;
                            break;
                        case 2:
                            y++;
                            break;
                        case 3:
                            y--;
                            break;
                        case 4:
                            x++;
                            y++;
                            break;
                        case 5:
                            x++;
                            y--;
                            break;
                        case 6:
                            x--;
                            y++;
                            break;
                        case 7:
                            x--;
                            y--;
                            break;
                    }

                    // clamp x and y to the page
                    if (x < 0)
                    {
                        x = 0;
                    }
                    if (x > pageSize - 1)
                    {
                        x = pageSize - 1;
                    }
                    if (y < 0)
                    {
                        y = 0;
                    }
                    if (y > pageSize - 1)
                    {
                        y = pageSize - 1;
                    }
                }
            }

            // simple box filter on the shade mask
            byteMask = FilterShadeMask(byteMask, pageSize);

            // generate a texture from the mask
            Image maskImage = Image.FromDynamicImage(byteMask, pageSize, pageSize, PixelFormat.A8);
            String texName = "PageShadeMask";
            shadeMask = TextureManager.Instance.LoadImage(texName, maskImage);
        }
示例#33
0
		protected virtual void EnsureShadowTexturesCreated()
		{
			if ( shadowTextureConfigDirty )
			{
				DestroyShadowTextures();
				ShadowTextureManager.Instance.GetShadowTextures( shadowTextureConfigList, shadowTextures );

				// clear shadow cam - light mapping
				shadowCameraLightMapping.Clear();

				// Recreate shadow textures
				foreach ( Texture shadowTexture in shadowTextures )
				{
					// Camera names are local to SM
					String camName = shadowTexture.Name + "Cam";
					// Material names are global to SM, make specific
					String matName = shadowTexture.Name + "Mat" + this.Name;

					RenderTexture shadowRTT = shadowTexture.GetBuffer().GetRenderTarget();

					// Create camera for this texture, but note that we have to rebind
					// in PrepareShadowTextures to coexist with multiple SMs
					Camera cam = CreateCamera( camName );
					cam.AspectRatio = shadowTexture.Width / (Real)shadowTexture.Height;
					shadowTextureCameras.Add( cam );

					// Create a viewport, if not there already
					if ( shadowRTT.NumViewports == 0 )
					{
						// Note camera assignment is transient when multiple SMs
						Viewport v = shadowRTT.AddViewport( cam );
						v.SetClearEveryFrame(true);
						// remove overlays
						v.ShowOverlays = false;
					}

					// Don't update automatically - we'll do it when required
					shadowRTT.IsAutoUpdated = false;

					// Also create corresponding Material used for rendering this shadow
					Material mat = (Material)MaterialManager.Instance[ matName ];
					if ( mat == null )
					{
						mat = (Material)MaterialManager.Instance.Create( matName, ResourceGroupManager.InternalResourceGroupName );
					}
					Pass p = mat.GetTechnique( 0 ).GetPass( 0 );
					if ( p.TextureUnitStageCount != 1 /* ||
						 p.GetTextureUnitState( 0 ).GetTexture( 0 ) != shadowTexture */ )
					{
						mat.GetTechnique( 0 ).GetPass( 0 ).RemoveAllTextureUnitStates();
						// create texture unit referring to render target texture
						TextureUnitState texUnit = p.CreateTextureUnitState( shadowTexture.Name );
						// set projective based on camera
						texUnit.SetProjectiveTexturing( !p.HasVertexProgram, cam );
						// clamp to border colour
                        texUnit.SetTextureAddressingMode( TextureAddressing.Border );
						texUnit.TextureBorderColor = ColorEx.White;
						mat.Touch();
					}

					// insert dummy camera-light combination
					shadowCameraLightMapping.Add( cam, null );

					// Get null shadow texture
					nullShadowTexture = shadowTextureConfigList.Count == 0 ?
										null :
										ShadowTextureManager.Instance.GetNullShadowTexture( shadowTextureConfigList[ 0 ].format );
				}
				shadowTextureConfigDirty = false;
			}
		}
        public void EnsureShadowTexturesCreated()
        {
            if (shadowTextureConfigDirty) {
                DestroyShadowTextures();
                ShadowTextureManager.Instance.GetShadowTextures(shadowTextureConfigList, shadowTextures);

                // clear shadow cam - light mapping
                shadowCamLightMapping.Clear();

                // Recreate shadow textures
                foreach (Texture shadowTex in shadowTextures) {

                    // Camera names are local to SM
                    string camName = shadowTex.Name + "Cam";
                    // Material names are global to SM, make specific
                    string matName = shadowTex.Name + "Mat" + smName;

                    RenderTexture shadowRTT = shadowTex.GetBuffer().GetRenderTarget();

                    // Create camera for this texture, but note that we have to rebind
                    // in prepareShadowTextures to coexist with multiple SMs
                    Camera cam = CreateCamera(camName);
                    cam.AspectRatio = (float)shadowTex.Width / (float)shadowTex.Height;
                    // Don't use rendering distance for light cameras; we don't want shadows
                    // for visible objects disappearing, especially for directional lights
                    cam.UseRenderingDistance = false;
                    shadowTextureCameras.Add(cam);

                    // Create a viewport, if not there already
                    if (shadowRTT.NumViewports == 0) {
                        // Note camera assignment is transient when multiple SMs
                        Viewport view = shadowRTT.AddViewport(cam);
                        view.ClearEveryFrame = true;
                        // remove overlays
                        view.OverlaysEnabled = false;
                    }

                    // Don't update automatically - we'll do it when required
                    shadowRTT.IsAutoUpdated = false;

                    // Also create corresponding Material used for rendering this shadow
                    Material mat = (Material)MaterialManager.Instance.GetByName(matName);
                    if (mat == null) {
                        mat = (Material)MaterialManager.Instance.Create(matName);
                    Pass p = mat.GetTechnique(0).GetPass(0);
                    if (p.NumTextureUnitStages != 1 ||
                        p.GetTextureUnitState(0).GetTexturePtr(0) != shadowTex) {
                        mat.GetTechnique(0).GetPass(0).RemoveAllTextureUnitStates();
                        // create texture unit referring to render target texture
                        TextureUnitState texUnit = p.CreateTextureUnitState(shadowTex.Name);
                        // set projective based on camera
                        texUnit.SetProjectiveTexturing(!p.HasVertexProgram, cam);
                        // clamp to border colour
                        texUnit.TextureAddressing = TextureAddressing.Border;
                        texUnit.TextureBorderColor = ColorEx.White;
                        mat.Touch();
                    }

                    // insert dummy camera-light combination
                    shadowCamLightMapping[cam] = null;

                    // Get null shadow texture
                    if (shadowTextureConfigList.Count == 0)
                        nullShadowTexture = null;
                    else
                        nullShadowTexture = ShadowTextureManager.Instance.GetNullShadowTexture(
                            shadowTextureConfigList[0].format);
                    }
                }
                shadowTextureConfigDirty = false;
            }
        }