public static FindMediaFile ( string path, string filename ) : string | ||
path | string | Initial path to search |
filename | string | Filename we're searching for |
리턴 | string |
/// <summary> /// The device has been created. Resources that are not lost on /// Reset() can be created here -- resources in Pool.Managed, /// Pool.Scratch, or Pool.SystemMemory. Image surfaces created via /// CreateImageSurface are never lost and can be created here. Vertex /// shaders and pixel shaders can also be created here as they are not /// lost on Reset(). /// </summary> protected override void InitializeDeviceObjects() { // Initialize the drawingFont's internal textures drawingFont.InitializeDeviceObjects(device); ExtendedMaterial[] mtrl = null; string path = DXUtil.FindMediaFile(initialDirectory, meshFilename); try { systemMemoryMesh = Mesh.FromFile(path, MeshFlags.SystemMemory, device, out adjacency, out mtrl); } catch { // Hide the error so we display a blue screen return; } // Lock the vertex buffer, to generate a simple bounding sphere VertexBuffer vb = null; try { vb = systemMemoryMesh.VertexBuffer; GraphicsStream vbStream = vb.Lock(0, 0, 0); objectRadius = Geometry.ComputeBoundingSphere(vbStream, systemMemoryMesh.NumberVertices, systemMemoryMesh.VertexFormat, out objectCenter); } finally { // Make sure we unlock the buffer if we fail if (vb != null) { vb.Unlock(); } } meshMaterials = new Material[mtrl.Length]; meshTextures = new Texture[mtrl.Length]; for (int i = 0; i < mtrl.Length; i++) { meshMaterials[i] = mtrl[i].Material3D; if ((mtrl[i].TextureFilename != null) && ((mtrl[i].TextureFilename != string.Empty))) { meshTextures[i] = TextureLoader.FromFile(device, DXUtil.FindMediaFile(null, mtrl[i].TextureFilename)); } } // Make sure there are normals, which are required for the tesselation // enhancement if ((systemMemoryMesh.VertexFormat & VertexFormats.Normal) != VertexFormats.Normal) { Mesh tempMesh = systemMemoryMesh.Clone(systemMemoryMesh.Options.Value, systemMemoryMesh.VertexFormat | VertexFormats.Normal, device); tempMesh.ComputeNormals(); systemMemoryMesh.Dispose(); systemMemoryMesh = tempMesh; } }
/// <summary> /// Helper function to create a texture. It checks the root path first, /// then tries the DXSDK media path (as specified in the system registry). /// </summary> public static Texture CreateTexture(Device device, string textureFilename, Format format) { // Get the path to the texture string path = DXUtil.FindMediaFile(null, textureFilename); // Create the texture using D3DX return(TextureLoader.FromFile(device, path, D3DX.Default, D3DX.Default, D3DX.Default, 0, format, Pool.Managed, Filter.Triangle | Filter.Mirror, Filter.Triangle | Filter.Mirror, 0)); }
public AudioClass(Control owner) { BufferDescription desc = new BufferDescription(); localDevice = new Device(); localDevice.SetCooperativeLevel(owner, CooperativeLevel.Normal); localBuffer = new Buffer(DXUtil.FindMediaFile(null, "drumpad-bass_drum.wav"), desc, localDevice); audioPlayer = new Audio(DXUtil.FindMediaFile(null, "DirectX Theme.wma")); }
/// <summary> /// Assembles and creates a file-based vertex shader /// </summary> public static VertexShader CreateVertexShader(Device device, string filename) { GraphicsStream code = null; string path = null; // Get the path to the vertex shader file path = DXUtil.FindMediaFile(null, filename); // Assemble the vertex shader file code = ShaderLoader.FromFile(path, null, 0); // Create the vertex shader return(new VertexShader(device, code)); }
/// <summary> /// The device has been created. Resources that are not lost on /// Reset() can be created here -- resources in Pool.Managed, /// Pool.Scratch, or Pool.SystemMemory. Image surfaces created via /// CreateImageSurface are never lost and can be created here. Vertex /// shaders and pixel shaders can also be created here as they are not /// lost on Reset(). /// </summary> protected override void InitializeDeviceObjects() { // Initialize the font's internal textures drawingFont.InitializeDeviceObjects(device); drawingFontSmall.InitializeDeviceObjects(device); // Load a sphere mesh ballMesh = Mesh.Sphere(device, 1.2f, 36, 36); // Load effect file string strPath = DXUtil.FindMediaFile(null, "MotionBlur.fx"); effect = Effect.FromFile(device, strPath, null, 0, null); }
/// <summary> /// Creates a new mesh /// </summary> /// <param name="device">The device used to create the mesh</param> /// <param name="filename">the file to load</param> public void Create(Device device, string filename) { string strPath = null; GraphicsStream adjacencyBuffer; ExtendedMaterial[] Mat; if (device != null) { device.DeviceLost += new System.EventHandler(this.InvalidateDeviceObjects); device.Disposing += new System.EventHandler(this.InvalidateDeviceObjects); device.DeviceReset += new System.EventHandler(this.RestoreDeviceObjects); } // Find the path for the file, and convert it to ANSI (for the D3DX API) strPath = DXUtil.FindMediaFile(null, filename); // Load the mesh systemMemoryMesh = Mesh.FromFile(strPath, MeshFlags.SystemMemory, device, out adjacencyBuffer, out Mat); // Optimize the mesh for performance systemMemoryMesh.OptimizeInPlace(MeshFlags.OptimizeCompact | MeshFlags.OptimizeAttrSort | MeshFlags.OptimizeVertexCache, adjacencyBuffer); textures = new Texture[Mat.Length]; materials = new Direct3D.Material[Mat.Length]; for (int i = 0; i < Mat.Length; i++) { materials[i] = Mat[i].Material3D; // Set the ambient color for the material (D3DX does not do this) materials[i].Ambient = materials[i].Diffuse; if (Mat[i].TextureFilename != null) { // Create the texture string texturefilename = DXUtil.FindMediaFile(null, Mat[i].TextureFilename); textures[i] = TextureLoader.FromFile(device, texturefilename); } } adjacencyBuffer.Close(); adjacencyBuffer = null; }
/// <summary> /// The device has been created. Resources that are not lost on /// Reset() can be created here -- resources in Pool.Managed, /// Pool.Scratch, or Pool.SystemMemory. Image surfaces created via /// CreateImageSurface are never lost and can be created here. Vertex /// shaders and pixel shaders can also be created here as they are not /// lost on Reset(). /// </summary> protected override void InitializeDeviceObjects() { // Initialize the font's internal textures drawingFont.InitializeDeviceObjects(device); drawingFontSmall.InitializeDeviceObjects(device); // Create teapot mesh and sphere mesh // Note: We don't need a declarator here since D3DXCreateSphere already // implicitly creates one for us, and it is set inside the DrawSubset call. teapotMesh = Mesh.Teapot(device); sphereMesh = Mesh.Sphere(device, 1.0f, 30, 30); // Load effect file string strPath = DXUtil.FindMediaFile(null, "ClipVolume.fx"); effect = Effect.FromFile(device, strPath, null, 0, null); }
protected override void RestoreDeviceObjects(object sender, System.EventArgs e) { // Now Create the VB if ((vertexBuffer == null) || (vertexBuffer.Disposed)) { vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), 100, device, Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Pool.Default); vertexBuffer.Created += new System.EventHandler(this.OnCreateVertexBuffer); this.OnCreateVertexBuffer(vertexBuffer, null); } device.RenderState.Ambient = System.Drawing.Color.White; // Turn off culling, so we see the front and back of the triangle device.RenderState.CullMode = Cull.None; // Turn off D3D lighting device.RenderState.Lighting = false; // Turn on the ZBuffer device.RenderState.ZBufferEnable = true; device.SamplerState[0].AddressU = TextureAddress.Clamp; device.SamplerState[0].AddressV = TextureAddress.Clamp; string path = DXUtil.FindMediaFile(null, "ruby.avi"); try { videoTexture = Video.FromFile(path); videoTexture.Ending += new System.EventHandler(this.MovieOver); videoTexture.TextureReadyToRender += new TextureRenderEventHandler(this.RenderIt); // Now start rendering to our texture videoTexture.RenderToTexture(device); } catch (Exception err) { MessageBox.Show(string.Format("An error has occurred that will not allow this sample to continue.\r\nException={0}", err.ToString()), "This sample must exit.", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); throw err; } }
/// <summary> /// The device exists, but may have just been Reset(). Resources in /// Pool.Default and any other device state that persists during /// rendering should be set here. Render states, matrices, textures, /// etc., that don't change during rendering can be set once here to /// avoid redundant state setting during Render() or FrameMove(). /// </summary> protected override void RestoreDeviceObjects(System.Object sender, System.EventArgs e) { // Setup render states device.RenderState.Lighting = false; device.RenderState.CullMode = Cull.None; // Create index buffer indexBuffer = new IndexBuffer(typeof(short), numberIndices, device, 0, Pool.Default); short[] indices = (short[])indexBuffer.Lock(0, 0); int count = 0; for (int y = 1; y < m_Size; y++) { for (int x = 1; x < m_Size; x++) { indices[count++] = (short)((y - 1) * m_Size + (x - 1)); indices[count++] = (short)((y - 0) * m_Size + (x - 1)); indices[count++] = (short)((y - 1) * m_Size + (x - 0)); indices[count++] = (short)((y - 1) * m_Size + (x - 0)); indices[count++] = (short)((y - 0) * m_Size + (x - 1)); indices[count++] = (short)((y - 0) * m_Size + (x - 0)); } } indexBuffer.Unlock(); // Create vertex buffer vertexBuffer = new VertexBuffer(typeof(Vector2), numberVertices, device, Usage.WriteOnly, 0, Pool.Default); Vector2[] vertices = (Vector2[])vertexBuffer.Lock(0, 0); count = 0; for (int y = 0; y < m_Size; y++) { for (int x = 0; x < m_Size; x++) { vertices[count++] = new Vector2(((float)x / (float)(m_Size - 1) - 0.5f) * (float)Math.PI, ((float)y / (float)(m_Size - 1) - 0.5f) * (float)Math.PI); } } vertexBuffer.Unlock(); // Create vertex shader string shaderPath = null; GraphicsStream code = null; // Create our declaration VertexElement[] decl = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.Position, 0), VertexElement.VertexDeclarationEnd }; ourDeclaration = new VertexDeclaration(device, decl); // Find the vertex shader file shaderPath = DXUtil.FindMediaFile(null, "Ripple.vsh"); // Assemble the vertex shader from the file code = ShaderLoader.FromFile(shaderPath, null, 0); // Create the vertex shader ourShader = new VertexShader(device, code); code.Close(); // Set up the projection matrix float fAspectRatio = (float)device.PresentationParameters.BackBufferWidth / (float)device.PresentationParameters.BackBufferHeight; projectionMatrix = Matrix.PerspectiveFovRH(Geometry.DegreeToRadian(60.0f), fAspectRatio, 0.1f, 100.0f); device.Transform.Projection = projectionMatrix; }
/// <summary> /// The device has been created. Resources that are not lost on /// Reset() can be created here -- resources in Pool.Managed, /// Pool.Scratch, or Pool.SystemMemory. Image surfaces created via /// CreateImageSurface are never lost and can be created here. Vertex /// shaders and pixel shaders can also be created here as they are not /// lost on Reset(). /// </summary> protected override void InitializeDeviceObjects() { // Initialize the font's internal textures font.InitializeDeviceObjects(device); string path = DXUtil.FindMediaFile(initialDirectory, meshFilename); Mesh pMesh = null; Mesh pTempMesh = null; GraphicsStream adj = null; ExtendedMaterial[] mtrl = null; MeshFlags i32BitFlag; WeldEpsilons Epsilons = new WeldEpsilons(); ProgressiveMesh pPMesh = null; int cVerticesMin = 0; int cVerticesMax = 0; int cVerticesPerMesh = 0; try { // Load the mesh from the specified file pMesh = Mesh.FromFile(path, MeshFlags.Managed, device, out adj, out mtrl); i32BitFlag = pMesh.Options.Use32Bit ? MeshFlags.Use32Bit : 0; // perform simple cleansing operations on mesh pTempMesh = Mesh.Clean(pMesh, adj, adj); pMesh.Dispose(); pMesh = pTempMesh; // Perform a weld to try and remove excess vertices like the model bigship1.x in the DX9.0 SDK (current model is fixed) // Weld the mesh using all epsilons of 0.0f. A small epsilon like 1e-6 works well too pMesh.WeldVertices(0, Epsilons, adj, adj); // verify validity of mesh for simplification pMesh.Validate(adj); meshMaterials = new Direct3D.Material[mtrl.Length]; meshTextures = new Texture[mtrl.Length]; for (int i = 0; i < mtrl.Length; i++) { meshMaterials[i] = mtrl[i].Material3D; meshMaterials[i].Ambient = meshMaterials[i].Diffuse; if ((mtrl[i].TextureFilename != null) && (mtrl[i].TextureFilename != "")) { path = DXUtil.FindMediaFile(initialDirectory, mtrl[i].TextureFilename); // Find the path to the texture and create that texture try { meshTextures[i] = TextureLoader.FromFile(device, path); } catch { meshTextures[i] = null; } } } // Lock the vertex buffer to generate a simple bounding sphere VertexBuffer vb = pMesh.VertexBuffer; GraphicsStream vertexData = vb.Lock(0, 0, LockFlags.NoSystemLock); objectRadius = Geometry.ComputeBoundingSphere(vertexData, pMesh.NumberVertices, pMesh.VertexFormat, out objectCenter); vb.Unlock(); vb.Dispose(); if (meshMaterials.Length == 0) { throw new Exception(); } if ((pMesh.VertexFormat & VertexFormats.Normal) == 0) { pTempMesh = pMesh.Clone(i32BitFlag | MeshFlags.Managed, pMesh.VertexFormat | VertexFormats.Normal, device); pTempMesh.ComputeNormals(); pMesh.Dispose(); pMesh = pTempMesh; } pPMesh = new ProgressiveMesh(pMesh, adj, null, 1, MeshFlags.SimplifyVertex); cVerticesMin = pPMesh.MinVertices; cVerticesMax = pPMesh.MaxVertices; cVerticesPerMesh = (cVerticesMax - cVerticesMin) / 10; pmeshes = new ProgressiveMesh[(int)Math.Max(1, Math.Ceiling((cVerticesMax - cVerticesMin) / (float)cVerticesPerMesh))]; // clone full size pmesh fullPmesh = pPMesh.Clone(MeshFlags.Managed | MeshFlags.VbShare, pPMesh.VertexFormat, device); // clone all the separate pmeshes for (int iPMesh = 0; iPMesh < pmeshes.Length; iPMesh++) { pmeshes[iPMesh] = pPMesh.Clone(MeshFlags.Managed | MeshFlags.VbShare, pPMesh.VertexFormat, device); // trim to appropriate space pmeshes[iPMesh].TrimByVertices(cVerticesMin + cVerticesPerMesh * iPMesh, cVerticesMin + cVerticesPerMesh * (iPMesh + 1)); pmeshes[iPMesh].OptimizeBaseLevelOfDetail(MeshFlags.OptimizeVertexCache); } currentPmesh = pmeshes.Length - 1; pmeshes[currentPmesh].NumberVertices = cVerticesMax; fullPmesh.NumberVertices = cVerticesMax; pPMesh.Dispose(); } catch { // hide error so that device changes will not cause exit, shows blank screen instead return; } }
/// <summary> /// The device has been created. Resources that are not lost on /// Reset() can be created here -- resources in Pool.Managed, /// Pool.Scratch, or Pool.SystemMemory. Image surfaces created via /// CreateImageSurface are never lost and can be created here. Vertex /// shaders and pixel shaders can also be created here as they are not /// lost on Reset(). /// </summary> protected override void InitializeDeviceObjects() { // Initialize the drawingFont's internal textures drawingFont.InitializeDeviceObjects(device); //ExtendedMaterial[] mtrl = null; mdlfile = new MDLFile(); string path = DXUtil.FindMediaFile(initialDirectory, meshFilename); try { //systemMemoryMesh = Mesh.FromFile(path, MeshFlags.SystemMemory, device, out adjacency, out mtrl); if (!mdlfile.ReadFromFile(initialDirectory + "\\" + meshFilename)) { throw new FileLoadException("not a valide MDL file.", meshFilename); } MDLObject obj = mdlfile.RootObject; rootmdl = obj; CBLOD.Items.Clear(); if (obj.type == MDLType.mdl_lod) { CBLOD.Enabled = true; for (int i = 0; i < obj.nchildren; i++) { CBLOD.Items.Add(obj.childrens[i].lodval); } obj = obj.childrens[0]; CBLOD.SelectedIndex = 0; } else { CBLOD.Enabled = false; } // while (obj.type != MDLType.mdl_mesh) // { // if (obj.childrens[0].type == MDLType.mdl_empty) // obj = obj.childrens[1]; // else // obj = obj.childrens[0]; // // } // process textures if (mdlfile.NumTextures > 0) { meshMaterials = new Material[mdlfile.NumTextures]; meshTextures = new Texture[mdlfile.NumTextures]; for (int i = 0; i < mdlfile.NumTextures; i++) { meshMaterials[i] = new Direct3D.Material(); meshMaterials[i].Ambient = Color.White; meshMaterials[i].Diffuse = Color.White; MDLFile mdlbmp = new MDLFile(); if (mdlbmp.ReadFromFile(initialDirectory + "\\" + mdlfile.Textures[i] + ".mdl")) { if (mdlbmp.RootObject.type == MDLType.mdl_image) { MDLImage mdlimg = mdlbmp.RootObject.image; MemoryStream memstream = new MemoryStream(mdlimg.bitmap); try { //meshTextures[i] = TextureLoader.FromStream(device,memstream,mdlimg.bitmap.Length,mdlimg.w,mdlimg.h,0,0,Format.R5G6B5,Pool.Managed,Filter.Linear,Filter.Linear,0); //meshTextures[i] = TextureLoader.FromStream(device,memstream,mdlimg.w,mdlimg.h,0,0,Format.R5G6B5,Pool.SystemMemory,Filter.Linear,Filter.Linear,1); Bitmap bitmap = new Bitmap(mdlimg.w, mdlimg.h, PixelFormat.Format16bppRgb565); Rectangle rect = new Rectangle(0, 0, mdlimg.w, mdlimg.h); BitmapData bmdata = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format16bppRgb565); IntPtr pixels = bmdata.Scan0; unsafe { byte *pBits = (byte *)pixels.ToPointer(); for (int p = 0; p < mdlimg.bitmap.Length; p++) { pBits[p] = mdlimg.bitmap[p]; } } bitmap.UnlockBits(bmdata); //bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX); meshTextures[i] = Texture.FromBitmap(device, bitmap, Usage.AutoGenerateMipMap, Pool.Managed); } catch (Exception e) { string mess = e.Message; MessageBox.Show("error loading texture '" + mdlfile.Textures[i] + ".mdl'. " + e.Message); } } } } } ArrayList objs = FlattenChildren(obj); Meshes = new Mesh[objs.Count]; MeshesEnable = new bool[objs.Count]; MeshesTex = new int[objs.Count]; objectRadius = 0; tvObj.Nodes.Clear(); for (int oi = 0; oi < objs.Count; oi++) { obj = (MDLObject)objs[oi]; TreeNode tn = new TreeNode("part " + oi.ToString()); tn.Tag = oi; tn.Checked = true; tn.Nodes.Add("# vertices = " + obj.mesh.nvertex.ToString()); tn.Nodes.Add("# faces = " + (obj.mesh.nfaces / 3).ToString()); if (obj.textidx == -1) { tn.Nodes.Add("no texture"); } else { tn.Nodes.Add("texture = " + mdlfile.Textures[obj.textidx]); } tvObj.Nodes.Add(tn); // process mesh systemMemoryMesh = new Mesh(obj.mesh.nfaces / 3, obj.mesh.nvertex, MeshFlags.SystemMemory, VertexFormats.Position | VertexFormats.Normal | VertexFormats.Texture1, device); //systemMemoryMesh = Mesh.Box(device,12,15,2); VertexBuffer pVB = systemMemoryMesh.VertexBuffer; int dwNumVertices = systemMemoryMesh.NumberVertices; CustomVertex.PositionNormalTextured [] dest = (CustomVertex.PositionNormalTextured [])pVB.Lock(0, typeof(CustomVertex.PositionNormalTextured), 0, dwNumVertices); for (int i = 0; i < dest.Length; i++) { dest[i].X = obj.mesh.vertices[i].x; dest[i].Y = obj.mesh.vertices[i].y; dest[i].Z = obj.mesh.vertices[i].z; dest[i].Nx = obj.mesh.vertices[i].nx; dest[i].Ny = obj.mesh.vertices[i].ny; dest[i].Nz = obj.mesh.vertices[i].nz; dest[i].Tu = obj.mesh.vertices[i].mx; dest[i].Tv = obj.mesh.vertices[i].my; } pVB.Unlock(); int dwNumFaces = systemMemoryMesh.NumberFaces * 3; ushort[] idxs = (ushort[])systemMemoryMesh.LockIndexBuffer(typeof(ushort), 0, dwNumFaces); for (int i = 0; i < dwNumFaces; i += 3) { idxs[i] = obj.mesh.faces[i]; idxs[i + 1] = obj.mesh.faces[i + 2]; idxs[i + 2] = obj.mesh.faces[i + 1]; } systemMemoryMesh.UnlockIndexBuffer(); //systemMemoryMesh.SetIndexBufferData(obj.mesh.faces,LockFlags.None); // Lock the vertex buffer, to generate a simple bounding sphere VertexBuffer vb = null; try { vb = systemMemoryMesh.VertexBuffer; GraphicsStream vbStream = vb.Lock(0, 0, 0); objectRadius = Math.Max(objectRadius, Geometry.ComputeBoundingSphere(vbStream, systemMemoryMesh.NumberVertices, systemMemoryMesh.VertexFormat, out objectCenter)); } finally { // Make sure we unlock the buffer if we fail if (vb != null) { vb.Unlock(); } } // Make sure there are normals, which are required for the tesselation // enhancement if ((systemMemoryMesh.VertexFormat & VertexFormats.Normal) != VertexFormats.Normal) { Mesh tempMesh = systemMemoryMesh.Clone(systemMemoryMesh.Options.Value, systemMemoryMesh.VertexFormat | VertexFormats.Normal, device); tempMesh.ComputeNormals(); systemMemoryMesh.Dispose(); systemMemoryMesh = tempMesh; } Meshes[oi] = systemMemoryMesh; MeshesEnable[oi] = true; MeshesTex[oi] = obj.textidx; } // oi loop tvObj.ExpandAll(); objectCenter = new Vector3(0, 0, 0); } // try catch { // Hide the error so we display a blue screen return; } }