Exemple #1
0
        private void compileShader(FixedFuncShaders.eFixedFuncShaderIndex id, string shaderText, string[] defines, bool vertexShader)
        {
            Macro [] Macrodefines = null;
            if (defines != null)
            {
                Macrodefines = new Macro[defines.Length];
                for (int k = 0; k < defines.Length; k++)
                {
                    Macrodefines[k].Definition = defines[k];
                }
            }
            GraphicsStream gs = ShaderLoader.CompileShader(shaderText, "main", Macrodefines, null, vertexShader ? "vs_2_0" : "ps_2_0", ShaderFlags.None);

            if (vertexShader)
            {
                BFixedFuncVS vsA = new BFixedFuncVS();
                vsA.mVS = new VertexShader(BRenderDevice.getDevice(), gs);
                vsA.mID = id;
                mVertexShaders.Add(vsA);
            }
            else
            {
                BFixedFuncPS vsA = new BFixedFuncPS();
                vsA.mPS = new PixelShader(BRenderDevice.getDevice(), gs);
                vsA.mID = id;
                mPixelShaders.Add(vsA);
            }
            gs.Close();
            gs = null;
        }
Exemple #2
0
        private void FractalForm_Resize(object sender, EventArgs e)
        {
            timer1.Stop();

            PresentParameters presentParams = new PresentParameters();

            presentParams.Windowed               = true;
            presentParams.SwapEffect             = SwapEffect.Copy;
            presentParams.AutoDepthStencilFormat = DepthFormat.D16;
            presentParams.EnableAutoDepthStencil = true;

            device = new Device(0, DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing, presentParams);

            device.RenderState.CullMode = Cull.None;
            device.RenderState.Lighting = false;
            device.VertexFormat         = CustomVertex.PositionTextured.Format;

            ShaderFlags shaderFlags = ShaderFlags.None;

            Assembly assembly = Assembly.GetExecutingAssembly();

            string[]       d      = assembly.GetManifestResourceNames();
            Stream         stream = assembly.GetManifestResourceStream("FractalFast0r.Resources.shaders.txt");
            string         errors = "";
            ConstantTable  consts;
            GraphicsStream gs = ShaderLoader.CompileShaderFromStream(stream, "vs_main", null, null, "vs_3_0", shaderFlags, out errors, out consts);
            VertexShader   vs = new VertexShader(device, gs);

            gs.Close();
            device.VertexShader = vs;

            stream.Seek(0, System.IO.SeekOrigin.Begin);

            gs = ShaderLoader.CompileShaderFromStream(stream, "ps_main", null, null, "ps_3_0", shaderFlags, out errors, out consts);
            PixelShader ps = new PixelShader(device, gs);

            gs.Close();
            stream.Close();
            device.PixelShader = ps;

            stop = new Stopwatch();
            stop.Start();
            timer1.Start();
        }
Exemple #3
0
        void createD3DTexturesFromBlades()
        {
            if (mFoliageBlades.Count == 0)
            {
                return;
            }

            //create our foliage texures
            int numVerts = mFoliageBlades.Count * mNumVertsPerBlade;

            mD3DPositionsTexture = new Texture(BRenderDevice.getDevice(), numVerts, 1, 1, Usage.None, Format.A32B32G32R32F, Pool.Managed);
            mD3DUVsTexture       = new Texture(BRenderDevice.getDevice(), numVerts, 1, 1, Usage.None, Format.A32B32G32R32F, Pool.Managed);
            unsafe
            {
                GraphicsStream gs    = mD3DPositionsTexture.LockRectangle(0, 0);
                Vector4 *      verts = (Vector4 *)gs.InternalDataPointer;
                GraphicsStream gsUV  = mD3DUVsTexture.LockRectangle(0, 0);
                Vector4 *      UVs   = (Vector4 *)gsUV.InternalDataPointer;

                int vc = 0;
                for (int i = 0; i < mFoliageBlades.Count; i++)
                {
                    for (int j = 0; j < mNumVertsPerBlade; j++)
                    {
                        verts[vc].X = mFoliageBlades[i].verts[j].X;
                        verts[vc].Y = mFoliageBlades[i].verts[j].Y;
                        verts[vc].Z = mFoliageBlades[i].verts[j].Z;
                        verts[vc].W = 1;

                        //uvs
                        UVs[vc].X = mFoliageBlades[i].uvs[j].X;
                        UVs[vc].Y = mFoliageBlades[i].uvs[j].Y;
                        UVs[vc].Z = 0;
                        UVs[vc].W = 0;

                        vc++;
                    }
                }
                gs.Close();
                mD3DPositionsTexture.UnlockRectangle(0);
                gsUV.Close();
                mD3DUVsTexture.UnlockRectangle(0);
            }
        }
Exemple #4
0
        /// <summary>
        /// Grabs the next frame of video obtained
        /// from the VMR9 and return it as an RGB image
        /// </summary>
        /// <returns>Returns null on failure or a Bitmap object</returns>
        public Bitmap GetCurrentImage()
        {
            try
            {
                //Log.Debug("GetCurrentImage called");

                lock (grabNotifier)
                {
                    grabSucceeded = false;
                    grabSample    = true;
                    if (!Monitor.Wait(grabNotifier, 500))
                    {
                        Log.Debug("FrameGrabber: Timed-out waiting for grabbed frame!");
                        return(null);
                    }

                    if (grabSucceeded)
                    {
                        using (GraphicsStream stream = SurfaceLoader.SaveToStream(ImageFileFormat.Bmp, rgbSurface))
                        {
                            Bitmap b = new Bitmap(Image.FromStream(stream));

                            // IMPORTANT: Closes and disposes the stream
                            // If this is not done we get a memory leak!
                            stream.Close();
                            return(b);
                        }
                    }
                    Log.Debug("FrameGrabber: Frame grab failed");
                    return(null);
                }
            }
            catch (Exception e) // Can occur for example if the video device is lost
            {
                Log.Debug(e.ToString());
                return(null);
            }
        }
