public static void Initialize(System.Windows.Forms.Control Parent) { // Initialize sound sounddevice = new DS.Device(); sounddevice.SetCooperativeLevel(Parent, CooperativeLevel.Normal); //BufferDescription description = new BufferDescription(); description = new BufferDescription(); description.ControlEffects = false; shotsound = new SecondaryBuffer[10]; //shotsound[0] // = new SecondaryBuffer("turn-left.wav", description, sounddevice); //shotsound[1] // = new SecondaryBuffer("turn-left.wav", description, sounddevice); shotsound[2] = new SecondaryBuffer("turn-left.wav", description, sounddevice); shotsound[3] = new SecondaryBuffer("turn-right.wav", description, sounddevice); shotsound[4] = new SecondaryBuffer("horn.wav", description, sounddevice); shotsound[5] = new SecondaryBuffer("ignition.wav", description, sounddevice); shotsound[6] = new SecondaryBuffer("police_siren.wav", description, sounddevice); shotsound[7] = new SecondaryBuffer("ambulance_siren.wav", description, sounddevice); //shotsound[8] // = new SecondaryBuffer("ignition.wav", description, sounddevice); //shotsound[9] // = new SecondaryBuffer("ignition.wav", description, sounddevice); //shotsound = new SecondaryBuffer("horn.wav", description, sounddevice); //shotsound.Play(0, BufferPlayFlags.Default); }
public Minimap(Device device, DeviceContext dc, int minimapWidth, int minimapHeight, Terrain terrain, CameraBase viewCam) { _dc = dc; _minimapViewport = new Viewport(0, 0, minimapWidth, minimapHeight); CreateMinimapTextureViews(device, minimapWidth, minimapHeight); _terrain = terrain; SetupOrthoCamera(); _viewCam = viewCam; // frustum vb will contain four corners of view frustum, with first vertex repeated as the last var vbd = new BufferDescription( VertexPC.Stride * 5, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0 ); _frustumVB = new Buffer(device, vbd); _edgePlanes = new[] { new Plane(1, 0, 0, -_terrain.Width / 2), new Plane(-1, 0, 0, _terrain.Width / 2), new Plane(0, 1, 0, -_terrain.Depth / 2), new Plane(0, -1, 0, _terrain.Depth / 2) }; ScreenPosition = new Vector2(0.25f, 0.75f); Size = new Vector2(0.25f, 0.25f); }
/// <summary> /// Carga un archivo WAV de audio, indicando el volumen del mismo /// Solo se pueden cargar sonidos WAV que sean MONO (1 channel). /// Sonidos stereos (2 channels) no pueden ser utilizados. /// </summary> /// <param name="soundPath">Path del archivo WAV</param> /// <param name="volume">Volumen del mismo</param> public void loadSound(string soundPath, int volume) { try { dispose(); BufferDescription bufferDescription = new BufferDescription(); bufferDescription.Control3D = true; if (volume != -1) { bufferDescription.ControlVolume = true; } soundBuffer = new SecondaryBuffer(soundPath, bufferDescription, GuiController.Instance.DirectSound.DsDevice); buffer3d = new Buffer3D(soundBuffer); buffer3d.MinDistance = 50; if (volume != -1) { soundBuffer.Volume = volume; } } catch (Exception ex) { throw new Exception("Error al cargar sonido estático WAV: " + soundPath, ex); } }
protected TransparencyShader(Device device, string vertexShaderPath, string pixelShaderPath, IInputLayoutProvider inputLayoutMaker) : base(device, vertexShaderPath, pixelShaderPath, inputLayoutMaker) { Contract.Ensures(transparencyConstantBuffer != null, "lightConstantBuffer must be instantiated by this function."); BufferDescription transparencyBufferDesc = new BufferDescription(System.Runtime.InteropServices.Marshal.SizeOf(typeof(TransparencyCBuffer)), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); transparencyConstantBuffer = new SlimDX.Direct3D11.Buffer(device, transparencyBufferDesc); }
public DX11IndexBuffer(DX11RenderContext context, DataStream initial,bool dynamic, bool dispose) { this.context = context; format = SlimDX.DXGI.Format.R32_UInt; BindFlags flags = BindFlags.IndexBuffer; if (context.IsFeatureLevel11) { flags |= BindFlags.ShaderResource; } BufferDescription bd = new BufferDescription() { BindFlags = flags, CpuAccessFlags = dynamic ? CpuAccessFlags.Write : CpuAccessFlags.None, OptionFlags = context.IsFeatureLevel11 ? ResourceOptionFlags.RawBuffer : ResourceOptionFlags.None, SizeInBytes = (int)initial.Length, Usage = dynamic ? ResourceUsage.Dynamic : ResourceUsage.Default, }; initial.Position = 0; this.IndicesCount = (int)initial.Length / 4; this.Buffer = new SlimDX.Direct3D11.Buffer(context.Device, initial, bd); this.CreateSRV(); if (dispose) { initial.Dispose(); } }
public Sky(Device device, string filename, float skySphereRadius) { CubeMapSRV = ShaderResourceView.FromFile(device, filename); using (var r = CubeMapSRV.Resource) { r.DebugName = "sky cubemap"; } var sphere = GeometryGenerator.CreateSphere(skySphereRadius, 30, 30); var vertices = sphere.Vertices.Select(v => v.Position).ToArray(); var vbd = new BufferDescription( Marshal.SizeOf(typeof(Vector3)) * vertices.Length, ResourceUsage.Immutable, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0 ); _vb = new Buffer(device, new DataStream(vertices, false, false), vbd); _indexCount = sphere.Indices.Count; var ibd = new BufferDescription( _indexCount * sizeof(int), ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0 ); _ib = new Buffer(device, new DataStream(sphere.Indices.ToArray(), false, false), ibd); }
/** 指定の音声データを読み込む*/ public bool loadWave(int idx, string fname) { try { BufferDescription desc = null; desc = new BufferDescription(); desc.ControlPan = true; desc.GlobalFocus = true; //現在実行中のアセンブリを取得 Assembly thisExe = Assembly.GetExecutingAssembly(); string assemblyName = thisExe.GetName().Name; // string FileName = assemblyName + "." + fname; string FileName = "DoujinGameProject.Resources." + fname; //埋め込みファイルのストリームを取得 Stream stream = thisExe.GetManifestResourceStream(FileName); //ストリームからバッファ作成 bufSec[idx] = new SecondaryBuffer(stream, desc, devSound); //ストリームを閉じる! stream.Close(); // bufSec[idx] = new SecondaryBuffer(fname, devSound); } catch (Exception e) { sErr = "[loadWaveエラー]" + e.ToString(); return false; } return true; }
/// <summary> /// Initializes a new instance of the <see cref="WVPTransformShader" /> class. /// </summary> /// <param name="device">The device.</param> /// <param name="vertexShaderPath">The vertex shader path.</param> /// <param name="pixelShaderPath">The pixel shader path.</param> public WVPTransformShader(Device device, string vertexShaderPath, string pixelShaderPath, IInputLayoutProvider inputLayoutMaker) : base(device, vertexShaderPath, pixelShaderPath, inputLayoutMaker) { Contract.Ensures(matrixConstantBuffer != null, "matrixConstantBuffer must not be null after this method executes."); BufferDescription matrixBufferDesc = new BufferDescription(System.Runtime.InteropServices.Marshal.SizeOf(typeof(MatrixCBuffer)), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); matrixConstantBuffer = new SlimDX.Direct3D11.Buffer(device, matrixBufferDesc); }
public ObjRenderer(Form1 F) : base(F.Device) { P = F; PortalRoomManager.Equals(null, null); S = new Sorter(); string s0 = Environment.CurrentDirectory + "/resources/shaders/ambient_fast.fx"; SB_V = ShaderBytecode.CompileFromFile(s0, "VS_STATIC", "vs_4_0", ManagedSettings.ShaderCompileFlags, EffectFlags.None); SB_P = ShaderBytecode.CompileFromFile(s0, "PS", "ps_4_0", ManagedSettings.ShaderCompileFlags, EffectFlags.None); VS = new VertexShader(F.Device.HadrwareDevice(), SB_V); PS = new PixelShader(F.Device.HadrwareDevice(), SB_P); IL = new InputLayout(Device.HadrwareDevice(), SB_V, StaticVertex.ies); BufferDescription desc = new BufferDescription { Usage = ResourceUsage.Default, SizeInBytes = 2 * 64, BindFlags = BindFlags.ConstantBuffer }; cBuf = new SlimDX.Direct3D11.Buffer(Device.HadrwareDevice(), desc); dS = new DataStream(2 * 64, true, true); BufferDescription desc2 = new BufferDescription { Usage = ResourceUsage.Default, SizeInBytes = 64, BindFlags = BindFlags.ConstantBuffer }; cBuf2 = new SlimDX.Direct3D11.Buffer(Device.HadrwareDevice(), desc2); dS2 = new DataStream(64, true, true); }
public DX11VertexBuffer(DX11RenderContext context, int verticescount, int vertexsize, bool allowstreamout) { this.context = context; this.TotalSize = verticescount * vertexsize; this.AllowStreamOutput = allowstreamout; BindFlags flags = BindFlags.VertexBuffer; if (allowstreamout) { flags |= BindFlags.StreamOutput; } BufferDescription bd = new BufferDescription() { BindFlags = flags, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = this.TotalSize, Usage = ResourceUsage.Default }; this.Buffer = new SlimDX.Direct3D11.Buffer(context.Device, bd); this.VertexSize = vertexsize; this.VerticesCount = verticescount; }
public Sound(string filename, int ID, short type) : base(filename, ID) { // get the file data WaveFile wf = FileManager.Instance.Load(filename); if(wf.WavFile != null) // we have a wave file with headers { // set up the buffer properties soundDesc = new BufferDescription(); soundDesc.GlobalFocus = false; soundDesc.ControlVolume = true; // enable 3D features for 3D sounds if(type == Sound.THREED_SOUND) { soundDesc.Control3D = true; soundDesc.Mute3DAtMaximumDistance = true; } // load the wave file from the stream into the buffer sound = new SecondaryBuffer(wf.WavFile, soundDesc, ((DirectSoundManager)SoundManager.Instance).Device); } else { // we have only raw PCM encoded sound data (usually from a decoder) // convert the format settings WaveFormat wfo = new WaveFormat(); wfo.BitsPerSample = wf.Bits; wfo.Channels = wf.Channels; wfo.SamplesPerSecond = wf.Frequency; wfo.BlockAlign = (short)(wf.Bits*wf.Channels / 8); wfo.FormatTag = WaveFormatTag.Pcm; wfo.AverageBytesPerSecond = wf.Frequency * wfo.BlockAlign; // set up buffer properties soundDesc = new BufferDescription(wfo); soundDesc.GlobalFocus = false; soundDesc.ControlVolume = true; soundDesc.BufferBytes = (int)wf.Data.Length; // enable 3D features for 3D sounds if(type == Sound.THREED_SOUND) { soundDesc.Control3D = true; soundDesc.Mute3DAtMaximumDistance = true; } // initialise the buffer and copy the (raw data) stream into it sound = new SecondaryBuffer(soundDesc, ((DirectSoundManager)SoundManager.Instance).Device); sound.Write(0, wf.Data, (int)wf.Data.Length, LockFlag.EntireBuffer); } // create a 3D buffer for 3D sounds if(type == Sound.THREED_SOUND) { threeDsound = new Buffer3D(sound); threeDsound.Mode = Mode3D.Normal; threeDsound.Deferred = true; } }
public DX11RawBuffer(Device dev, int size, DX11RawBufferFlags flags= new DX11RawBufferFlags()) { this.Size = size; BufferDescription bd = new BufferDescription() { BindFlags = BindFlags.ShaderResource | BindFlags.UnorderedAccess, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.RawBuffer, SizeInBytes = this.Size, Usage = ResourceUsage.Default, }; this.Buffer = new Buffer(dev, bd); ShaderResourceViewDescription srvd = new ShaderResourceViewDescription() { Format = SlimDX.DXGI.Format.R32_Typeless, Dimension = ShaderResourceViewDimension.ExtendedBuffer, Flags = ShaderResourceViewExtendedBufferFlags.RawData, ElementCount = size / 4 }; this.SRV = new ShaderResourceView(dev, this.Buffer, srvd); UnorderedAccessViewDescription uavd = new UnorderedAccessViewDescription() { Format = SlimDX.DXGI.Format.R32_Typeless, Dimension = UnorderedAccessViewDimension.Buffer, Flags = UnorderedAccessViewBufferFlags.RawData, ElementCount = size / 4 }; this.UAV = new UnorderedAccessView(dev, this.Buffer, uavd); }
public SoundPlayer(Control owner, PullAudio pullAudio, string sample, short channels) { if (sample == null || File.Exists(sample) == false) return; this.channels = channels; this.pullAudio = pullAudio; this.samplefile = sample; this._owner = owner; this.soundDevice = new Device(); this.soundDevice.SetCooperativeLevel(_owner, CooperativeLevel.Priority); // Set up our wave format to 44,100Hz, with 16 bit resolution WaveFormat wf = new WaveFormat(); wf.FormatTag = WaveFormatTag.Pcm; wf.SamplesPerSecond = 44100; wf.BitsPerSample = 16; wf.Channels = channels; wf.BlockAlign = (short)(wf.Channels * wf.BitsPerSample / 8); wf.AverageBytesPerSecond = wf.SamplesPerSecond * wf.BlockAlign; this.samplesPerUpdate = 512; // Create a buffer with 2 seconds of sample data BufferDescription bufferDesc = new BufferDescription(); bufferDesc.BufferBytes = this.samplesPerUpdate * wf.BlockAlign * 2; bufferDesc.ControlPositionNotify = true; bufferDesc.GlobalFocus = true; bufferDesc.ControlFrequency = true; bufferDesc.ControlEffects = true; bufferDesc.ControlVolume = true; this.soundBuffer = new SecondaryBuffer(samplefile, bufferDesc, this.soundDevice); this.soundBuffer.Volume = 0; Notify notify = new Notify(this.soundBuffer); fillEvent[0] = new AutoResetEvent(false); fillEvent[1] = new AutoResetEvent(false); // Set up two notification events, one at halfway, and one at the end of the buffer BufferPositionNotify[] posNotify = new BufferPositionNotify[2]; posNotify[0] = new BufferPositionNotify(); posNotify[0].Offset = bufferDesc.BufferBytes / 2 - 1; posNotify[0].EventNotifyHandle = fillEvent[0].Handle; posNotify[1] = new BufferPositionNotify(); posNotify[1].Offset = bufferDesc.BufferBytes - 1; posNotify[1].EventNotifyHandle = fillEvent[1].Handle; notify.SetNotificationPositions(posNotify); this.thread = new Thread(new ThreadStart(SoundPlayback)); this.thread.Priority = ThreadPriority.Lowest; this.thread.IsBackground = true; this.Pause(); this.running = true; this.thread.Start(); }
public GameSound(System.Windows.Forms.Control Owner) { _bufferDesc = new BufferDescription(); _bufferDesc.GlobalFocus = true; _bufferDesc.Control3D = true; _soundDevice = new Device(); _soundDevice.SetCooperativeLevel(Owner, CooperativeLevel.Normal); }
public SecondaryBuffer GetBuffer(Microsoft.DirectX.DirectSound.Device device, string fileName) { BufferDescription bd = new BufferDescription(); bd.ControlEffects = false; bd.ControlPan = true; bd.ControlVolume = true; return new SecondaryBuffer(GetFileStream(fileName), bd, device); }
public SoundBox(System.Windows.Forms.Form frm, string soundFileName) { soundDevice = new Device(); soundDevice.SetCooperativeLevel(frm, CooperativeLevel.Normal); BufferDescription description = new BufferDescription(); description.ControlVolume = true; description.ControlEffects = false; sound = new SecondaryBuffer(soundFileName, description, soundDevice); soundList = new ArrayList(); }
/// <summary> /// Konstruktor parametrowy obiektu /// </summary> /// <param name="device">Uchwyt do karty dzwiekowej</param> /// <param name="fileName">Sciezka do pliku wav</param> /// <param name="position">Pozycja dzwieku w przestrzeni</param> public SoundBuffer(Device device, String fileName, Vector3 position) { BufferDescription description3D = new BufferDescription(); description3D.ControlEffects = false; description3D.Control3D = true; sound = new SecondaryBuffer(fileName, description3D, device); sound3D = new Buffer3D(sound); sound3D.Position = position; sound3D.MinDistance = 15f; }
public MdxListener(Device device) { BufferDescription desc = new BufferDescription(); desc.PrimaryBuffer = true; desc.Control3D = true; desc.Mute3DAtMaximumDistance = true; Microsoft.DirectX.DirectSound.Buffer buffer = new Microsoft.DirectX.DirectSound.Buffer(desc, device); _listener = new Listener3D(buffer); Orientation = Matrix.Identity; }
public static Buffer CreateStaticVertexBuffer( int nVertices, int vertexSizeBytes ) { var bd = new BufferDescription ( nVertices * vertexSizeBytes, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None ); return new Buffer( D3D10Wrapper.Instance.Device, bd ); }
public static Buffer CreateStagingBuffer( int nBytes ) { var bd = new BufferDescription ( nBytes, ResourceUsage.Staging, BindFlags.None, CpuAccessFlags.Read | CpuAccessFlags.Write, ResourceOptionFlags.None ); return new Buffer( D3D10Wrapper.Instance.Device, bd ); }
public Sound(string p_fileName, Device p_device) { this.device = p_device; this.fileName = p_fileName; this.desc = new BufferDescription(); this.desc.StaticBuffer = true; this.soundBuffer = new List<SecondaryBuffer>(); for (int i = 0; i < 3; i++) { this.soundBuffer.Add(new SecondaryBuffer(GameEngine.Framework.GetResourceStream(this.fileName), this.desc, this.device)); } }
public TerrainObject(TerrainRenderer renderer, Device renderingDevice) { this.renderingDevice = renderingDevice; this.renderer = renderer; // Default position Position = new Vector3(0, 20, 0); // Load textures noiseTexture = ShaderResourceView.FromFile(renderingDevice, renderer.Directory + "\\Resources\\Noise.dds"); grassTexture = ShaderResourceView.FromFile(renderingDevice, renderer.Directory + "\\Resources\\Grass.dds"); sandTexture = ShaderResourceView.FromFile(renderingDevice, renderer.Directory + "\\Resources\\Sand.dds"); snowTexture = ShaderResourceView.FromFile(renderingDevice, renderer.Directory + "\\Resources\\Snow.dds"); snowRockTexture = ShaderResourceView.FromFile(renderingDevice, renderer.Directory + "\\Resources\\SnowRock.dds"); // Create shader SetSourceCode(" float4 getColor(float4 position, float4 normal, float4 camera) { return float4(0, 0, 0, 0); } "); // Read data from file Vector3[] vertices; int[] indices; new XLoader().LoadFile(renderer.Directory + "\\Resources\\Terrain.X", out vertices, out indices); // DataStream vertexStream = new DataStream(vertices.Length * 12, true, true); vertexStream.WriteRange(vertices); vertexStream.Position = 0; DataStream indexStream = new DataStream(indices.Length * 4, true, true); indexStream.WriteRange(indices); indexStream.Position = 0; // BufferDescription vbufferDescription = new BufferDescription(); vbufferDescription.BindFlags = BindFlags.VertexBuffer; vbufferDescription.CpuAccessFlags = CpuAccessFlags.None; vbufferDescription.OptionFlags = ResourceOptionFlags.None; vbufferDescription.SizeInBytes = (int)vertexStream.Length; vbufferDescription.Usage = ResourceUsage.Immutable; vertexBuffer = new Buffer(renderingDevice, vertexStream, vbufferDescription); // BufferDescription ibufferDescription = new BufferDescription(); ibufferDescription.BindFlags = BindFlags.IndexBuffer; ibufferDescription.CpuAccessFlags = CpuAccessFlags.None; ibufferDescription.OptionFlags = ResourceOptionFlags.None; ibufferDescription.SizeInBytes = (int)indexStream.Length; ibufferDescription.Usage = ResourceUsage.Immutable; indexBuffer = new Buffer(renderingDevice, indexStream, ibufferDescription); indexCount = (int)indexStream.Length / 4; }
public Form1() { InitializeComponent(); //devList = new DevicesCollection(); // Populate cmbAudioCards // Create Device dSound = new Device();//devList[0].DriverGuid); dSound.SetCooperativeLevel(this.Handle, CooperativeLevel.Priority); d = new BufferDescription(); d.Flags = BufferDescriptionFlags.ControlVolume | BufferDescriptionFlags.ControlFrequency | BufferDescriptionFlags.ControlPan | BufferDescriptionFlags.ControlEffects; }
internal override void Draw(SlimDX.Direct3D11.DeviceContext context) { Effect effect; using (ShaderBytecode byteCode = ShaderBytecode.CompileFromFile("Graphics/Effects/default.fx", "bidon", "fx_5_0", ShaderFlags.OptimizationLevel3, EffectFlags.None)) { effect = new Effect(context.Device, byteCode); } var technique = effect.GetTechniqueByIndex(1); var pass = technique.GetPassByIndex(0); InputLayout inputLayout = new InputLayout(context.Device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32_Float, 0), new InputElement("COLOR", 0, SlimDX.DXGI.Format.R8G8B8A8_UNorm, InputElement.AppendAligned, 0) }); DataStream vertices = new DataStream((Vector3.SizeInBytes + 4) * 6, true, true); vertices.Write(new ColoredVertex(new Vector3(1.0f, 1.0f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 0.0f).ToArgb())); vertices.Write(new ColoredVertex(new Vector3(-1.0f, 1.0f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 0.0f).ToArgb())); vertices.Write(new ColoredVertex(new Vector3(-1.0f, -1.0f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 0.0f).ToArgb())); vertices.Write(new ColoredVertex(new Vector3(-1.0f, -1.0f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 0.0f).ToArgb())); vertices.Write(new ColoredVertex(new Vector3(1.0f, 1.0f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 0.0f).ToArgb())); vertices.Write(new ColoredVertex(new Vector3(1.0f, -1.0f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 0.0f).ToArgb())); vertices.Position = 0; BufferDescription bd = new BufferDescription() { Usage = ResourceUsage.Default, SizeInBytes = 16 * 6, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None }; var vertexBuffer = new SlimDX.Direct3D11.Buffer(context.Device, vertices, bd); context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 16, 0)); //context.InputAssembler.SetIndexBuffer(indices, Format.R16_UInt, 0); /* scale * rotation * translation */ Matrix worldMatrix = Matrix.Scaling(Scale) * Matrix.RotationYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) * Matrix.Translation(Position); Matrix viewMatrix = Camera.ViewMatrix; Matrix projectionMatrix = Camera.ProjectionMatrix; effect.GetVariableByName("finalMatrix").AsMatrix().SetMatrix(worldMatrix * viewMatrix * projectionMatrix); context.InputAssembler.InputLayout = inputLayout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip; pass.Apply(context); context.Draw(6, 0); }
public TgcDirectSound() { //Crear device de DirectSound dsDevice = new Device(); dsDevice.SetCooperativeLevel(GuiController.Instance.MainForm, CooperativeLevel.Normal); //Crear Listener3D BufferDescription primaryBufferDesc = new BufferDescription(); primaryBufferDesc.Control3D = true; primaryBufferDesc.PrimaryBuffer = true; primaryBuffer = new Microsoft.DirectX.DirectSound.Buffer(primaryBufferDesc, dsDevice); listener3d = new Listener3D(primaryBuffer); listener3d.Position = new Vector3(0f, 0f, 0f); listener3d.Orientation = new Listener3DOrientation(new Vector3(1, 0, 0), new Vector3(0, 1, 0)); }
public static Buffer CreateDynamicDataBuffer( int nElements, int elementSizeBytes ) { throw new NotImplementedException(); var bd = new BufferDescription ( nElements * elementSizeBytes, //ResourceUsage.Dynamic, ResourceUsage.Default, BindFlags.StreamOutput | BindFlags.ShaderResource, //CpuAccessFlags.None, CpuAccessFlags.Write, ResourceOptionFlags.None ); return new Buffer( D3D10Wrapper.Instance.Device, bd ); }
/// <summary> /// Initializes a new instance of the <see cref="Buffer" /> class. /// </summary> /// <param name="description">The description.</param> /// <param name="viewFlags">Type of the buffer.</param> /// <param name="viewFormat">The view format.</param> /// <param name="dataPointer">The data pointer.</param> protected Buffer InitializeFromImpl(BufferDescription description, BufferFlags viewFlags, PixelFormat viewFormat, IntPtr dataPointer) { bufferDescription = description; nativeDescription = ConvertToNativeDescription(Description); ViewFlags = viewFlags; InitCountAndViewFormat(out this.elementCount, ref viewFormat); ViewFormat = viewFormat; NativeDeviceChild = new SharpDX.Direct3D11.Buffer(GraphicsDevice.RootDevice.NativeDevice, dataPointer, nativeDescription); // Staging resource don't have any views if (nativeDescription.Usage != ResourceUsage.Staging) this.InitializeViews(); return this; }
public DirectSound(Control mainForm, int device, int samplesPerSecond, short bitsPerSample, short channels, int bufferSize, int bufferCount) { _fillQueue = new Queue(bufferCount); _playQueue = new Queue(bufferCount); for (int i = 0; i < bufferCount; i++) _fillQueue.Enqueue(new byte[bufferSize]); _bufferSize = bufferSize; _bufferCount = bufferCount; _zeroValue = bitsPerSample == 8 ? (byte)128 : (byte)0; _device = new Device(); _device.SetCooperativeLevel(mainForm, CooperativeLevel.Priority); WaveFormat wf = new WaveFormat(); wf.FormatTag = WaveFormatTag.Pcm; wf.SamplesPerSecond = samplesPerSecond; wf.BitsPerSample = bitsPerSample; wf.Channels = channels; wf.BlockAlign = (short)(wf.Channels * (wf.BitsPerSample / 8)); wf.AverageBytesPerSecond = (int)wf.SamplesPerSecond * (int)wf.BlockAlign; // Create a buffer BufferDescription bufferDesc = new BufferDescription(wf); bufferDesc.BufferBytes = _bufferSize * _bufferCount; bufferDesc.ControlPositionNotify = true; bufferDesc.GlobalFocus = true; _soundBuffer = new SecondaryBuffer(bufferDesc, _device); _notify = new Notify(_soundBuffer); BufferPositionNotify[] posNotify = new BufferPositionNotify[_bufferCount]; for (int i = 0; i < posNotify.Length; i++) { posNotify[i] = new BufferPositionNotify(); posNotify[i].Offset = i * _bufferSize; posNotify[i].EventNotifyHandle = _fillEvent.SafeWaitHandle.DangerousGetHandle(); } _notify.SetNotificationPositions(posNotify); _waveFillThread = new Thread(new ThreadStart(waveFillThreadProc)); _waveFillThread.IsBackground = true; _waveFillThread.Name = "Wave fill thread"; _waveFillThread.Priority = ThreadPriority.Highest; _waveFillThread.Start(); }
public void TestMethod1() { // Set up wave format WaveFormat waveFormat = new WaveFormat(); waveFormat.FormatTag = WaveFormatTag.Pcm; waveFormat.Channels = 1; waveFormat.BitsPerSample = 16; waveFormat.SamplesPerSecond = 44100; waveFormat.BlockAlign = (short) ( waveFormat.Channels * waveFormat.BitsPerSample / 8 ); waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * waveFormat.SamplesPerSecond; // Set up buffer description BufferDescription bufferDesc = new BufferDescription( waveFormat ); bufferDesc.Control3D = false; bufferDesc.ControlEffects = false; bufferDesc.ControlFrequency = true; bufferDesc.ControlPan = true; bufferDesc.ControlVolume = true; bufferDesc.DeferLocation = true; bufferDesc.GlobalFocus = true; Device d = new Device(); d.SetCooperativeLevel( new System.Windows.Forms.Control(), CooperativeLevel.Priority ); int samples = 5 * waveFormat.SamplesPerSecond * waveFormat.Channels; char[] buffer = new char[samples]; // Set buffer length bufferDesc.BufferBytes = buffer.Length * waveFormat.BlockAlign; // Set initial amplitude and frequency double frequency = 500; double amplitude = short.MaxValue / 3; double two_pi = 2 * Math.PI; // Iterate through time for( int i = 0; i < buffer.Length; i++ ) { // Add to sine buffer[i] = (char) ( amplitude * Math.Sin( i * two_pi * frequency / waveFormat.SamplesPerSecond ) ); } SecondaryBuffer bufferSound = new SecondaryBuffer( bufferDesc, d ); bufferSound.Volume = (int) Volume.Max; bufferSound.Write( 0, buffer, LockFlag.None ); bufferSound.Play( 0, BufferPlayFlags.Default ); System.Threading.Thread.Sleep( 10000 ); }
// Static functions static public GPUBufferObject CreateBuffer(Device device, int size, int elementSizeInBytes, DataStream stream = null, bool append = false, bool allowStaging = false) { GPUBufferObject newBuffer = new GPUBufferObject(); // Variables newBuffer.m_Size = size; BindFlags bindFlags = BindFlags.ShaderResource | BindFlags.UnorderedAccess; BufferDescription description = new BufferDescription(size * elementSizeInBytes, ResourceUsage.Default, bindFlags, CpuAccessFlags.None, ResourceOptionFlags.StructuredBuffer, elementSizeInBytes); newBuffer.m_BufferObject = stream != null ? new Buffer(device, stream, description) : new Buffer(device, description); ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription { FirstElement = 0, ElementCount = size, Format = Format.Unknown, Dimension = ShaderResourceViewDimension.ExtendedBuffer, Flags = 0, }; newBuffer.m_ShaderResourceView = new ShaderResourceView(device, newBuffer.m_BufferObject, srvViewDesc); UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription { ArraySize = 0, Dimension = UnorderedAccessViewDimension.Buffer, ElementCount = size, Flags = append ? UnorderedAccessViewBufferFlags.AllowAppend : UnorderedAccessViewBufferFlags.None, Format = Format.Unknown, MipSlice = 0 }; newBuffer.m_UnorderedAccessView = new UnorderedAccessView(device, newBuffer.m_BufferObject, uavDesc); if (allowStaging) { description = new BufferDescription(size * elementSizeInBytes, ResourceUsage.Staging, BindFlags.None, CpuAccessFlags.Read, ResourceOptionFlags.StructuredBuffer, elementSizeInBytes); newBuffer.m_StagingBufferObject = new Buffer(device, description); description = new BufferDescription(16, ResourceUsage.Staging, BindFlags.None, CpuAccessFlags.Read, ResourceOptionFlags.None, 4); newBuffer.m_StagingCountBufferObject = new Buffer(device, description); } return newBuffer; }
private bool InitializeShader(Device device, IntPtr windowsHandler, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName; psFileName = DSystemConfiguration.ShaderFilePath + psFileName; // Compile the Vertex Shader & Pixel Shader code. ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "LightVertexShader", DSystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None); ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "LightPixelShader", DSystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None); // Create the Vertex & Pixel Shaders from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. InputElement[] inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "NORMAL", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Kin dof like a Vertex Declaration. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Create a texture sampler state description. SamplerStateDescription samplerDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), // Black Border. MinimumLod = 0, MaximumLod = float.MaxValue }; // Create the texture sampler state. SamplerState = new SamplerState(device, samplerDesc); // Setup the description of the dynamic matrix constant Matrix buffer that is in the vertex shader. BufferDescription matrixBufferDescription = new BufferDescription() { Usage = ResourceUsage.Dynamic, // ResourceUsage.Default SizeInBytes = Utilities.SizeOf <DMatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, // CpuAccessFlags.None OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDescription); //// Setup the description of the camera dynamic constant buffer that is in the vertex shader. //var cameraBufferDesc = new BufferDescription() //{ // Usage = ResourceUsage.Dynamic, // SizeInBytes = Utilities.SizeOf<DCameraBuffer>(), // BindFlags = BindFlags.ConstantBuffer, // CpuAccessFlags = CpuAccessFlags.Write, // OptionFlags = ResourceOptionFlags.None, // StructureByteStride = 0 //}; //// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. //ConstantCameraBuffer = new SharpDX.Direct3D11.Buffer(device, cameraBufferDesc); // Setup the description of the light dynamic constant bufffer that is in the pixel shader. // Note that ByteWidth alwalys needs to be a multiple of the 16 if using D3D11_BIND_CONSTANT_BUFFER or CreateBuffer will fail. BufferDescription lightBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DLightBuffer>(), // Must be divisable by 16 bytes, so this is equated to 32. BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantLightBuffer = new SharpDX.Direct3D11.Buffer(device, lightBufferDesc); return(true); } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return(false); } }
private void CreateResources() { { var desc = new BufferDescription { Usage = ResourceUsage.Default, SizeInBytes = 1024, BindFlags = BindFlags.VertexBuffer, }; m_VB = new Buffer(m_Device, desc); } { var desc = new BufferDescription { Usage = ResourceUsage.Default, SizeInBytes = 64, // hold 1 matrix BindFlags = BindFlags.ConstantBuffer, }; m_CB = new Buffer(m_Device, desc); } { m_VertexShader = new VertexShader(m_Device, kVertexShaderCode); m_PixelShader = new PixelShader(m_Device, kPixelShaderCode); } { var m_DX11InputElementDesc = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 0), }; m_InputLayout = new InputLayout(m_Device, kVertexShaderCode, m_DX11InputElementDesc); } { var rsdesc = new RasterizerStateDescription { FillMode = FillMode.Solid, CullMode = CullMode.None, IsDepthClipEnabled = true, }; m_RasterState = new RasterizerState(m_Device, rsdesc); } { var dsdesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = GetUsesReverseZ() ? Comparison.GreaterEqual : Comparison.LessEqual, }; m_DepthState = new DepthStencilState(m_Device, dsdesc); } { var bdesc = new BlendStateDescription(); bdesc.RenderTarget[0].IsBlendEnabled = false; bdesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; m_BlendState = new BlendState(m_Device, bdesc); } }
private static void PlayThread(object osn) { EmulatorForm myform = (EmulatorForm)osn; SecondaryBuffer SecBuf; AutoResetEvent SecBufNotifyAtHalf = new AutoResetEvent(false); AutoResetEvent SecBufNotifyAtBeginning = new AutoResetEvent(false); int SamplingRate = (int)myform._samplingRate; int HoldThisManySamples = (int)(1 * SamplingRate); int BlockAlign = 2; int SecBufByteSize = HoldThisManySamples * BlockAlign; WaveFormat MyWaveFormat = new WaveFormat(); // Set the format MyWaveFormat.AverageBytesPerSecond = (int)(myform._samplingRate * BlockAlign); MyWaveFormat.BitsPerSample = (short)16; MyWaveFormat.BlockAlign = (short)BlockAlign; MyWaveFormat.Channels = (short)1; MyWaveFormat.SamplesPerSecond = (int)myform._samplingRate; MyWaveFormat.FormatTag = WaveFormatTag.Pcm; BufferDescription MyDescription; // Set BufferDescription MyDescription = new BufferDescription(); MyDescription.Format = MyWaveFormat; MyDescription.BufferBytes = HoldThisManySamples * BlockAlign; MyDescription.CanGetCurrentPosition = true; MyDescription.ControlPositionNotify = true; MyDescription.GlobalFocus = true; // Create the buffer SecBuf = new SecondaryBuffer(MyDescription, myform._directSoundDevice); Notify MyNotify; MyNotify = new Notify(SecBuf); BufferPositionNotify[] MyBufferPositions = new BufferPositionNotify[2]; MyBufferPositions[0].Offset = 0; MyBufferPositions[0].EventNotifyHandle = SecBufNotifyAtBeginning.Handle; MyBufferPositions[1].Offset = (HoldThisManySamples / 2) * BlockAlign; MyBufferPositions[1].EventNotifyHandle = SecBufNotifyAtHalf.Handle; MyNotify.SetNotificationPositions(MyBufferPositions); WaitHandle[] SecBufWaitHandles = { SecBufNotifyAtBeginning, SecBufNotifyAtHalf }; Int16[] buffer; buffer = myform._sn.GenerateSamples((uint)HoldThisManySamples, ""); SecBuf.Write(0, buffer, LockFlag.None); SecBuf.Play(0, BufferPlayFlags.Looping); int SecBufNextWritePosition = 0; while (myform._bufferPlaying) { int WriteCount = 0, PlayPosition = SecBuf.PlayPosition, WritePosition = SecBuf.WritePosition; if (SecBufNextWritePosition < PlayPosition && (WritePosition >= PlayPosition || WritePosition < SecBufNextWritePosition)) { WriteCount = PlayPosition - SecBufNextWritePosition; } else if (SecBufNextWritePosition > WritePosition && WritePosition >= PlayPosition) { WriteCount = (SecBufByteSize - SecBufNextWritePosition) + PlayPosition; } // System.Diagnostics.Debug.WriteLine("WC: "+WriteCount.ToString()); if (WriteCount > 0) { WriteCount = (int)Math.Min(WriteCount, 1000); buffer = myform._sn.GenerateSamples((uint)WriteCount / 2, ""); SecBuf.Write( SecBufNextWritePosition, buffer, LockFlag.None); SecBufNextWritePosition = (SecBufNextWritePosition + WriteCount) % SecBufByteSize; } else { WaitHandle.WaitAny(SecBufWaitHandles, new TimeSpan(0, 0, 5), true); } } SecBuf.Dispose(); MyDescription.Dispose(); MyNotify.Dispose(); }
public override void Initialize() { Form.SizeChanged += (o, args) => { if (_swapChain == null) { return; } renderView.Dispose(); depthView.Dispose(); DisposeBuffers(); if (Form.WindowState == FormWindowState.Minimized) { return; } _width = Form.ClientSize.Width; _height = Form.ClientSize.Height; _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0); CreateBuffers(); SetSceneConstants(); }; _width = 1024; _height = 768; _nearPlane = 1.0f; ambient = new Color4(Color.Gray.ToArgb()); try { OnInitializeDevice(); } catch (Exception e) { MessageBox.Show(e.ToString(), "Could not create DirectX 10 device."); return; } // shader.fx const ShaderFlags shaderFlags = ShaderFlags.None; //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization; ShaderBytecode shaderByteCode = LoadShader("shader.fx", shaderFlags); effect = new Effect(_device, shaderByteCode); EffectTechnique technique = effect.GetTechniqueByIndex(0); shadowGenPass = technique.GetPassByIndex(0); gBufferGenPass = technique.GetPassByIndex(1); debugDrawPass = technique.GetPassByName("debug"); BufferDescription sceneConstantsDesc = new BufferDescription() { SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None }; sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc); EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene"); effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer); _rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullingEnabled ? CullMode.Back : CullMode.None, FillMode = FillMode.Solid, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, }; _device.Rasterizer.State = new RasterizerState(_device, _rasterizerStateDesc); DepthStencilStateDescription depthDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; depthStencilState = new DepthStencilState(_device, depthDesc); DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc); // grender.fx shaderByteCode = LoadShader("grender.fx", shaderFlags); effect2 = new Effect(_device, shaderByteCode); technique = effect2.GetTechniqueByIndex(0); gBufferRenderPass = technique.GetPassByIndex(0); gBufferOverlayPass = technique.GetPassByIndex(1); info = new InfoText(_device); _meshFactory = new MeshFactory(this); MeshFactory = _meshFactory; CreateBuffers(); GraphicsLibraryManager.LibraryStarted(); }
public void CreateDeviceDependentResourcesAsync(DeviceResources deviceResources) { byte[] bytes = Convert.FromBase64String(spriteImg); Stream stream = new MemoryStream(bytes); var factory = new SharpDX.WIC.ImagingFactory2(); var bitmapDecoder = new SharpDX.WIC.BitmapDecoder( factory, stream, SharpDX.WIC.DecodeOptions.CacheOnDemand ); var formatConverter = new SharpDX.WIC.FormatConverter(factory); formatConverter.Initialize( bitmapDecoder.GetFrame(0), SharpDX.WIC.PixelFormat.Format32bppPRGBA, SharpDX.WIC.BitmapDitherType.None, null, 0.0, SharpDX.WIC.BitmapPaletteType.Custom); SharpDX.WIC.BitmapSource bitmapSource = formatConverter; imageWidth = bitmapSource.Size.Width; imageHeight = bitmapSource.Size.Height; var height = bitmapSource.Size.Height * Spritesheet.textureScaleFactor; var width = bitmapSource.Size.Width * Spritesheet.textureScaleFactor; BlendStateDescription blendSdesc = new BlendStateDescription(); blendSdesc.IndependentBlendEnable = false; blendSdesc.AlphaToCoverageEnable = false; blendSdesc.RenderTarget[0].IsBlendEnabled = true; blendSdesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; blendSdesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; blendSdesc.RenderTarget[0].BlendOperation = BlendOperation.Add; blendSdesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; blendSdesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; blendSdesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; blendSdesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; BlendState blendS = new BlendState(deviceResources.D3DDevice, blendSdesc); deviceResources.D3DDeviceContext.OutputMerger.SetBlendState(blendS); // Load mesh vertices. Each vertex has a position and a color. // Note that the cube size has changed from the default DirectX app // template. Windows Holographic is scaled in meters, so to draw the // cube at a comfortable size we made the cube width 0.2 m (20 cm). VertexPositionTexture[] cubeVertices = { new VertexPositionTexture(new System.Numerics.Vector3(-1f * width, -1f * height, 0f), new System.Numerics.Vector2(0.0f, 1.0f)), new VertexPositionTexture(new System.Numerics.Vector3(1f * width, -1f * height, 0f), new System.Numerics.Vector2(1.0f, 1.0f)), new VertexPositionTexture(new System.Numerics.Vector3(-1f * width, 1f * height, 0f), new System.Numerics.Vector2(0.0f, 0.0f)), new VertexPositionTexture(new System.Numerics.Vector3(1f * width, 1f * height, 0f), new System.Numerics.Vector2(1.0f, 0.0f)) }; BufferDescription mdescription = new BufferDescription(sizeof(float) * 5 * cubeVertices.Length, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); vertexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, cubeVertices, mdescription)); //vertexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( // deviceResources.D3DDevice, // SharpDX.Direct3D11.BindFlags.VertexBuffer, // cubeVertices, // 0, // ResourceUsage.Dynamic, CpuAccessFlags.Write)); // Load mesh indices. Each trio of indices represents // a triangle to be rendered on the screen. // For example: 0,2,1 means that the vertices with indexes // 0, 2 and 1 from the vertex buffer compose the // first triangle of this mesh. ushort[] cubeIndices = { 2, 1, 0, // -x 2, 3, 1, //back face 2, 0, 1, // -x 2, 1, 3, }; indexCount = cubeIndices.Length; indexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.IndexBuffer, cubeIndices)); // Create a constant buffer to store the model matrix. modelConstantBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.ConstantBuffer, ref modelConstantBufferData)); //Load the image Texture2D texture = TextureLoader.CreateTexture2DFromBitmap(deviceResources.D3DDevice, bitmapSource); textureView = new ShaderResourceView(deviceResources.D3DDevice, texture); deviceResources.D3DDeviceContext.PixelShader.SetShaderResource(0, textureView); //Load the sampler SamplerStateDescription samplerDesc = new SamplerStateDescription(); samplerDesc.AddressU = TextureAddressMode.Wrap; samplerDesc.AddressV = TextureAddressMode.Wrap; samplerDesc.AddressW = TextureAddressMode.Wrap; samplerDesc.ComparisonFunction = Comparison.Never; samplerDesc.Filter = Filter.MinMagMipLinear; samplerDesc.MaximumLod = float.MaxValue; SamplerState sampler = new SamplerState(deviceResources.D3DDevice, samplerDesc); deviceResources.D3DDeviceContext.PixelShader.SetSampler(0, sampler); hasLoaded = true; }
private void BuildMeshGeometryBuffers() { try { var min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); var max = new Vector3(float.MinValue, float.MinValue, float.MinValue); _meshVertices = new List <Basic32>(); _meshIndices = new List <int>(); var vcount = 0; var tcount = 0; using (var reader = new StreamReader("Models\\car.txt")) { var input = reader.ReadLine(); if (input != null) { // VertexCount: X vcount = Convert.ToInt32(input.Split(new[] { ':' })[1].Trim()); } input = reader.ReadLine(); if (input != null) { //TriangleCount: X tcount = Convert.ToInt32(input.Split(new[] { ':' })[1].Trim()); } // skip ahead to the vertex data do { input = reader.ReadLine(); } while (input != null && !input.StartsWith("{")); // Get the vertices for (int i = 0; i < vcount; i++) { input = reader.ReadLine(); if (input != null) { var vals = input.Split(new[] { ' ' }); var position = new Vector3(Convert.ToSingle(vals[0].Trim()), Convert.ToSingle(vals[1].Trim()), Convert.ToSingle(vals[2].Trim())); _meshVertices.Add( new Basic32( position, new Vector3( Convert.ToSingle(vals[3].Trim()), Convert.ToSingle(vals[4].Trim()), Convert.ToSingle(vals[5].Trim())), new Vector2() ) ); min = Vector3.Minimize(min, position); max = Vector3.Maximize(max, position); } } _meshBox = new BoundingBox(min, max); // skip ahead to the index data do { input = reader.ReadLine(); } while (input != null && !input.StartsWith("{")); // Get the indices _meshIndexCount = 3 * tcount; for (var i = 0; i < tcount; i++) { input = reader.ReadLine(); if (input == null) { break; } var m = input.Trim().Split(new[] { ' ' }); _meshIndices.Add(Convert.ToInt32(m[0].Trim())); _meshIndices.Add(Convert.ToInt32(m[1].Trim())); _meshIndices.Add(Convert.ToInt32(m[2].Trim())); } } var vbd = new BufferDescription(Basic32.Stride * vcount, ResourceUsage.Immutable, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); _meshVB = new Buffer(Device, new DataStream(_meshVertices.ToArray(), false, false), vbd); var ibd = new BufferDescription(sizeof(int) * _meshIndexCount, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); _meshIB = new Buffer(Device, new DataStream(_meshIndices.ToArray(), false, false), ibd); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void PlayFile(FileInfo FI) { lock (this) { if (this.AudioDevice == null) { this.AudioDevice = new Device(); AudioDevice.SetCooperativeLevel(this, CooperativeLevel.Normal); } this.StopPlayback(); WaveFormat fmt = new WaveFormat(); fmt.FormatTag = WaveFormatTag.Pcm; fmt.Channels = FI.AudioFile.Channels; fmt.SamplesPerSecond = FI.AudioFile.SampleRate; fmt.BitsPerSample = 16; fmt.BlockAlign = (short)(FI.AudioFile.Channels * (fmt.BitsPerSample / 8)); fmt.AverageBytesPerSecond = fmt.SamplesPerSecond * fmt.BlockAlign; BufferDescription BD = new BufferDescription(fmt); BD.BufferBytes = this.AudioBufferSize; BD.GlobalFocus = true; BD.StickyFocus = true; if (this.chkBufferedPlayback.Checked) { BD.ControlPositionNotify = true; this.CurrentBuffer = new SecondaryBuffer(BD, this.AudioDevice); if (this.AudioUpdateTrigger == null) { this.AudioUpdateTrigger = new AutoResetEvent(false); } int ChunkSize = this.AudioBufferSize / this.AudioBufferMarkers; BufferPositionNotify[] UpdatePositions = new BufferPositionNotify[this.AudioBufferMarkers]; for (int i = 0; i < this.AudioBufferMarkers; ++i) { UpdatePositions[i] = new BufferPositionNotify(); UpdatePositions[i].EventNotifyHandle = this.AudioUpdateTrigger.SafeWaitHandle.DangerousGetHandle(); UpdatePositions[i].Offset = ChunkSize * i; } Notify N = new Notify(this.CurrentBuffer); N.SetNotificationPositions(UpdatePositions); this.CurrentStream = FI.AudioFile.OpenStream(); this.CurrentBuffer.Write(0, this.CurrentStream, this.CurrentBuffer.Caps.BufferBytes, LockFlag.EntireBuffer); if (this.CurrentStream.Position < this.CurrentStream.Length) { this.AudioUpdateTrigger.Reset(); this.AudioUpdateThread = new Thread(new ThreadStart(this.AudioUpdate)); this.AudioUpdateThread.Start(); this.btnPause.Enabled = true; this.btnStop.Enabled = true; this.AudioIsLooping = true; } else { this.CurrentStream.Close(); this.CurrentStream = null; this.AudioIsLooping = false; } } else { this.CurrentStream = FI.AudioFile.OpenStream(true); this.CurrentBuffer = new SecondaryBuffer(this.CurrentStream, BD, this.AudioDevice); this.btnPause.Enabled = true; this.btnStop.Enabled = true; } this.CurrentBuffer.Play(0, (this.AudioIsLooping ? BufferPlayFlags.Looping : BufferPlayFlags.Default)); } }
public override void Initialize() { Form.SizeChanged += (o, args) => { if (_swapChain == null) { return; } renderView.Dispose(); depthView.Dispose(); DisposeBuffers(); if (Form.WindowState == FormWindowState.Minimized) { return; } _width = Form.ClientSize.Width; _height = Form.ClientSize.Height; _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0); CreateBuffers(); SetSceneConstants(); }; _width = 1024; _height = 768; _nearPlane = 0.1f; try { OnInitializeDevice(); } catch (Exception e) { MessageBox.Show(e.ToString(), "Could not create DirectX 11 device."); return; } // shader.fx const ShaderFlags shaderFlags = ShaderFlags.None; //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization; string[] sources = { "shader.fx", "grender.fx" }; using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), sources, shaderFlags)) { effect = new Effect(Device, shaderByteCode); } EffectTechnique technique = effect.GetTechniqueByName("GBufferCreate"); shadowGenPass = technique.GetPassByName("ShadowMap"); gBufferGenPass = technique.GetPassByName("GBufferGen"); debugDrawPass = technique.GetPassByName("DebugDraw"); var sceneConstantsDesc = new BufferDescription { SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None }; sceneConstantsBuffer = new Buffer(Device, sceneConstantsDesc); EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene"); effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer); var _rasterizerStateDesc = new RasterizerStateDescription { CullMode = CullMode.None, FillMode = FillMode.Solid, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, }; noCullState = new RasterizerState(Device, _rasterizerStateDesc); _rasterizerStateDesc.CullMode = CullMode.Back; backCullState = new RasterizerState(Device, _rasterizerStateDesc); _rasterizerStateDesc.CullMode = CullMode.Front; frontCullState = new RasterizerState(Device, _rasterizerStateDesc); _immediateContext.Rasterizer.State = CullingEnabled ? backCullState : noCullState; var depthDesc = new DepthStencilStateDescription { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; depthState = new DepthStencilState(Device, depthDesc); depthDesc.DepthWriteMask = DepthWriteMask.Zero; outsideLightVolumeDepthState = new DepthStencilState(Device, depthDesc); depthDesc.DepthComparison = Comparison.Greater; insideLightVolumeDepthState = new DepthStencilState(Device, depthDesc); var lightDepthStateDesc = new DepthStencilStateDescription { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; lightDepthStencilState = new DepthStencilState(Device, lightDepthStateDesc); // grender.fx technique = effect.GetTechniqueByName("DeferredShader"); gBufferRenderPass = technique.GetPassByName("DeferredShader"); gBufferPostProcessPass = technique.GetPassByName("Blur"); gBufferPostProcessPass2 = technique.GetPassByName("PostProcess"); gBufferOverlayPass = technique.GetPassByName("Overlay"); lightBufferVar = effect.GetVariableByName("lightBuffer").AsShaderResource(); normalBufferVar = effect.GetVariableByName("normalBuffer").AsShaderResource(); diffuseBufferVar = effect.GetVariableByName("diffuseBuffer").AsShaderResource(); depthMapVar = effect.GetVariableByName("depthMap").AsShaderResource(); shadowLightDepthBufferVar = effect.GetVariableByName("lightDepthMap").AsShaderResource(); sunLightDirectionVar = effect.GetVariableByName("SunLightDirection").AsVector(); viewportWidthVar = effect.GetVariableByName("ViewportWidth").AsScalar(); viewportHeightVar = effect.GetVariableByName("ViewportHeight").AsScalar(); viewParametersVar = effect.GetVariableByName("ViewParameters").AsVector(); overlayViewProjectionVar = effect.GetVariableByName("OverlayViewProjection").AsMatrix(); // light.fx using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), "light.fx", shaderFlags)) { lightShader = new Effect(Device, shaderByteCode); } technique = lightShader.GetTechniqueByIndex(0); lightAccumulationPass = technique.GetPassByName("Light"); lightWorldVar = lightShader.GetVariableByName("World").AsMatrix(); lightPositionRadiusVar = lightShader.GetVariableByName("PositionRadius").AsVector(); lightColorVar = lightShader.GetVariableByName("Color").AsVector(); lightProjectionVar = lightShader.GetVariableByName("Projection").AsMatrix(); lightViewVar = lightShader.GetVariableByName("View").AsMatrix(); lightViewInverseVar = lightShader.GetVariableByName("ViewInverse").AsMatrix(); lightViewportWidthVar = lightShader.GetVariableByName("ViewportWidth").AsScalar(); lightViewportHeightVar = lightShader.GetVariableByName("ViewportHeight").AsScalar(); lightEyePositionVar = lightShader.GetVariableByName("EyePosition").AsVector(); lightViewParametersVar = lightShader.GetVariableByName("ViewParameters").AsVector(); var elements = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), }; lightVolumeInputLayout = new InputLayout(Device, lightShader.GetTechniqueByIndex(0).GetPassByName("Light").Description.Signature, elements); pointLightVolumeVertices = Light.CreatePointLightVolume(out pointLightVolumeIndices); var vertexBufferDesc = new BufferDescription { SizeInBytes = Vector3.SizeInBytes * pointLightVolumeVertices.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.VertexBuffer, }; using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(pointLightVolumeVertices); data.Position = 0; pointLightVolumeVertexBuffer = new Buffer(Device, data, vertexBufferDesc); } pointLightVolumeVertexBufferBinding = new VertexBufferBinding(pointLightVolumeVertexBuffer, 12, 0); var indexBufferDesc = new BufferDescription { SizeInBytes = sizeof(uint) * pointLightVolumeIndices.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.IndexBuffer }; using (var data = new DataStream(indexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(pointLightVolumeIndices); data.Position = 0; pointLightVolumeIndexBuffer = new Buffer(Device, data, indexBufferDesc); } lightDepthBufferVar = lightShader.GetVariableByName("depthBuffer").AsShaderResource(); lightNormalBufferVar = lightShader.GetVariableByName("normalBuffer").AsShaderResource(); lights.Add(new Light(pointLightPosition, 60, new Vector4(1, 0.95f, 0.9f, 1))); //lights.Add(new Light(pointLightPosition, 60, new Vector4(0, 0, 1, 1))); //lights.Add(new Light(new Vector3(-10, 10, 10), 30, new Vector4(1, 0, 0, 1))); //lights.Add(new Light(new Vector3(10, 5, -10), 20, new Vector4(0, 1, 0, 1))); //lights.Add(new Light(new Vector3(-10, 5, -10), 20, new Vector4(1, 0, 1, 1))); info = new InfoText(Device, 256, 256); _meshFactory = new MeshFactory(this); MeshFactory = _meshFactory; CreateBuffers(); GraphicsLibraryManager.LibraryStarted(); }
private bool InitializeShader(SharpDX.Direct3D11.Device device, IntPtr windowHandler, string vsFileName, string psFileName) { try { #region Input Layout Configuration // Setup full paths vsFileName = DSystemConfiguration.FontFilePath + vsFileName; psFileName = DSystemConfiguration.FontFilePath + psFileName; // Compile the vertex shader code. var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "FontVertexShader", "vs_4_0", ShaderFlags.EnableStrictness, EffectFlags.None); // Compile the pixel shader code. var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "FontPixelShader", "ps_4_0", ShaderFlags.EnableStrictness, EffectFlags.None); // Create the vertex shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); // Create the pixel shader from the buffer. PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. var inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = Format.R32G32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); #endregion #region Matrix Constant Buffer // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DMatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDesc); #endregion #region Sampler State // Create a texture sampler state description. var samplerDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), MinimumLod = 0, MaximumLod = float.MaxValue }; // Create the texture sampler state. SamplerState = new SamplerState(device, samplerDesc); #endregion #region Pixel Constant Buffer // Setup the description of the dynamic pixel constant buffer that is in the pixel shader. var pixelBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DPixelBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantPixelBuffer = new SharpDX.Direct3D11.Buffer(device, pixelBufferDesc); #endregion return(true); } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return(false); }; }
private bool InitializeShader(Device device, IntPtr hwnd, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName; psFileName = DSystemConfiguration.ShaderFilePath + psFileName; // Compile the Vertex & Pixel Shader code. ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "SkyDomeVertexShader", DSystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None); ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "SkyDomePixelShader", DSystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None); // Create the Vertex & Pixel Shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); // Create the vertex input layout description. InputElement[] inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. BufferDescription matrixBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DMatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDesc); // Setup the description of the gradient constant buffer that is in the pixel shader. BufferDescription gradientBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DGradientBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class. ConstantGradientBuffer = new SharpDX.Direct3D11.Buffer(device, gradientBufferDesc); return(true); } catch { return(false); } }
private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = SystemConfiguration.ShadersFilePath + vsFileName; psFileName = SystemConfiguration.ShadersFilePath + psFileName; // Compile the vertex shader code. var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None); // Compile the pixel shader code. var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None); // Create the vertex shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); // Create the pixel shader from the buffer. PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. var inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "COLOR", SemanticIndex = 0, Format = Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = ColorShader.Vertex.AppendAlignedElement, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <Matrix>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc); return(true); } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return(false); }; }
void InitPlay(long lStartPosition, long lEndPosition) { { // Adjust the start and end position according to frame size lStartPosition = Calc.AdaptToFrame(lStartPosition, m_Asset.FrameSize); lEndPosition = Calc.AdaptToFrame(lEndPosition, m_Asset.FrameSize); m_SamplingRate = m_Asset.SampleRate; // lEndPosition = 0 means that file is played to end if (lEndPosition != 0) { m_lLength = (lEndPosition) - lStartPosition; } else { m_lLength = (m_Asset.SizeInBytes - lStartPosition); } WaveFormat newFormat = new WaveFormat(); BufferDesc = new BufferDescription(); // retrieve format from file m_FrameSize = m_Asset.FrameSize; m_Channels = m_Asset.Channels; newFormat.AverageBytesPerSecond = m_Asset.SampleRate * m_Asset.FrameSize; newFormat.BitsPerSample = Convert.ToInt16(m_Asset.BitDepth); newFormat.BlockAlign = Convert.ToInt16(m_Asset.FrameSize); newFormat.Channels = Convert.ToInt16(m_Asset.Channels); newFormat.FormatTag = WaveFormatTag.Pcm; newFormat.SamplesPerSecond = m_Asset.SampleRate; // loads format to buffer description BufferDesc.Format = newFormat; // calculate size of buffer so as to contain 1 second of audio m_SizeBuffer = m_Asset.SampleRate * m_Asset.FrameSize; if (m_SizeBuffer > m_lLength) { m_SizeBuffer = Convert.ToInt32(m_lLength); } m_RefreshLength = (m_Asset.SampleRate / 2) * m_Asset.FrameSize; // calculate the size of VuMeter Update array length m_UpdateVMArrayLength = m_SizeBuffer / 20; m_UpdateVMArrayLength = Convert.ToInt32(Calc.AdaptToFrame(Convert.ToInt32(m_UpdateVMArrayLength), m_FrameSize)); arUpdateVM = new byte [m_UpdateVMArrayLength]; // reset the VuMeter ob_VuMeter.Reset(); // sets the calculated size of buffer BufferDesc.BufferBytes = m_SizeBuffer; // Global focus is set to true so that the sound can be played in background also BufferDesc.GlobalFocus = true; // initialising secondary buffer SoundBuffer = new SecondaryBuffer(BufferDesc, SndDevice); // Compensate played length due to the skip of frames during compression if (m_Step != 1) { m_CompAddition = (m_RefreshLength * 2) / m_Step; m_CompAddition = Convert.ToInt32(Calc.AdaptToFrame(m_CompAddition, m_FrameSize)); } // Load from file to memory LoadStream(true); // check for fast play int reduction = 0; if (m_FastPlay == false) { SoundBuffer.Write(0, m_MemoryStream, m_SizeBuffer, 0); } else { // for fast play buffer is filled in parts with new part overlapping previous part for (int i = 0; i < m_SizeBuffer; i = i + (m_Step * m_FrameSize)) { SoundBuffer.Write(i, m_MemoryStream, m_Step * m_FrameSize, 0); i = i - (2 * m_FrameSize); // compute the difference in bytes skipped reduction = reduction + (2 * m_FrameSize); } } // Adds the length (count) of file played into a variable m_lPlayed = m_SizeBuffer + reduction + (2 * m_CompAddition); m_PlayFile = true; // trigger events StateChanged ob_StateChanged = new StateChanged(m_State); m_State = AudioPlayerState.Playing; TriggerStateChangedEvent(ob_StateChanged); // starts playing SoundBuffer.Play(0, BufferPlayFlags.Looping); m_BufferCheck = 1; //initialise and start thread for refreshing buffer RefreshThread = new Thread(new ThreadStart(RefreshBuffer)); RefreshThread.Start(); // end of playing check } // end of function }
public VkVertexBuffer(VkGraphicsDevice gd, ref BufferDescription description) : base(gd, description.SizeInBytes, description.Dynamic, Vulkan.VkBufferUsageFlags.VertexBuffer) { }
private void LoadSoundFile(string FileName) { BufferDescription description = new BufferDescription(); WaveFormat wf = new WaveFormat(); buttonPlay.Enabled = false; buttonStop.Enabled = false; labelStatus.Text = "Loading file..."; description.Guid3DAlgorithm = guid3DAlgorithm; description.Control3D = true; if (null != applicationBuffer) { applicationBuffer.Stop(); applicationBuffer.SetCurrentPosition(0); } // Load the wave file into a DirectSound buffer try { applicationBuffer = new SecondaryBuffer(FileName, description, applicationDevice); if (applicationBuffer.NotVirtualized) { MessageBox.Show(this, "The 3D virtualization algorithm requested is not supported under this " + "operating system. It is available only on Windows 2000, Windows ME, and Windows 98 with WDM " + "drivers and beyond. This buffer was created without virtualization.", "DirectSound Sample", MessageBoxButtons.OK); } } catch (ArgumentException) { // Check to see if it was a stereo buffer that threw the exception. labelStatus.Text = "Wave file must be mono for 3D control."; labelFilename.Text = string.Empty; return; } catch { // Unknown error, but not a critical failure, so just update the status labelStatus.Text = "Could not create sound buffer."; return; } if (WaveFormatTag.Pcm != (WaveFormatTag.Pcm & description.Format.FormatTag)) { labelStatus.Text = "Wave file must be PCM for 3D control."; if (null != applicationBuffer) { applicationBuffer.Dispose(); } applicationBuffer = null; } // Remember the file for next time if (null != applicationBuffer) { FileName = FileName; } labelStatus.Text = "Ready."; labelFilename.Text = FileName; }
/// <summary> /// Create Direct3D device and swap chain /// </summary> protected void InitDevice() { device = D3DDevice.CreateDeviceAndSwapChain(directControl.Handle); swapChain = device.SwapChain; SetViews(); // Create the effect using (FileStream effectStream = File.OpenRead("Tutorial02.fxo")) { effect = device.CreateEffectFromCompiledBinary(new BinaryReader(effectStream)); } // Obtain the technique technique = effect.GetTechniqueByName("Render"); // Define the input layout InputElementDescription[] layout = { new InputElementDescription() { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32Float, InputSlot = 0, AlignedByteOffset = 0, InputSlotClass = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; PassDescription passDesc = technique.GetPassByIndex(0).Description; vertexLayout = device.CreateInputLayout( layout, passDesc.InputAssemblerInputSignature, passDesc.InputAssemblerInputSignatureSize); device.IA.InputLayout = vertexLayout; SimpleVertexArray vertex = new SimpleVertexArray(); BufferDescription bd = new BufferDescription() { Usage = Usage.Default, ByteWidth = (uint)Marshal.SizeOf(vertex), BindingOptions = BindingOptions.VertexBuffer, CpuAccessOptions = CpuAccessOptions.None, MiscellaneousResourceOptions = MiscellaneousResourceOptions.None }; IntPtr vertexData = Marshal.AllocCoTaskMem(Marshal.SizeOf(vertex)); Marshal.StructureToPtr(vertex, vertexData, false); SubresourceData InitData = new SubresourceData() { SystemMemory = vertexData, SystemMemoryPitch = 0, SystemMemorySlicePitch = 0 }; //D3DBuffer buffer = null; vertexBuffer = device.CreateBuffer(bd, InitData); // Set vertex buffer uint stride = (uint)Marshal.SizeOf(typeof(Vector3F)); uint offset = 0; device.IA.SetVertexBuffers(0, new Collection <D3DBuffer>() { vertexBuffer }, new uint[] { stride }, new uint[] { offset }); // Set primitive topology device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList; Marshal.FreeCoTaskMem(vertexData); }
#pragma warning restore 0169, 0649 public void Init(Device device) { BufferDescription bufferDescription = new BufferDescription(Utilities.SizeOf <BufferType>(), ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); m_cameraBuffer = new Buffer(device, bufferDescription); }
public Play3DSound() { try { // Load the icon from our resources System.Resources.ResourceManager resources = new System.Resources.ResourceManager(this.GetType()); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); } catch { // It's no big deal if we can't load our icons, but try to load the embedded one try { this.Icon = new System.Drawing.Icon(this.GetType(), "directx.ico"); } catch {} } // // Required for Windows Form Designer support // InitializeComponent(); BufferDescription description = new BufferDescription(); WaveFormat fmt = new WaveFormat(); description.PrimaryBuffer = true; description.Control3D = true; Buffer buff = null; fmt.FormatTag = WaveFormatTag.Pcm; fmt.Channels = 2; fmt.SamplesPerSecond = 22050; fmt.BitsPerSample = 16; fmt.BlockAlign = (short)(fmt.BitsPerSample / 8 * fmt.Channels); fmt.AverageBytesPerSecond = fmt.SamplesPerSecond * fmt.BlockAlign; applicationDevice.SetCooperativeLevel(this, CooperativeLevel.Priority); // Get the primary buffer and set the format. buff = new Buffer(description, applicationDevice); buff.Format = fmt; applicationListener = new Listener3D(buff); listenerParameters = applicationListener.AllParameters; labelFilename.Text = String.Empty; labelStatus.Text = "No file loaded."; pictureboxRenderWindow.BackgroundImage = Image.FromFile(DXUtil.SdkMediaPath + "grid.jpg"); GridWidth = pictureboxRenderWindow.Width; GridHeight = pictureboxRenderWindow.Height; trackbarDopplerSlider.Maximum = ConvertLogScaleToLinearSliderPos(DSoundHelper.MaxDopplerFactor); trackbarDopplerSlider.Minimum = ConvertLogScaleToLinearSliderPos(DSoundHelper.MinDopplerFactor); trackbarRolloffSlider.Maximum = ConvertLogScaleToLinearSliderPos(DSoundHelper.MaxRolloffFactor); trackbarRolloffSlider.Minimum = ConvertLogScaleToLinearSliderPos(DSoundHelper.MinRolloffFactor); trackbarMindistanceSlider.Maximum = 40; trackbarMindistanceSlider.Minimum = 1; trackbarMaxdistanceSlider.Maximum = 40; trackbarMaxdistanceSlider.Minimum = 1; trackbarVerticalSlider.Maximum = 100; trackbarVerticalSlider.Minimum = -100; trackbarVerticalSlider.Value = 100; trackbarHorizontalSlider.Maximum = 100; trackbarHorizontalSlider.Minimum = -100; trackbarHorizontalSlider.Value = 100; SetSlidersPos(0, 0, maxOrbitRadius, maxOrbitRadius * 20.0f); SliderChanged(); }
protected override void InitShaderBuffers(Device device) { BufferDescription bufferDescription = new BufferDescription(MatrixBufferType.SizeInBytes(), ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); m_matrixBuffer = new SharpDX.Direct3D11.Buffer(device, bufferDescription); }
private bool InitializeShader(Device device, IntPtr windowsHandle, string vsFileName, string psFileName) { try { /*vsFileName = "../../../sc_instance_shader/" + "Color.vs"; * psFileName = "../../../sc_instance_shader/" + "Color.ps"; * * vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None); * pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None); */ /* * if (MainWindow.is_wpf == 1) * { * var vsFileNameByteArray = SCCoreSystems.Properties.Resources.Color1; * var psFileNameByteArray = SCCoreSystems.Properties.Resources.Color; * //var gsFileNameByteArray = SC_WPF_RENDER.Properties.Resources.HLSL; * vertexShaderByteCode = ShaderBytecode.Compile(vsFileNameByteArray, "ColorVertexShader", "vs_5_0", ShaderFlags.None, EffectFlags.None); * pixelShaderByteCode = ShaderBytecode.Compile(psFileNameByteArray, "ColorPixelShader", "ps_5_0", ShaderFlags.None, EffectFlags.None); * * } * else * { * }*/ //vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName; //psFileName = DSystemConfiguration.ShaderFilePath + psFileName; /* */ var vsFileNameByteArray = SCCoreSystems.Properties.Resources.Color1; var psFileNameByteArray = SCCoreSystems.Properties.Resources.Color; //var gsFileNameByteArray = SC_WPF_RENDER.Properties.Resources.HLSL; vertexShaderByteCode = ShaderBytecode.Compile(vsFileNameByteArray, "ColorVertexShader", "vs_5_0", ShaderFlags.None, EffectFlags.None); pixelShaderByteCode = ShaderBytecode.Compile(psFileNameByteArray, "ColorPixelShader", "ps_5_0", ShaderFlags.None, EffectFlags.None); // Compile the vertex shader code. //ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None); // Compile the pixel shader code. //ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None); // Create the vertex shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); // Create the pixel shader from the buffer. PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. InputElement[] inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "COLOR", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. BufferDescription matrixBufDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DMatrixBuffer>(), // was Matrix BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufDesc); return(true); } catch (Exception ex) { //MessageBox.Show("Error initializing shader. Error is " + ex.Message); Console.WriteLine(" DColorShader ERROR ### " + ex.ToString()); return(false); } }
private bool InitializeShader(Device device, IntPtr windowsHandler, string vsFileName, string psFileName) { try { /*vsFileName = "../../../sc_instance_shader/" + "texture.vs"; * psFileName = "../../../sc_instance_shader/" + "texture.ps"; * * vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None); * pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "TexturePixelShader", "ps_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None); */ /* * if (MainWindow.is_wpf == 1) * { * vsFileName = SCCoreSystems.Properties.Resources.texture1; * psFileName = SCCoreSystems.Properties.Resources.texture; * * vertexShaderByteCode = ShaderBytecode.Compile(vsFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None); * pixelShaderByteCode = ShaderBytecode.Compile(psFileName, "TexturePixelShader", "ps_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None); * } * else * { * * }*/ vsFileName = SCCoreSystems.Properties.Resources.texture1; psFileName = SCCoreSystems.Properties.Resources.texture; vertexShaderByteCode = ShaderBytecode.Compile(vsFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None); pixelShaderByteCode = ShaderBytecode.Compile(psFileName, "TexturePixelShader", "ps_4_0", ShaderFlags.None, SharpDX.D3DCompiler.EffectFlags.None); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); InputElement[] inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "COLOR", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "NORMAL", SemanticIndex = 0, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "POSITION", SemanticIndex = 1, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 1, AlignedByteOffset = 0, Classification = InputClassification.PerInstanceData, InstanceDataStepRate = 1 }, new InputElement() { SemanticName = "POSITION", SemanticIndex = 2, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 2, AlignedByteOffset = 0, Classification = InputClassification.PerInstanceData, InstanceDataStepRate = 1 }, new InputElement() { SemanticName = "POSITION", SemanticIndex = 3, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 3, AlignedByteOffset = 0, Classification = InputClassification.PerInstanceData, InstanceDataStepRate = 1 }, new InputElement() { SemanticName = "POSITION", SemanticIndex = 4, Format = SharpDX.DXGI.Format.R32G32B32_Float, Slot = 4, AlignedByteOffset = 0, Classification = InputClassification.PerInstanceData, InstanceDataStepRate = 1 }, }; Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); BufferDescription matrixBufferDescription = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf <DMatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDescription); SamplerStateDescription samplerDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), MinimumLod = 0, MaximumLod = float.MaxValue }; SamplerState = new SamplerState(device, samplerDesc); return(true); } catch (Exception ex) { return(false); } }
// TODO: private protected /// <summary> /// </summary> /// <param name="description"></param> /// <returns></returns> protected abstract DeviceBuffer CreateBufferCore(ref BufferDescription description);
static private void GenerateDome() { int Latitude = DomeN / 2; int Longitude = DomeN; DVSize = Longitude * Latitude; DISize = (Longitude - 1) * (Latitude - 1) * 2; DVSize *= 2; DISize *= 2; DataStream s = new DataStream(DVSize * Marshal.SizeOf(typeof(Vertex)), true, true); // Fill Vertex Buffer int DomeIndex = 0; for (int i = 0; i < Longitude; i++) { double MoveXZ = 100.0f * (i / ((float)Longitude - 1.0f)) * Math.PI / 180.0; for (int j = 0; j < Latitude; j++) { double MoveY = Math.PI * j / (Latitude - 1); Vertex v = new Vertex(); v.position = new Vector3((float)(Math.Sin(MoveXZ) * Math.Cos(MoveY)), (float)Math.Cos(MoveXZ), (float)(Math.Sin(MoveXZ) * Math.Sin(MoveY))); v.position *= 10.0f; v.texCoord = new Vector2(); v.texCoord.X = 0.5f / (float)Longitude + i / (float)Longitude; v.texCoord.Y = 0.5f / (float)Latitude + j / (float)Latitude; s.Write(v); DomeIndex++; } } for (int i = 0; i < Longitude; i++) { double MoveXZ = 100.0 * (i / (float)(Longitude - 1)) * Math.PI / 180.0; for (int j = 0; j < Latitude; j++) { double MoveY = (Math.PI * 2.0) - (Math.PI * j / (Latitude - 1)); Vertex v = new Vertex(); v.position = new Vector3((float)(Math.Sin(MoveXZ) * Math.Cos(MoveY)), (float)Math.Cos(MoveXZ), (float)(Math.Sin(MoveXZ) * Math.Sin(MoveY))); v.position *= 10.0f; v.texCoord = new Vector2(); v.texCoord.X = 0.5f / (float)Longitude + i / (float)Longitude; v.texCoord.Y = 0.5f / (float)Latitude + j / (float)Latitude; s.Write(v); DomeIndex++; } } s.Position = 0; BufferDescription bufferDescription = new BufferDescription(); bufferDescription.BindFlags = BindFlags.VertexBuffer; bufferDescription.CpuAccessFlags = CpuAccessFlags.None; bufferDescription.OptionFlags = ResourceOptionFlags.None; bufferDescription.SizeInBytes = DVSize * Marshal.SizeOf(typeof(Vertex)); bufferDescription.Usage = ResourceUsage.Default; domeVerts = new D3D10.Buffer(Game.Device, s, bufferDescription); s.Close(); // Fill index buffer s = new DataStream((DISize * 3) * sizeof(short), true, true); int index = 0; for (short i = 0; i < Longitude - 1; i++) { for (short j = 0; j < Latitude - 1; j++) { s.Write((short)(i * Latitude + j)); s.Write((short)((i + 1) * Latitude + j)); s.Write((short)((i + 1) * Latitude + j + 1)); s.Write((short)((i + 1) * Latitude + j + 1)); s.Write((short)(i * Latitude + j + 1)); s.Write((short)(i * Latitude + j)); } } short Offset = (short)(Latitude * Longitude); for (short i = 0; i < Longitude - 1; i++) { for (short j = 0; j < Latitude - 1; j++) { s.Write((short)(Offset + i * Latitude + j)); s.Write((short)(Offset + (i + 1) * Latitude + j + 1)); s.Write((short)(Offset + (i + 1) * Latitude + j)); s.Write((short)(Offset + i * Latitude + j + 1)); s.Write((short)(Offset + (i + 1) * Latitude + j + 1)); s.Write((short)(Offset + i * Latitude + j)); } } s.Position = 0; bufferDescription = new BufferDescription(); bufferDescription.BindFlags = BindFlags.IndexBuffer; bufferDescription.CpuAccessFlags = CpuAccessFlags.None; bufferDescription.OptionFlags = ResourceOptionFlags.None; bufferDescription.SizeInBytes = (DISize * 3) * sizeof(short); bufferDescription.Usage = ResourceUsage.Default; domeIndices = new D3D10.Buffer(Game.Device, s, bufferDescription); s.Close(); }
// Initialize hardware-dependent resources. private void CreateDeviceResources() { // Unlike the original C++ sample, we don't have smart pointers so we need to // dispose Direct3D objects explicitly Utilities.Dispose(ref d3dDevice); Utilities.Dispose(ref vertexShader); Utilities.Dispose(ref inputLayout); Utilities.Dispose(ref pixelShader); Utilities.Dispose(ref constantBuffer); Utilities.Dispose(ref vertexBuffer); Utilities.Dispose(ref indexBuffer); // This flag adds support for surfaces with a different color channel ordering // than the API default. It is required for compatibility with Direct2D. var creationFlags = DeviceCreationFlags.BgraSupport; #if DEBUG // If the project is in a debug build, enable debugging via SDK Layers. creationFlags |= DeviceCreationFlags.Debug; #endif // This array defines the set of DirectX hardware feature levels this app will support. // Note the ordering should be preserved. // Don't forget to declare your application's minimum required feature level in its // description. All applications are assumed to support 9.1 unless otherwise stated. FeatureLevel[] featureLevels = { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0, FeatureLevel.Level_9_3, FeatureLevel.Level_9_2, FeatureLevel.Level_9_1, }; // Create the Direct3D 11 API device object. d3dDevice = new Device(DriverType.Hardware, creationFlags, featureLevels); d3dContext = d3dDevice.ImmediateContext; // Get the Direct3D 11.1 API device. using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>()) { // Query for ISurfaceImageSourceNative interface. using (var sisNative = ComObject.QueryInterface <ISurfaceImageSourceNative>(this)) { sisNative.Device = dxgiDevice; } } // Load the vertex shader. var vsBytecode = ReadData("Scenario2Component\\SimpleVertexShader.cso"); vertexShader = new VertexShader(d3dDevice, vsBytecode); // Create input layout for vertex shader. var vertexDesc = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, Format.R32G32B32_Float, 12, 0, InputClassification.PerVertexData, 0), }; inputLayout = new InputLayout(d3dDevice, vsBytecode, vertexDesc); // Load the pixel shader. var psBytecode = ReadData("Scenario2Component\\SimplePixelShader.cso"); pixelShader = new PixelShader(d3dDevice, psBytecode); // Create the constant buffer. var constantBufferDesc = new BufferDescription() { SizeInBytes = Utilities.SizeOf <ModelViewProjectionConstantBuffer>(), BindFlags = BindFlags.ConstantBuffer }; constantBuffer = new Buffer(d3dDevice, constantBufferDesc); // Describe the vertices of the cube. var cubeVertices = new[] { new VertexPositionColor(new Vector3(-0.5f, -0.5f, -0.5f), new Vector3(0.0f, 0.0f, 0.0f)), new VertexPositionColor(new Vector3(-0.5f, -0.5f, 0.5f), new Vector3(0.0f, 0.0f, 1.0f)), new VertexPositionColor(new Vector3(-0.5f, 0.5f, -0.5f), new Vector3(0.0f, 1.0f, 0.0f)), new VertexPositionColor(new Vector3(-0.5f, 0.5f, 0.5f), new Vector3(0.0f, 1.0f, 1.0f)), new VertexPositionColor(new Vector3(0.5f, -0.5f, -0.5f), new Vector3(1.0f, 0.0f, 0.0f)), new VertexPositionColor(new Vector3(0.5f, -0.5f, 0.5f), new Vector3(1.0f, 0.0f, 1.0f)), new VertexPositionColor(new Vector3(0.5f, 0.5f, -0.5f), new Vector3(1.0f, 1.0f, 0.0f)), new VertexPositionColor(new Vector3(0.5f, 0.5f, 0.5f), new Vector3(1.0f, 1.0f, 1.0f)), }; var vertexBufferDesc = new BufferDescription() { SizeInBytes = Utilities.SizeOf <VertexPositionColor>() * cubeVertices.Length, BindFlags = BindFlags.VertexBuffer }; vertexBuffer = Buffer.Create(d3dDevice, cubeVertices, vertexBufferDesc); // Describe the cube indices. var cubeIndices = new ushort[] { 0, 2, 1, // -x 1, 2, 3, 4, 5, 6, // +x 5, 7, 6, 0, 1, 5, // -y 0, 5, 4, 2, 6, 7, // +y 2, 7, 3, 0, 4, 6, // -z 0, 6, 2, 1, 3, 7, // +z 1, 7, 5, }; indexCount = cubeIndices.Length; // Create the index buffer. var indexBufferDesc = new BufferDescription() { SizeInBytes = sizeof(ushort) * cubeIndices.Length, BindFlags = BindFlags.IndexBuffer }; indexBuffer = Buffer.Create(d3dDevice, cubeIndices, indexBufferDesc); // Calculate the aspect ratio and field of view. float aspectRatio = (float)width / (float)height; float fovAngleY = 70.0f * MathUtil.Pi / 180.0f; if (aspectRatio < 1.0f) { fovAngleY /= aspectRatio; } // Set right-handed perspective projection based on aspect ratio and field of view. constantBufferData.projection = Matrix.Transpose( Matrix.PerspectiveFovRH( fovAngleY, aspectRatio, 0.01f, 100.0f ) ); // Start animating at frame 0. frameCount = 0; }
protected override Buffer CreateBufferCore(ref BufferDescription description) { return(new D3D11Buffer(_device, description.SizeInBytes, description.Usage, description.StructureByteStride)); }
public override VertexBuffer CreateVertexBuffer(ref BufferDescription description) { return(new D3D11VertexBuffer(_device, ref description)); }
public void CreateResources() { ResourceFactory factory = GraphicsDevice.ResourceFactory; ProjectionBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); WorldBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); ResourceLayout = factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("World", ResourceKind.UniformBuffer, ShaderStages.Vertex)) ); ResourceSet = factory.CreateResourceSet( new ResourceSetDescription( ResourceLayout, ProjectionBuffer, WorldBuffer) ); VertexPositionColor[] quadVertices = { new VertexPositionColor(new Vector2(0, 0), RgbaFloat.Red), new VertexPositionColor(new Vector2(200, 0), RgbaFloat.Red), new VertexPositionColor(new Vector2(200, 200), RgbaFloat.Red), new VertexPositionColor(new Vector2(0, 200), RgbaFloat.Red) }; BufferDescription vbDescription = new BufferDescription( (uint)quadVertices.Length * VertexPositionColor.SizeInBytes, BufferUsage.VertexBuffer); VertexBuffer = factory.CreateBuffer(vbDescription); GraphicsDevice.UpdateBuffer(VertexBuffer, 0, quadVertices); ushort[] quadIndices = { 0, 1, 2, 3, 0 }; BufferDescription ibDescription = new BufferDescription( (uint)quadIndices.Length * sizeof(ushort), BufferUsage.IndexBuffer); IndexBuffer = factory.CreateBuffer(ibDescription); GraphicsDevice.UpdateBuffer(IndexBuffer, 0, quadIndices); ProjMatrixBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); VertexLayoutDescription vertexLayout = new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("Color", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float4)); ShaderDescription vertexShaderDesc = new ShaderDescription( ShaderStages.Vertex, Encoding.UTF8.GetBytes(VertexCode), "main"); ShaderDescription fragmentShaderDesc = new ShaderDescription( ShaderStages.Fragment, Encoding.UTF8.GetBytes(FragmentCode), "main"); Shaders = factory.CreateFromSpirv(vertexShaderDesc, fragmentShaderDesc); // Create pipeline GraphicsPipelineDescription pipelineDescription = new GraphicsPipelineDescription( BlendStateDescription.SingleAlphaBlend, new DepthStencilStateDescription( depthTestEnabled: true, depthWriteEnabled: true, comparisonKind: ComparisonKind.LessEqual), new RasterizerStateDescription( cullMode: FaceCullMode.None, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false), PrimitiveTopology.TriangleStrip, new ShaderSetDescription( vertexLayouts: new VertexLayoutDescription[] { vertexLayout }, shaders: Shaders), new[] { ResourceLayout }, GraphicsDevice.SwapchainFramebuffer.OutputDescription ); Pipeline = factory.CreateGraphicsPipeline(pipelineDescription); CommandList = factory.CreateCommandList(); }
/// <summary> /// Creates a new <see cref="DeviceBuffer"/>. /// </summary> /// <param name="description">The desired properties of the created object.</param> /// <returns>A new <see cref="DeviceBuffer"/>.</returns> public DeviceBuffer CreateBuffer(BufferDescription description) => CreateBuffer(ref description);
private void BuildGeometryBuffers() { try { var vertices = new List <VertexPC>(); var indices = new List <int>(); var vcount = 0; var tcount = 0; using (var reader = new StreamReader("Models\\skull.txt")) { var input = reader.ReadLine(); if (input != null) { // VertexCount: X vcount = Convert.ToInt32(input.Split(new[] { ':' })[1].Trim()); } input = reader.ReadLine(); if (input != null) { //TriangleCount: X tcount = Convert.ToInt32(input.Split(new[] { ':' })[1].Trim()); } var c = Color.Black; // skip ahead to the vertex data do { input = reader.ReadLine(); } while (input != null && !input.StartsWith("{")); //set fixed number format format for correct parsing of the vector var provider = new NumberFormatInfo { NumberDecimalSeparator = ".", NumberGroupSeparator = "," }; // Get the vertices for (var i = 0; i < vcount; i++) { input = reader.ReadLine(); if (input != null) { var vals = input.Split(new[] { ' ' }); vertices.Add(new VertexPC( new Vector3( Convert.ToSingle(vals[0].Trim(), provider), Convert.ToSingle(vals[1].Trim(), provider), Convert.ToSingle(vals[2].Trim(), provider)), c)); } } // skip ahead to the index data do { input = reader.ReadLine(); } while (input != null && !input.StartsWith("{")); // Get the indices _skullIndexCount = 3 * tcount; for (var i = 0; i < tcount; i++) { input = reader.ReadLine(); if (input == null) { break; } var m = input.Trim().Split(new[] { ' ' }); indices.Add(Convert.ToInt32(m[0].Trim())); indices.Add(Convert.ToInt32(m[1].Trim())); indices.Add(Convert.ToInt32(m[2].Trim())); } } var vbd = new BufferDescription(VertexPC.Stride * vcount, ResourceUsage.Immutable, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); _vb = new Buffer(Device, new DataStream(vertices.ToArray(), false, false), vbd); var ibd = new BufferDescription(sizeof(int) * _skullIndexCount, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); _ib = new Buffer(Device, new DataStream(indices.ToArray(), false, false), ibd); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
protected override DeviceBuffer CreateBufferCore(ref BufferDescription description) { return(new MTLBuffer(ref description, _gd)); }
public override UniformBuffer CreateUniformBuffer(ref BufferDescription description) { return(new D3D11UniformBuffer(_device, ref description)); }