Exemple #5
0
        public void Set3D(int left_index, int right_index)
        {
            Rectangle destRect = new Rectangle(0, 0, _size.Width, _size.Height);

            _device.StretchRectangle(_imageLeftList[left_index], _size, _imageBuf, destRect, TextureFilter.None);
            destRect.X = _size.Width;
            _device.StretchRectangle(_imageRightList[right_index], _size, _imageBuf, destRect, TextureFilter.None);

            GraphicsStream gStream = _imageBuf.LockRectangle(LockFlags.None);

            byte[] data = new byte[] { 0x4e, 0x56, 0x33, 0x44,                            //NVSTEREO_IMAGE_SIGNATURE         = 0x4433564e
                                       0x00, 0x0F, 0x00, 0x00,                            //Screen width * 2 = 1920*2 = 3840 = 0x00000F00;
                                       0x38, 0x04, 0x00, 0x00,                            //Screen height = 1080             = 0x00000438;
                                       0x20, 0x00, 0x00, 0x00,                            //dwBPP = 32                       = 0x00000020;
                                       0x02, 0x00, 0x00, 0x00 };                          //dwFlags = SIH_SCALE_TO_FIT       = 0x00000002;

            gStream.Seek(_size.Width * 2 * _size.Height * 4, System.IO.SeekOrigin.Begin); //last row
            gStream.Write(data, 0, data.Length);

            gStream.Close();

            _imageBuf.UnlockRectangle();
        }
Exemple #6
0
        /// <summary>
        /// The device exists, but may have just been Reset().  Resources in
        /// Pool.Default and any other device state that persists during
        /// rendering should be set here.  Render states, matrices, textures,
        /// etc., that don't change during rendering can be set once here to
        /// avoid redundant state setting during Render() or FrameMove().
        /// </summary>
        protected override void RestoreDeviceObjects(System.Object sender, System.EventArgs e)
        {
            // Setup render states
            device.RenderState.Lighting = false;
            device.RenderState.CullMode = Cull.None;

            // Create index buffer

            indexBuffer = new IndexBuffer(typeof(short), numberIndices, device, 0, Pool.Default);

            short[] indices = (short[])indexBuffer.Lock(0, 0);

            int count = 0;

            for (int y = 1; y < m_Size; y++)
            {
                for (int x = 1; x < m_Size; x++)
                {
                    indices[count++] = (short)((y - 1) * m_Size + (x - 1));
                    indices[count++] = (short)((y - 0) * m_Size + (x - 1));
                    indices[count++] = (short)((y - 1) * m_Size + (x - 0));

                    indices[count++] = (short)((y - 1) * m_Size + (x - 0));
                    indices[count++] = (short)((y - 0) * m_Size + (x - 1));
                    indices[count++] = (short)((y - 0) * m_Size + (x - 0));
                }
            }

            indexBuffer.Unlock();


            // Create vertex buffer
            vertexBuffer = new VertexBuffer(typeof(Vector2), numberVertices, device, Usage.WriteOnly, 0, Pool.Default);

            Vector2[] vertices = (Vector2[])vertexBuffer.Lock(0, 0);

            count = 0;
            for (int y = 0; y < m_Size; y++)
            {
                for (int x = 0; x < m_Size; x++)
                {
                    vertices[count++] = new Vector2(((float)x / (float)(m_Size - 1) - 0.5f) * (float)Math.PI,
                                                    ((float)y / (float)(m_Size - 1) - 0.5f) * (float)Math.PI);
                }
            }

            vertexBuffer.Unlock();
            // Create vertex shader
            string         shaderPath = null;
            GraphicsStream code       = null;

            // Create our declaration
            VertexElement[] decl = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.Position, 0), VertexElement.VertexDeclarationEnd };
            ourDeclaration = new VertexDeclaration(device, decl);

            // Find the vertex shader file
            shaderPath = DXUtil.FindMediaFile(null, "Ripple.vsh");

            // Assemble the vertex shader from the file
            code = ShaderLoader.FromFile(shaderPath, null, 0);
            // Create the vertex shader
            ourShader = new VertexShader(device, code);
            code.Close();

            // Set up the projection matrix
            float fAspectRatio = (float)device.PresentationParameters.BackBufferWidth / (float)device.PresentationParameters.BackBufferHeight;

            projectionMatrix            = Matrix.PerspectiveFovRH(Geometry.DegreeToRadian(60.0f), fAspectRatio, 0.1f, 100.0f);
            device.Transform.Projection = projectionMatrix;
        }
        public void OnTextSubtitle(ref TEXT_SUBTITLE sub)
        {
            try
            {
                if (sub.page == _activeSubPage)
                {
                    Log.Debug("Page: " + sub.page);
                    Log.Debug("Character table: " + sub.encoding);
                    Log.Debug("Timeout: " + sub.timeOut);
                    Log.Debug("Timestamp: " + sub.timeStamp);
                    Log.Debug("Language: " + sub.language);

                    String content = sub.text;
                    if (content == null)
                    {
                        Log.Error("OnTextSubtitle: sub.txt == null!");
                        return;
                    }
                    Log.Debug("Content: ");
                    if (content.Trim().Length > 0) // debug log subtitles
                    {
                        StringTokenizer st = new StringTokenizer(content, new char[] { '\n' });
                        while (st.HasMore)
                        {
                            Log.Debug(st.NextToken());
                        }
                    }
                    else
                    {
                        Log.Debug("Page: <BLANK PAGE>");
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error("Problem with TEXT_SUBTITLE");
                Log.Error(e);
            }

            try
            {
                // if we dont need the subtitle
                if (!_renderSubtitles || _useBitmap || (_activeSubPage != sub.page))
                {
                    //
                    //chemelli: too much logging. You can check if logs have:
                    //          Log.Debug("Page: " + sub.page);  or Log.Debug("Page: <BLANK PAGE>");
                    //          and
                    //          Log.Debug("Text subtitle (page {0}) ACCEPTED: [...]
                    //          to know the evaluation of this if block
                    //
                    //Log.Debug("Text subtitle (page {0}) discarded: useBitmap is {1} and activeSubPage is {2}", sub.page, useBitmap,
                    //          activeSubPage);

                    return;
                }
                Log.Debug("Text subtitle (page {0}) ACCEPTED: useBitmap is {1} and activeSubPage is {2}", sub.page, _useBitmap,
                          _activeSubPage);

                Subtitle subtitle = new Subtitle();

                // TODO - RenderText should directly draw to a D3D texture
                subtitle.subBitmap   = RenderText(sub.lc);
                subtitle.timeOut     = sub.timeOut;
                subtitle.presentTime = sub.timeStamp / 90000.0f + _startPos;

                subtitle.height             = 576;
                subtitle.width              = 720;
                subtitle.screenHeight       = 576;
                subtitle.screenWidth        = 720;
                subtitle.firstScanLine      = 0;
                subtitle.horizontalPosition = 0;

                Texture texture = null;
                try
                {
                    // allocate new texture
                    texture = new Texture(GUIGraphicsContext.DX9Device, subtitle.subBitmap.Width,
                                          subtitle.subBitmap.Height, 1, Usage.Dynamic, Format.A8R8G8B8, Pool.Default);
                    int pitch;
                    using (GraphicsStream a = texture.LockRectangle(0, LockFlags.Discard, out pitch))
                    {
                        BitmapData bd = subtitle.subBitmap.LockBits(new Rectangle(0, 0, subtitle.subBitmap.Width,
                                                                                  subtitle.subBitmap.Height), ImageLockMode.ReadOnly,
                                                                    PixelFormat.Format32bppArgb);

                        // Quick copy of content
                        unsafe
                        {
                            byte *to   = (byte *)a.InternalDataPointer;
                            byte *from = (byte *)bd.Scan0.ToPointer();
                            for (int y = 0; y < bd.Height; ++y)
                            {
                                for (int x = 0; x < bd.Width * 4; ++x)
                                {
                                    to[pitch * y + x] = from[y * bd.Stride + x];
                                }
                            }
                        }

                        texture.UnlockRectangle(0);
                        subtitle.subBitmap.UnlockBits(bd);
                        subtitle.subBitmap.SafeDispose();
                        subtitle.subBitmap = null;
                        subtitle.texture   = texture;
                        a.Close();
                    }
                }
                catch (Exception e)
                {
                    Log.Debug("SubtitleRenderer: Failed to create subtitle surface!");
                    Log.Error(e);
                    return;
                }

                AddSubtitle(subtitle);
            }
            catch (Exception e)
            {
                Log.Error("Problem processing text subtitle");
                Log.Error(e);
            }
        }
        /// <summary>
        /// Callback from subtitle filter, alerting us that a new subtitle is available
        /// It receives the new subtitle as the argument sub, which data is only valid
        /// for the duration of OnSubtitle.
        /// </summary>
        /// <returns></returns>
        public int OnSubtitle(ref NATIVE_SUBTITLE sub)
        {
            if (!_useBitmap || !_renderSubtitles)
            {
                return(0);
                // TODO: Might be good to let this cache and then check in Render method because bitmap subs arrive a while before display
            }
            Log.Debug("OnSubtitle - stream position " + _player.StreamPosition);
            lock (_alert)
            {
                try
                {
                    Log.Debug("SubtitleRenderer:  Bitmap: bpp=" + sub.bmBitsPixel + " planes " + sub.bmPlanes + " dim = " +
                              sub.bmWidth + " x " + sub.bmHeight + " stride : " + sub.bmWidthBytes);
                    Log.Debug("SubtitleRenderer: to = " + sub.timeOut + " ts=" + sub.timeStamp + " fsl=" + sub.firstScanLine +
                              " h pos=" + sub.horizontalPosition + " (startPos = " + _startPos + ")");

                    Subtitle subtitle = new Subtitle();
                    subtitle.subBitmap          = new Bitmap(sub.bmWidth, sub.bmHeight, PixelFormat.Format32bppArgb);
                    subtitle.timeOut            = sub.timeOut;
                    subtitle.presentTime        = ((double)sub.timeStamp / 1000.0f) + _startPos; // compute present time in SECONDS
                    subtitle.height             = (uint)sub.bmHeight;
                    subtitle.width              = (uint)sub.bmWidth;
                    subtitle.screenHeight       = (uint)sub.screenHeight;
                    subtitle.screenWidth        = (uint)sub.screenWidth;
                    subtitle.firstScanLine      = sub.firstScanLine;
                    subtitle.horizontalPosition = sub.horizontalPosition;
                    subtitle.id = _subCounter++;
                    //Log.Debug("Received Subtitle : " + subtitle.ToString());

                    Texture texture = null;
                    try
                    {
                        // allocate new texture
                        texture = new Texture(GUIGraphicsContext.DX9Device, (int)subtitle.width, (int)subtitle.height, 1,
                                              Usage.Dynamic,
                                              Format.A8R8G8B8, GUIGraphicsContext.GetTexturePoolType());

                        if (texture == null)
                        {
                            Log.Debug("OnSubtitle: Failed to create new texture!");
                            return(0);
                        }

                        int pitch;
                        using (GraphicsStream a = texture.LockRectangle(0, LockFlags.Discard, out pitch))
                        {
                            // Quick copy of content
                            unsafe
                            {
                                byte *to   = (byte *)a.InternalDataPointer;
                                byte *from = (byte *)sub.bmBits;
                                for (int y = 0; y < sub.bmHeight; ++y)
                                {
                                    for (int x = 0; x < sub.bmWidth * 4; ++x)
                                    {
                                        to[pitch * y + x] = from[y * sub.bmWidthBytes + x];
                                    }
                                }
                            }
                            a.Close();
                        }

                        texture.UnlockRectangle(0);
                        subtitle.texture = texture;
                    }
                    catch (Exception)
                    {
                        Log.Debug("OnSubtitle: Failed to copy bitmap data!");
                        return(0);
                    }

                    AddSubtitle(subtitle);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            }
            return(0);
        }
Exemple #9
0
        static private unsafe void processMesh(ref BRenderGrannyMesh mesh, granny_mesh *grannyMesh)
        {
            BRenderPrimitive prim = new BRenderPrimitive();

            //indicies
            prim.mNumInds = GrannyGetMeshTriangleCount(grannyMesh) * 3;
            int[] indData = new int[prim.mNumInds];

            int    indexSize          = prim.mNumInds * sizeof(int);
            IntPtr pMarshaledIndexMem = System.Runtime.InteropServices.Marshal.AllocHGlobal(indexSize);

            GrannyCopyMeshIndices(grannyMesh, 4, (int *)pMarshaledIndexMem);
            System.Runtime.InteropServices.Marshal.Copy(pMarshaledIndexMem, indData, 0, prim.mNumInds);
            System.Runtime.InteropServices.Marshal.FreeHGlobal(pMarshaledIndexMem);


            //ib's
            prim.mIB = new IndexBuffer(typeof(int), prim.mNumInds, BRenderDevice.getDevice(), Usage.None, Pool.Managed);
            GraphicsStream stream  = prim.mIB.Lock(0, 0, LockFlags.None);
            int *          outInds = (int *)stream.InternalDataPointer;

            for (int q = 0; q < prim.mNumInds; q++)
            {
                outInds[q] = indData[q];
            }

            prim.mIB.Unlock();
            stream.Close();


            //verticies
            prim.mVertexSize = 0;


            granny_data_type_definition *grnyVertTypeDef = GrannyGetMeshVertexType(grannyMesh);

            granny_data_type_definition[] grnDTD = null;
            VertexDeclaration             grnVD  = null;

            if (!getVertexTypeFromGranny(grnyVertTypeDef, ref prim.mVertexSize, ref grnDTD, ref grnVD, ref prim.mVDecl))
            {
                //already logged
                //CoreGlobals.getErrorManager().OnSimpleWarning(String.Format("Error loading {0} getVertexTypeFromGranny failed", filename));

                return;
            }

            prim.mNumVerts = GrannyGetMeshVertexCount(grannyMesh);

            {
                int    size          = prim.mNumVerts * prim.mVertexSize;
                IntPtr pMarshaledMem = System.Runtime.InteropServices.Marshal.AllocHGlobal(size);
                byte[] tGrnVerts     = new byte[size];


                fixed(granny_data_type_definition *grnPD = grnDTD)
                GrannyCopyMeshVertices(grannyMesh, grnPD /*grnyVertTypeDef*/, (void *)pMarshaledMem);

                System.Runtime.InteropServices.Marshal.Copy(pMarshaledMem, tGrnVerts, 0, size);
                System.Runtime.InteropServices.Marshal.FreeHGlobal(pMarshaledMem);

                byte[] d3dVerts = new byte[size];

                //swizzle the granny verts to be d3d friendly before copying them to the device
                swzzlGrnyVertsToD3DVerts(tGrnVerts, grnVD, prim.mVertexSize, prim.mNumVerts,
                                         ref d3dVerts, prim.mVDecl);



                prim.mVB = new VertexBuffer(BRenderDevice.getDevice(), (int)prim.mNumVerts * prim.mVertexSize, Usage.None, VertexFormats.None, Pool.Managed);
                stream   = prim.mVB.Lock(0, 0, LockFlags.None);

                stream.Write(d3dVerts, 0, size);
                prim.mVB.Unlock();
                stream.Close();


                tGrnVerts = null;
                grnVD.Dispose();
                grnVD = null;
            }
            //SUB GROUPS
            int groupCount = GrannyGetMeshTriangleGroupCount(grannyMesh);
            granny_tri_material_group *GrannyMatGroups = GrannyGetMeshTriangleGroups(grannyMesh);


            //process our material groups for this mesh


            for (int k = 0; k < groupCount; k++)
            {
                BRenderMaterialGroup group = new BRenderMaterialGroup();


                group.mStartIndex = GrannyMatGroups[k].TriFirst * 3;
                group.mPrimCount  = GrannyMatGroups[k].TriCount;

                //load your texture here.
                prim.mGroups.Add(group);
            }


            mesh.addRenderPrimitive(prim);
        }
        /// <summary>
        /// Grabs the next frame of video obtained
        /// from the VMR9 and return it as an RGB image
        /// </summary>
        /// <returns>Returns null on failure or a Bitmap object</returns>
        public Bitmap GetCurrentImage()
        {
            try
            {
                //Log.Debug("GetCurrentImage called");

                if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR &&
                    GUIGraphicsContext.Vmr9Active && !FrameGrabberD3D9Enable)
                {
                    lock (grabNotifier)
                    {
                        if (VMR9Util.g_vmr9 != null)
                        {
                            VMR9Util.g_vmr9.MadVrGrabCurrentFrame();
                            try
                            {
                                if (FrameResult != null)
                                {
                                    FrameResult.SafeDispose();
                                    FrameResult = null;
                                }

                                if (GUIGraphicsContext.madVRCurrentFrameBitmap != null)
                                {
                                    FrameResult = new Bitmap(GUIGraphicsContext.madVRCurrentFrameBitmap);
                                    return(FrameResult);
                                }
                            }
                            catch
                            {
                                Log.Debug("FrameGrabber: Frame grab catch failed for madVR");
                                return(null);
                                // When Bitmap is not yet ready
                            }
                        }

                        //////// Part of code used for D3D9 setting in madVR
                        //////lock (grabNotifier)
                        //////{
                        //////  grabSucceeded = false;
                        //////  grabSample = true;
                        //////  if (!Monitor.Wait(grabNotifier, 500))
                        //////  {
                        //////    Log.Debug("FrameGrabber: Timed-out waiting for grabbed frame!");
                        //////    return null;
                        //////  }

                        //////  if (grabSucceeded)
                        //////  {
                        //////    try
                        //////    {
                        //////      if (FrameResult != null)
                        //////      {
                        //////        FrameResult.SafeDispose();
                        //////        FrameResult = null;
                        //////      }

                        //////      if (GUIGraphicsContext.madVRFrameBitmap != null)
                        //////      {
                        //////        FrameResult = new Bitmap(GUIGraphicsContext.madVRFrameBitmap);
                        //////        return FrameResult;
                        //////      }
                        //////    }
                        //////    catch
                        //////    {
                        //////      Log.Debug("FrameGrabber: Frame grab catch failed for madVR");
                        //////      return null;
                        //////      // When Bitmap is not yet ready
                        //////    }
                        //////  }
                        //////}
                    }
                    // Bitmap not ready return null
                    Log.Debug("FrameGrabber: Frame grab failed for madVR");
                    return(null);
                }

                if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR &&
                    GUIGraphicsContext.Vmr9Active)
                {
                    Surface backbuffer = null;
                    Bitmap  b          = null;
                    try
                    {
                        backbuffer = GUIGraphicsContext.DX9DeviceMadVr.GetBackBuffer(0, 0, BackBufferType.Mono);
                        using (var stream = SurfaceLoader.SaveToStream(ImageFileFormat.Bmp, backbuffer))
                        {
                            b = new Bitmap(Image.FromStream(stream));

                            // IMPORTANT: Closes and disposes the stream
                            // If this is not done we get a memory leak!
                            stream.Close();
                            stream.Dispose();
                            backbuffer.Dispose();
                            return(b);
                        }
                    }
                    catch (Exception)
                    {
                        backbuffer?.Dispose();
                        b?.Dispose();
                        Log.Debug("FrameGrabber: Timed-out waiting for grabbed frame!");
                    }
                }
                else
                {
                    lock (grabNotifier)
                    {
                        grabSucceeded = false;
                        grabSample    = true;
                        if (!Monitor.Wait(grabNotifier, 500))
                        {
                            Log.Debug("FrameGrabber: Timed-out waiting for grabbed frame!");
                            return(null);
                        }

                        if (grabSucceeded)
                        {
                            using (GraphicsStream stream = SurfaceLoader.SaveToStream(ImageFileFormat.Bmp, rgbSurface))
                            {
                                Bitmap b = new Bitmap(Image.FromStream(stream));

                                // IMPORTANT: Closes and disposes the stream
                                // If this is not done we get a memory leak!
                                stream.Close();
                                return(b);
                            }
                        }
                        Log.Debug("FrameGrabber: Frame grab failed");
                        return(null);
                    }
                }
            }
            catch (Exception e) // Can occur for example if the video device is lost
            {
                Log.Debug(e.ToString());
                return(null);
            }
            // Not image grabbed
            return(null);
        }
Exemple #11
0
        //-------------------------------------

        public void createRenderVBs()
        {
            destroyRenderVBs();
            int width = TerrainGlobals.getTerrain().getNumXVerts();

            for (int setI = 0; setI < mSetsUsed.Count; setI++)
            {
                List <int> validIndexes      = new List <int>();
                List <int> validBladeIndexes = new List <int>();
                for (int x = 0; x < BTerrainQuadNode.cMaxWidth; x++)
                {
                    for (int z = 0; z < BTerrainQuadNode.cMaxWidth; z++)
                    {
                        int             index = (x + mOwnerNodeDesc.mMinXVert) + width * (z + mOwnerNodeDesc.mMinZVert);
                        FoliageVertData fvd   = FoliageManager.mVertData.GetValue(index);
                        if (fvd.compare(FoliageManager.cEmptyVertData))
                        {
                            continue;
                        }

                        if (FoliageManager.giveIndexOfSet(fvd.mFoliageSetName) == FoliageManager.giveIndexOfSet(mSetsUsed[setI]))
                        {
                            int localIndex = x + FoliageManager.cNumXBladesPerChunk * z;
                            validIndexes.Add(localIndex);
                            validBladeIndexes.Add(fvd.mFoliageSetBladeIndex);
                        }
                    }
                }

                if (validIndexes.Count == 0)
                {
                    //remove this set from us
                    mSetsUsed.RemoveAt(setI);
                    setI--;
                    continue;
                }

                //now that we have our valid indexes
                int numVertsPerBlade = 10;
                int totalNumVerts    = (validIndexes.Count * numVertsPerBlade);

                //VERTEX BUFFERS
                mSetVBs.Add(new VertexBuffer(typeof(VertexTypes.Pos), totalNumVerts, BRenderDevice.getDevice(), Usage.WriteOnly, VertexTypes.Pos.FVF_Flags, Pool.Default));

                GraphicsStream gStream = mSetVBs[setI].Lock(0, 0, LockFlags.None);
                unsafe
                {
                    VertexTypes.Pos *verts = (VertexTypes.Pos *)gStream.InternalDataPointer;

                    mSetVertCount.Add(0);
                    //ADD OTHER STRIPS
                    for (int i = 0; i < validIndexes.Count; i++)
                    {
                        int vC = mSetVertCount[setI];

                        int startInd = validIndexes[i] * numVertsPerBlade;
                        //add 10 verts with:  index (x*width+z), bladeIndex, 0, 0
                        for (int k = 0; k < numVertsPerBlade; k++)
                        {
                            verts[vC].x = startInd + k;
                            verts[vC].y = validBladeIndexes[i];

                            vC++;
                        }

                        mSetVertCount[setI] += numVertsPerBlade;
                    }
                }

                gStream.Close();
                mSetVBs[setI].Unlock();


                //INDEX BUFFERS (UGG WE SHOULD BE USING TRI-STRIPS!!!)
                int numInds = (validIndexes.Count * ((numVertsPerBlade - 2) * 3));
                mSetIBs.Add(new IndexBuffer(typeof(short), numInds, BRenderDevice.getDevice(), Usage.WriteOnly, Pool.Default));

                gStream = mSetIBs[setI].Lock(0, 0, LockFlags.None);
                unsafe
                {
                    short *inds = (short *)gStream.InternalDataPointer;

                    mSetPolyCount.Add(0);

                    //add first strip
                    short startInd = (short)(0);
                    int   vC       = 0;

                    for (int i = 0; i < validIndexes.Count; i++)
                    {
                        startInd = (short)(i * (numVertsPerBlade));

                        short pC = (short)((numVertsPerBlade - 2) >> 1);
                        short sI = 0;
                        for (int k = 0; k < pC; k++)
                        {
                            inds[vC++] = (short)(startInd + sI + 0);
                            inds[vC++] = (short)(startInd + sI + 1);
                            inds[vC++] = (short)(startInd + sI + 2);

                            inds[vC++] = (short)(startInd + sI + 1);
                            inds[vC++] = (short)(startInd + sI + 2);
                            inds[vC++] = (short)(startInd + sI + 3);
                            sI        += 2;
                        }


                        mSetPolyCount[setI] += (numVertsPerBlade - 2);
                    }
                }
                gStream.Close();
                mSetIBs[setI].Unlock();
            }

            //COOL!
        }
Exemple #12
0
        /// <summary>
        /// Grabs the next frame of video obtained
        /// from the VMR9 and return it as an RGB image
        /// </summary>
        /// <returns>Returns null on failure or a Bitmap object</returns>
        public Bitmap GetCurrentImage()
        {
            lock (grabFrame)
            {
                try
                {
                    //Log.Debug("GetCurrentImage called");

                    if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR &&
                        GUIGraphicsContext.Vmr9Active)
                    {
                        lock (grabNotifier)
                        {
                            if (VMR9Util.g_vmr9?._syncRoot != null)
                            {
                                lock (VMR9Util.g_vmr9?._syncRoot)
                                {
                                    if (VMR9Util.g_vmr9 != null && !VMR9Util.g_vmr9._exitThread)
                                    {
                                        try
                                        {
                                            if (FrameResult != null)
                                            {
                                                FrameResult.SafeDispose();
                                                FrameResult = null;
                                            }

                                            // Grab frame
                                            //VMR9Util.g_vmr9.GrabCurrentFrame(); // Using C# WIP
                                            VMR9Util.g_vmr9.MadVrGrabCurrentFrame();

                                            if (GUIGraphicsContext.madVRCurrentFrameBitmap != null)
                                            {
#if DEBUG
                                                string directory = string.Format("{0}\\MediaPortal Screenshots\\{1:0000}-{2:00}-{3:00}",
                                                                                 Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                                                                                 DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                                                if (!Directory.Exists(directory))
                                                {
                                                    Log.Info("GetCurrentImage: Taking screenshot - Creating directory: {0}", directory);
                                                    Directory.CreateDirectory(directory);
                                                }
                                                string fileName = string.Format("{0}\\madVR - {1:00}-{2:00}-{3:00}-{4:000}", directory,
                                                                                DateTime.Now.Hour,
                                                                                DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond);
#endif
                                                FrameResult = new Bitmap(GUIGraphicsContext.madVRCurrentFrameBitmap);
#if DEBUG
                                                // Need to be commented out for saving screenshot frame
                                                //FrameResult.Save(fileName + ".jpg", ImageFormat.Jpeg);
#endif
                                                return(FrameResult);
                                            }
                                            // Bitmap not ready return null
                                            Log.Debug("FrameGrabber: Frame not ready for madVR");
                                            return(null);
                                        }
                                        catch
                                        {
                                            Log.Debug("FrameGrabber: Frame grab catch failed for madVR");
                                            return(null);
                                            // When Bitmap is not yet ready
                                        }
                                    }
                                }
                            }

                            //////// Part of code used for D3D9 setting in madVR
                            //////lock (grabNotifier)
                            //////{
                            //////  grabSucceeded = false;
                            //////  grabSample = true;
                            //////  if (!Monitor.Wait(grabNotifier, 500))
                            //////  {
                            //////    Log.Debug("FrameGrabber: Timed-out waiting for grabbed frame!");
                            //////    return null;
                            //////  }

                            //////  if (grabSucceeded)
                            //////  {
                            //////    try
                            //////    {
                            //////      if (FrameResult != null)
                            //////      {
                            //////        FrameResult.SafeDispose();
                            //////        FrameResult = null;
                            //////      }

                            //////      if (GUIGraphicsContext.madVRFrameBitmap != null)
                            //////      {
                            //////        FrameResult = new Bitmap(GUIGraphicsContext.madVRFrameBitmap);
                            //////        return FrameResult;
                            //////      }
                            //////    }
                            //////    catch
                            //////    {
                            //////      Log.Debug("FrameGrabber: Frame grab catch failed for madVR");
                            //////      return null;
                            //////      // When Bitmap is not yet ready
                            //////    }
                            //////  }
                            //////}
                        }
                        // Bitmap not ready return null
                        Log.Debug("FrameGrabber: Frame grab failed for madVR");
                        return(null);
                    }

                    //// This code is used only for D3D9 so comment it for now
                    //if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR &&
                    //    GUIGraphicsContext.Vmr9Active && FrameGrabberD3D9Enable)
                    //{
                    //  Surface backbuffer = null;
                    //  Bitmap b = null;
                    //  try
                    //  {
                    //    backbuffer = GUIGraphicsContext.DX9DeviceMadVr.GetBackBuffer(0, 0, BackBufferType.Mono);
                    //    using (var stream = SurfaceLoader.SaveToStream(ImageFileFormat.Bmp, backbuffer))
                    //    {
                    //      b = new Bitmap(Image.FromStream(stream));

                    //      // IMPORTANT: Closes and disposes the stream
                    //      // If this is not done we get a memory leak!
                    //      stream.Close();
                    //      stream.Dispose();
                    //      backbuffer.Dispose();
                    //      return b;
                    //    }
                    //  }
                    //  catch (Exception)
                    //  {
                    //    backbuffer?.Dispose();
                    //    b?.Dispose();
                    //    Log.Debug("FrameGrabber: Timed-out waiting for grabbed frame!");
                    //  }
                    //}
                    else if (GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR) // used for EVR
                    {
                        lock (grabNotifier)
                        {
                            grabSucceeded = false;
                            grabSample    = true;
                            if (!Monitor.Wait(grabNotifier, 500))
                            {
                                Log.Debug("FrameGrabber: Timed-out waiting for grabbed frame!");
                                return(null);
                            }

                            if (grabSucceeded)
                            {
                                using (GraphicsStream stream = SurfaceLoader.SaveToStream(ImageFileFormat.Bmp, rgbSurface))
                                {
                                    Bitmap b = new Bitmap(Image.FromStream(stream));

                                    // IMPORTANT: Closes and disposes the stream
                                    // If this is not done we get a memory leak!
                                    stream.Close();
                                    return(b);
                                }
                            }
                            Log.Debug("FrameGrabber: Frame grab failed");
                            return(null);
                        }
                    }
                    else
                    {
                        Log.Debug("FrameGrabber: Frame grab failed");
                        return(null);
                    }
                }
                catch (Exception e) // Can occur for example if the video device is lost
                {
                    Log.Debug(e.ToString());
                    return(null);
                }
                // Not image grabbed
                return(null);
            }
        }
Exemple #13
0
        /// <summary>
        /// Static method to calculate tangents along with the handedness of the tangents.
        /// </summary>
        /// <param name="model">Model to calculate the tangents on.</param>
        public static void CalculateTangents(Mesh model)
        {
            // Get a copy of the buffers.
            GraphicsStream ib = model.LockIndexBuffer(LockFlags.None);
            GraphicsStream vb = model.LockVertexBuffer(LockFlags.None);

            // List of the final vertex list.
            List <Vertex> final = new List <Vertex>();

            // Temperary lists to store vectors in.
            List <Vector3> tan1 = new List <Vector3>(model.NumberVertices);
            List <Vector3> tan2 = new List <Vector3>(model.NumberVertices);

            // Loop through and copy the vertex list from the vertex buffer
            // and to also add empty values to tan1 and tan2.
            for (int i = 0; i < model.NumberVertices; i++)
            {
                final.Add((Vertex)vb.Read(typeof(Vertex)));
                tan1.Add(new Vector3());
                tan2.Add(new Vector3());
            }

            // Various variables used in the calculation.
            int     i1, i2, i3;
            Vector3 v1, v2, v3;
            Vector2 w1, w2, w3;

            float x1, x2, y1, y2, z1, z2;
            float s1, s2, t1, t2, r;

            // Loop through and calculate the tangent information.
            for (int i = 0; i < model.NumberFaces; i++)
            {
                i1 = (int)ib.Read(typeof(int));
                i2 = (int)ib.Read(typeof(int));
                i3 = (int)ib.Read(typeof(int));

                // Get the vertex values for the 3 vertices of a face.
                Vertex vertex1 = final[i1];
                Vertex vertex2 = final[i2];
                Vertex vertex3 = final[i3];

                // Get the positions.
                v1 = vertex1.Position;
                v2 = vertex2.Position;
                v3 = vertex3.Position;

                // Get the texture coordinates.
                w1 = vertex1.TexCoord;
                w2 = vertex2.TexCoord;
                w3 = vertex3.TexCoord;

                x1 = v2.X - v1.X;
                x2 = v3.X - v1.X;
                y1 = v2.Y - v1.Y;
                y2 = v3.Y - v1.Y;
                z1 = v2.Z - v1.Z;
                z2 = v3.Z - v1.Z;

                s1 = w2.X - w1.X;
                s2 = w3.X - w1.X;
                t1 = w2.Y - w1.Y;
                t2 = w3.Y - w1.Y;

                r = 1.0F / (s1 * t2 - s2 * t1);

                // Calculate the direction of the vector
                Vector3 sdir = new Vector3((t2 * x1 - t1 * x2) * r,
                                           (t2 * y1 - t1 * y2) * r,
                                           (t2 * z1 - t1 * z2) * r);
                // Calculate the direction of the uv
                Vector3 tdir = new Vector3((s1 * x2 - s2 * x1) * r,
                                           (s1 * y2 - s2 * y1) * r,
                                           (s1 * z2 - s2 * z1) * r);

                Vector3 temp1 = tan1[i1];
                Vector3 temp2 = tan1[i2];
                Vector3 temp3 = tan1[i3];
                Vector3 temp4 = tan2[i1];
                Vector3 temp5 = tan2[i2];
                Vector3 temp6 = tan2[i3];

                tan1[i1] = temp1 + sdir;
                tan1[i2] = temp2 + sdir;
                tan1[i3] = temp3 + sdir;

                tan2[i1] = temp4 + tdir;
                tan2[i2] = temp5 + tdir;
                tan2[i3] = temp6 + tdir;
            }

            for (int i = 0; i < model.NumberVertices; i++)
            {
                Vertex tempVertex = final[i];

                Vector3 n = tempVertex.Normal;
                Vector3 t = tan1[i];

                Vector3 temp = (t - n * Vector3.Dot(n, t));
                temp.Normalize();

                // Gram-Schmidt orthogonalize
                tempVertex.Tangent = new Vector4(temp.X, temp.Y, temp.Z, 1.0f);

                // Calculate the handedness
                tempVertex.Tangent.W = (Vector3.Dot(Vector3.Cross(n, t), tan2[i]) < 0.0F) ? -1.0F : 1.0F;

                final[i] = tempVertex;
            }

            ib.Close();
            vb.Close();

            model.SetVertexBufferData(final.ToArray(), LockFlags.None);
        }
Exemple #14
0
        public void toTextureArray(ref List <Texture> mTempAlphaTextures, int minXVert, int minZVert)
        {
            bool doBlendedFill = true;

            //lock in our alpha texture
            int slicePitch = (int)(BTerrainTexturing.getAlphaTextureWidth() * BTerrainTexturing.getAlphaTextureHeight());
            int count      = Math.Min(mTempAlphaTextures.Count, mLayers.Count);

            int width  = (int)BTerrainTexturing.getAlphaTextureWidth();
            int height = (int)BTerrainTexturing.getAlphaTextureHeight();

            byte[] tempLargerImg = new byte[(width + 2) * (height + 2)];
            byte[] bordered      = new byte[width * height];

            int i = 0;

            for (i = 0; i < count; i++)
            {
                if (mTempAlphaTextures[i] != null)
                {
                    GraphicsStream texstream = mTempAlphaTextures[i].LockRectangle(0, LockFlags.None);
                    if (i == 0)
                    {
                        for (int k = 0; k < slicePitch; k++)
                        {
                            texstream.WriteByte(255);
                        }
                    }
                    else
                    {
                        if (doBlendedFill)
                        {
                            fillCreateLayer(mLayers[i].mAlphaLayer, mLayers[i].mActiveTextureIndex, mLayers[i].mLayerType, minXVert, minZVert, tempLargerImg, bordered);
                            texstream.Write(bordered, 0, slicePitch);
                        }
                        else
                        {
                            texstream.Write(mLayers[i].mAlphaLayer, 0, slicePitch);
                        }
                    }

                    mTempAlphaTextures[i].UnlockRectangle(0);
                    texstream.Close();
                }
                else
                {
                }
            }

            //we've got more layers than we've preallocated
            if (mTempAlphaTextures.Count < mLayers.Count)
            {
                int diff = mLayers.Count - mTempAlphaTextures.Count;
                for (int k = 0; k < diff; k++)
                {
                    mTempAlphaTextures.Add(new Texture(BRenderDevice.getDevice(), (int)BTerrainTexturing.getAlphaTextureWidth(), (int)BTerrainTexturing.getAlphaTextureHeight(), 1, 0, Format.L8, Pool.Managed));

                    GraphicsStream texstream = mTempAlphaTextures[mTempAlphaTextures.Count - 1].LockRectangle(0, LockFlags.None);
                    if (doBlendedFill)
                    {
                        fillCreateLayer(mLayers[i + k].mAlphaLayer, mLayers[i + k].mActiveTextureIndex, mLayers[i + k].mLayerType, minXVert, minZVert, tempLargerImg, bordered);
                        texstream.Write(bordered, 0, slicePitch);
                    }
                    else
                    {
                        texstream.Write(mLayers[i + k].mAlphaLayer, 0, slicePitch);
                    }

                    mTempAlphaTextures[mTempAlphaTextures.Count - 1].UnlockRectangle(0);
                    texstream.Close();
                }
            }

            tempLargerImg = null;
        }