Beispiel #1
0
        public TgcDrawText(Device d3dDevice)
        {
            textSprite = new Sprite(d3dDevice);

            //Fuente default
            dxFont = new Microsoft.DirectX.Direct3D.Font(d3dDevice, VERDANA_10);
        }
Beispiel #2
0
        public override void OnInitializeScene(GameFramework g)
        {
            BindGameController();

            font_small = g.CANVAS.CreateFont(new System.Drawing.Font("Arial", 12));
            font_large = g.CANVAS.CreateFont(new System.Drawing.Font("Arial", 28));
            menu = new PanelMenu(font_small, new PanelMenuSelectHandler(MenuHandler));
            menu.ForegroundColor = Color.White;
            menu.BackgroundColor = Color.Black;
            menu.BorderColor = Color.White;

            //menu.ScrollButtonWidth = 20;
            menu.SetHeight(100);
            menu.SetPosition(200, 200);
            menu.SetWidth(100);
            //menu.DrawFormat = DrawTextFormat.None;

            int height = menu.LayoutMenuOptions(new string[] {
                "item1",
                "item2",
                "item3",
                "item4",
                "item5",
                 "item6",
                "item7",
                "item8 ",
                "item9 ",
                "item10"
            }, PanelLayout.HorizontalFree);
 


        }
Beispiel #3
0
        /// <summary>
        /// Constructs the font object using the desired font family. If the desired family
        /// is not supported, the fallback family defined in the Settings file is used.
        /// </summary>
        public Font(Renderer renderer, string familyName, int height)
        {
            this.renderer = renderer;
            this.familyName = familyName;
            this.height = height + 5;

            // Attempt to create the Windows font object
            try
            {
                windowsFont = new System.Drawing.Font(familyName, this.height,
                    System.Drawing.FontStyle.Regular);
            }
            catch
            {
                // Attempt to create the font using the "fallback" font family
                // defined in the Settings file
                Log.Write("The desired font family was not available. Falling back on the default " +
                    "family defined in the Settings file.");
                windowsFont = new System.Drawing.Font(Dynamic2DLighting.Properties.Settings.Default.FallbackFontFamily,
                    this.height, System.Drawing.FontStyle.Regular);
            }

            d3dFont = new Direct3D.Font(renderer.Device, windowsFont);
            textSprite = new Direct3D.Sprite(renderer.Device);

            renderer.AddGraphicsObject(this);
        }
Beispiel #4
0
 public Engine_Font(string typeFace, float size, FontStyle fontStyle)
 {
     using (GDIFont gdiFont = new GDIFont(typeFace, size, fontStyle))
     {
         m_Font = new D3DFont(Engine_Game.DGDevice, gdiFont);
     }
 }
 /// <summary>
 /// A constructor that creates a new font
 /// </summary>
 /// <param name="device">Direct3D Device</param>
 /// <param name="faceName">Font face name</param>
 /// <param name="size">Size of the font</param>
 /// <param name="bold">true for bold text, false for normal text</param>
 /// <param name="italic">true for italic text, false for normal text</param> 
 public SimpleD3DFont(Device device, string faceName, int size, bool bold, bool italic)
 {
     m_size = size;
     m_font = new Microsoft.DirectX.Direct3D.Font(device, -size, 0,
     (bold) ? FontWeight.Bold : FontWeight.Normal, 1, italic,
     CharacterSet.Default, Precision.Default, FontQuality.Default,
     PitchAndFamily.DefaultPitch | PitchAndFamily.FamilyDoNotCare, faceName);
 }
        public void Init(Device device)
        {
            this.device = device;

            font = new Microsoft.DirectX.Direct3D.Font(device, 14, 0, FontWeight.SemiBold,
                                                       1, false, CharacterSet.Ansi,
                                                       Precision.Default, FontQuality.AntiAliased,
                                                       PitchAndFamily.DefaultPitch, "Segoe UI");
        }
Beispiel #7
0
        /// <summary>
        /// Creates a form for the Turret game
        /// </summary>
        public Game()
        {
            InitializeWindow();
            InitializeInputDevices();
            InitializeGraphics();
            InitializeGame();

            theFont = new D3DFont(device, systemFont);
        }
Beispiel #8
0
        /// <summary>
        /// ����������
        /// </summary>
        /// <param name="family">��������</param>
        /// <param name="size">�����С</param>
        public static void InitializeFont()
        {
            if (font != null)
                font = null;
            System.Drawing.Font sf = new System.Drawing.Font(fontFamily, fontSize);
            font = new Microsoft.DirectX.Direct3D.Font(EngineSrv.device, sf);

            LoadFrame();
        }
Beispiel #9
0
        public EditorWindow()
        {
            InitializeComponent();
            InitGraphics();
            InitInput();

            frames = new List<EditorFrame>();
            frameIndex = -1;
            font = new Microsoft.DirectX.Direct3D.Font(device, 16, 8, FontWeight.Normal, 0, false, CharacterSet.Ansi, Precision.Default, FontQuality.Default, PitchAndFamily.DefaultPitch, "Arial");
        }
Beispiel #10
0
        /// <summary>
        /// Handles GUI creation and drawing.
        /// </summary>
        /// <param name="p">The player, a Turret.</param>
        /// <param name="healthA">Area for health on screen.</param>
        /// <param name="healthP">Point for health on screen.</param>
        /// <param name="device">The graphics device.</param>
        /// <param name="w">Width of the screen.</param>
        /// <param name="h">Height of the screen.</param>
        public GUI(Turret p, Rectangle healthA, Point healthP,
            Device device, int w, int h)
        {
            this.healthArea = healthA;
            this.healthTexturePoint = healthP;
            this.device = device;
            this.width = w;
            this.height = h;
            this.player = p;

            font = new D3DFont(device, sysFont);
        }
Beispiel #11
0
        public override void OnInitializeScene(GameFramework g)
        {
            BindGameController();

            
           
            //font_small = g.CANVAS.CreateFont(new System.Drawing.Font("Arial", 12));
            font_small = g.CANVAS.CreateFont(new System.Drawing.Font("MS Sans Serif", 14));

            font_large = g.CANVAS.CreateFont(new System.Drawing.Font("Arial", 28));

        }
Beispiel #12
0
 public Lives(Device device)
 {
     //create the font
     font = new Microsoft.DirectX.Direct3D.Font(device,  // Device we are drawing on
         20,         // Font height in pixels
         0,          // Font width in pixels or zero to match height
         FontWeight.Bold,    // Font weight (Normal, Bold, etc.)
         0,          // mip levels (0 for default)
         false,      // italics?
         CharacterSet.Default,   // Character set to use
         Precision.Default,      // The font precision, try some of them...
         FontQuality.Default,    // Quality?
         PitchAndFamily.FamilyDoNotCare,     // Pitch and family, we don't care
         "Arial");               // And the name of the font
 }
Beispiel #13
0
        public void Init(Device device)
        {
            // create angle lines
            line = new Line(device);
            line.Antialias = true;
            line.Width = 1;
            //line.Pattern = (int)0xFFF0;
            //line.PatternScale = 1.0f;

            // create text sprite
            font = new Microsoft.DirectX.Direct3D.Font(device, 12, 0, FontWeight.Bold, 1, false,
                                                       CharacterSet.Ansi, Precision.Default, FontQuality.ClearType,
                                                       PitchAndFamily.DefaultPitch, "Tahoma");

            points = new Vector2[3];

            // calc angle to -/+ degrees
            angle = 90;// (180 / Math.PI) * BondTools.giveAngleFromMiddle(atom2, atom1, atom3);
            // round for text
            angleText = Math.Round(angle, 1).ToString() + (char)176;

            // calc world arc points
            arcWorldPoints = new Vector3[3];
            arcPoints = new Vector2[3];
            Vector3 a1 = new Vector3((float)atom1.X3d, (float)atom1.Y3d, (float)atom1.Z3d);
            Vector3 a2 = new Vector3((float)atom2.X3d, (float)atom2.Y3d, (float)atom2.Z3d);
            Vector3 a3 = new Vector3((float)atom3.X3d, (float)atom3.Y3d, (float)atom3.Z3d);
            
            Vector3 arm1 = a2 - a1;
            float arm1Len = arm1.Length();
            arm1.Normalize();
            Vector3 arcStartPos = arm1 * (arm1Len * 0.3f);

            Vector3 arm2 = a2 - a3;
            arm2.Normalize();
            Vector3 arcEndPos = arm2 * (arm1Len * 0.3f);

            arcWorldPoints[0] = a2 - arcStartPos;
            arcWorldPoints[2] = a2 - arcEndPos;

            Vector3 arm3 = ((arcWorldPoints[0] - arcWorldPoints[2]) * 0.5f) + arcWorldPoints[2];
            arm3 = a2 - arm3;
            arm3.Normalize();
            arcWorldPoints[1] = a2 - (arm3 * (arm1Len * 0.35f));
        }
Beispiel #14
0
        public static void Initialize(Microsoft.DirectX.Direct3D.Device device)
        {
            Fonts = new Dictionary<int, Microsoft.DirectX.Direct3D.Font>();
            //FontFamily[] fontFamily = FontFamily.Families; все поддерживаемые шрифты

            System.Drawing.Font font = new System.Drawing.Font("Constantia", 13.5f);
            Microsoft.DirectX.Direct3D.Font Font = new Microsoft.DirectX.Direct3D.Font(device, font);
            Fonts.Add((int)OurFonts.mainMenu, Font);

            font = new System.Drawing.Font("Arial", 10.5f);
            Font = new Microsoft.DirectX.Direct3D.Font(device, font);
            Fonts.Add((int)OurFonts.settingMenu, Font);

            font = new System.Drawing.Font("Arial", 7.0f);
            Font = new Microsoft.DirectX.Direct3D.Font(device, font);
            Fonts.Add((int)OurFonts.smallFont, Font);

            font = new System.Drawing.Font("Arial", 8.5f);
            Font = new Microsoft.DirectX.Direct3D.Font(device, font);
            Fonts.Add((int)OurFonts.infoFont, Font);
        }
Beispiel #15
0
        public void Render1()
        {
            dx_device.Clear(ClearFlags.Target | ClearFlags.ZBuffer | ClearFlags.Stencil, Color.Blue, 1.0f, 0);

            dx_device.BeginScene();
            dx_device.SetTexture(0, m_Tex);

            dx_device.SetTransform(TransformType.World, m_Camera.m_World);
            dx_device.SetTransform(TransformType.View, m_Camera.m_View);
            dx_device.SetTransform(TransformType.Projection, m_Camera.m_Projection);

            // 원래 객체를 그린다.
            dx_device.RenderState.ShadeMode = ShadeMode.Gouraud;
            dx_device.RenderState.CullMode = Cull.None;
            dx_device.RenderState.ZBufferWriteEnable = true;
            dx_device.RenderState.StencilEnable = false;
            dx_device.RenderState.AlphaBlendEnable = false;
            //            m_Objects[4].render(dx_device);

            // 그림자 영역을 그린다.
            dx_device.RenderState.ZBufferWriteEnable = false;
            dx_device.RenderState.StencilEnable = true;
            dx_device.RenderState.ShadeMode = ShadeMode.Flat;
            dx_device.RenderState.StencilFunction = Compare.Always;
            dx_device.RenderState.StencilZBufferFail = StencilOperation.Keep;
            dx_device.RenderState.StencilFail = StencilOperation.Keep;
            dx_device.RenderState.ReferenceStencil = 1;
            dx_device.RenderState.StencilMask = -1;
            dx_device.RenderState.StencilWriteMask = -1;
            dx_device.RenderState.StencilPass = StencilOperation.Increment;
            dx_device.RenderState.AlphaBlendEnable = true;
            dx_device.RenderState.SourceBlend = Blend.Zero;
            dx_device.RenderState.DestinationBlend = Blend.One;

            dx_device.Transform.World = m_Camera.m_ShadowWorld;
            m_Objects[4].render(dx_device);
            dx_device.Transform.World = m_Camera.m_World;

            // 원래 객체를 그린다.
            dx_device.RenderState.ShadeMode = ShadeMode.Gouraud;
            dx_device.RenderState.CullMode = Cull.None;
            dx_device.RenderState.ZBufferWriteEnable = true;
            dx_device.RenderState.StencilEnable = false;
            dx_device.RenderState.AlphaBlendEnable = false;
            m_Objects[0].render(dx_device);
            m_Objects[1].render(dx_device);
            m_Objects[4].render(dx_device);

            // 그림자에 해당하는 부분을 다시 그린다.
            dx_device.RenderState.ZBufferEnable = true;
            dx_device.RenderState.ZBufferWriteEnable = false;
            dx_device.RenderState.StencilEnable = true;
            dx_device.RenderState.AlphaBlendEnable = true;
            dx_device.RenderState.SourceBlend = Blend.SourceAlpha;
            dx_device.RenderState.DestinationBlend = Blend.InvSourceAlpha;

            dx_device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor;
            dx_device.TextureState[0].ColorArgument2 = TextureArgument.Constant;
            dx_device.TextureState[0].ColorOperation = TextureOperation.SelectArg2;
            dx_device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor;
            dx_device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse;
            dx_device.TextureState[0].AlphaOperation = TextureOperation.Modulate;

            dx_device.RenderState.ReferenceStencil = 1;
            dx_device.RenderState.StencilFunction = Compare.LessEqual;
            dx_device.RenderState.StencilPass = StencilOperation.Keep;

            m_Objects[0].render(dx_device);

            dx_device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor;
            dx_device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse;
            dx_device.TextureState[0].ColorOperation = TextureOperation.Modulate;
            dx_device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor;
            dx_device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse;
            dx_device.TextureState[0].AlphaOperation = TextureOperation.Modulate;

            dx_device.RenderState.ShadeMode = ShadeMode.Gouraud;
            dx_device.RenderState.CullMode = Cull.None;
            dx_device.RenderState.ZBufferWriteEnable = true;
            dx_device.RenderState.StencilEnable = false;
            dx_device.RenderState.AlphaBlendEnable = false;

            FontDescription desc = new FontDescription();
            Microsoft.DirectX.Direct3D.Font fnt = new Microsoft.DirectX.Direct3D.Font(dx_device, desc);

            fnt.DrawText(null, m_Camera.ToString() + "\n"
                + m_Cursor.ToString() + "\n"
                + m_Camera.getPicking(m_Cursor.m_MousePoint, dx_device.Viewport) + "\n"
                + m_Count, new Point(5, 5), Color.White);

            m_Count = (m_Count + 1) % 10000;

            fnt.Dispose();

            dx_device.EndScene();

            dx_device.Present();
        }
Beispiel #16
0
        public override int Render(DrawArgs drawArgs, int xOffset, int yOffset)
        {
            m_ConsumedSize.Height = 0;
            if (m_textFont == null)
            {
                System.Drawing.Font localHeaderFont = new System.Drawing.Font("Arial", 12.0f, FontStyle.Bold);
                m_textFont = new Microsoft.DirectX.Direct3D.Font(drawArgs.device, localHeaderFont);
            }
            if (m_visible)
            {
                if (!m_isInitialized)
                {
                    this.Initialize(drawArgs);
                }

                m_ConsumedSize.Height = NODE_HEIGHT;

                // This value is dynamic based on the number of expanded nodes above this one
                m_location.Y = yOffset;

                // store this value so the mouse events can figure out where the buttons are
                m_xOffset = xOffset;

                // compute the color
                int color = this.Enabled ? m_itemOnColor : m_itemOffColor;

                // create the bounds of the text draw area
                Rectangle bounds = new Rectangle(this.AbsoluteLocation, new System.Drawing.Size(this.ClientSize.Width, NODE_HEIGHT));

                if (m_isMouseOver)
                {
                    if (!Enabled)
                    {
                        color = m_mouseOverOffColor;
                    }

                    WidgetUtilities.DrawBox(
                        bounds.X,
                        bounds.Y,
                        bounds.Width,
                        bounds.Height,
                        0.0f,
                        m_mouseOverColor,
                        drawArgs.device);
                }

                #region Draw arrow

                bounds.X     = this.AbsoluteLocation.X + xOffset;
                bounds.Width = NODE_ARROW_SIZE;
                // draw arrow if any children
                if (m_subNodes.Count > 0)
                {
                    m_worldwinddingsFont.DrawText(
                        null,
                        (this.m_isExpanded ? "L" : "A"),
                        bounds,
                        DrawTextFormat.None,
                        color);
                }
                #endregion Draw arrow

                #region Draw checkbox

                bounds.Width = NODE_CHECKBOX_SIZE;
                bounds.X    += NODE_ARROW_SIZE;

                // Normal check symbol
                string checkSymbol;

                if (m_isRadioButton)
                {
                    checkSymbol = this.IsChecked ? "O" : "P";
                }
                else
                {
                    checkSymbol = this.IsChecked ? "N" : "F";
                }

                m_worldwinddingsFont.DrawText(
                    null,
                    checkSymbol,
                    bounds,
                    DrawTextFormat.NoClip,
                    color);

                #endregion draw checkbox

                #region Draw update

                bounds.X    += NODE_CHECKBOX_SIZE;
                bounds.Width = NODE_UPDATE_SIZE;

                string updateSymbol = "U";

                //m_worldwinddingsFont
                m_textFont.DrawText(null, updateSymbol, bounds, DrawTextFormat.NoClip, color);

                #endregion draw update


                #region Draw name

                // compute the length based on name length
                // TODO: Do this only when the name changes
                Rectangle stringBounds = drawArgs.defaultDrawingFont.MeasureString(null, Name, DrawTextFormat.NoClip, 0);
                m_size.Width         = NODE_ARROW_SIZE + NODE_CHECKBOX_SIZE + NODE_UPDATE_SIZE + 5 + stringBounds.Width;
                m_ConsumedSize.Width = m_size.Width;

                bounds.Y    += 2;
                bounds.X    += NODE_UPDATE_SIZE + 5;
                bounds.Width = stringBounds.Width;

                drawArgs.defaultDrawingFont.DrawText(
                    null,
                    Name,
                    bounds,
                    DrawTextFormat.None,
                    color);

                #endregion Draw name

                if (m_isExpanded)
                {
                    int newXOffset = xOffset + NODE_INDENT;

                    for (int i = 0; i < m_subNodes.Count; i++)
                    {
                        if (m_subNodes[i] is TreeNodeWidget)
                        {
                            m_ConsumedSize.Height += ((TreeNodeWidget)m_subNodes[i]).Render(drawArgs, newXOffset, m_ConsumedSize.Height);
                        }
                        else
                        {
                            System.Drawing.Point newLocation = m_subNodes[i].Location;
                            newLocation.Y          = m_ConsumedSize.Height;
                            newLocation.X          = newXOffset;
                            m_ConsumedSize.Height += m_subNodes[i].WidgetSize.Height;
                            m_subNodes[i].Location = newLocation;
                            m_subNodes[i].Render(drawArgs);
                            // render normal widgets as a stack of widgets
                        }

                        // if the child width is bigger than my width save it as the consumed width for widget size calculations
                        if (m_subNodes[i].WidgetSize.Width + newXOffset > m_ConsumedSize.Width)
                        {
                            m_ConsumedSize.Width = m_subNodes[i].WidgetSize.Width + newXOffset;
                        }
                    }
                }
            }
            return(m_ConsumedSize.Height);
        }
Beispiel #17
0
        public override void OnInitialize(Microsoft.DirectX.Direct3D.Device d)
        {
            ShowMouseCursor = true;
            d.RenderState.Lighting = true;

            d.RenderState.FillMode = FillMode.Solid;
            d.RenderState.ZBufferEnable = true;
            
            d.RenderState.ShadeMode = ShadeMode.Phong;
            d.RenderState.SpecularEnable = true;
            d.RenderState.AntiAliasedLineEnable = true;
            d.RenderState.MultiSampleAntiAlias = true;
            d.RenderState.Ambient = Color.White;
            

            d.Lights[0].Diffuse = Color.White;
            d.Lights[0].Type = LightType.Directional;
            d.Lights[0].Falloff = 132f;
            d.Lights[0].InnerConeAngle = 10;
            d.Lights[0].OuterConeAngle = 20;
            d.Lights[0].Specular = Color.White;
            d.Lights[0].Position = new Vector3(0, 0, -100);
            d.Lights[0].Direction = new Vector3(0, 0, 1);

            d.Lights[0].Update();
            d.Lights[0].Enabled = true;

            _Projection_ = Matrix.PerspectiveFovLH(.8f, (float)d.Viewport.Width / (float)d.Viewport.Height, 1.0f, 100.0f);
            _View_ = Matrix.LookAtLH(new Vector3(0, 0, -4f), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
            
            selected_material.Diffuse = Color.Yellow;
            selected_material.Specular = Color.White;
            selected_material.SpecularSharpness = 32f;

            teapot_material.Diffuse = Color.DodgerBlue;
            teapot_material.Specular = Color.White;
            teapot_material.SpecularSharpness = 32f;

            font = new Microsoft.DirectX.Direct3D.Font(d, new System.Drawing.Font("Arial", 12));


            teapot = Mesh.Teapot(d);
            _Line_ = new Microsoft.DirectX.Direct3D.Line(d);

            RenderLayers.Add(new RenderableLayer(this.Layer1));
            RenderLayers.Add(new RenderableLayer(this.Layer2));


            /* Remember to set the appropriate State, or risk being stuck in INIT
             *  forever.  To begin rendering set the scene state to RENDER.
             * */
            State = SceneState.RENDER;
        }
        /// <summary>
        /// Cambia la fuente del texto
        /// </summary>
        /// <param name="font">Fuente del sistema</param>
        public void changeFont(System.Drawing.Font font)
        {
            Sprite sprite = GuiController.Instance.Text3d.TextSprite;

            d3dFont = new Microsoft.DirectX.Direct3D.Font(GuiController.Instance.D3dDevice, font);
        }
Beispiel #19
0
        public bool InitializeApplication(TSOForm form)
        {
            this.form = form;

            for (int i = 0; i < keysEnabled.Length; i++)
            {
                keysEnabled[i] = true;
            }
            form.KeyDown += new KeyEventHandler(form_OnKeyDown);
            form.KeyUp   += new KeyEventHandler(form_OnKeyUp);

            form.MouseDown += new MouseEventHandler(form_OnMouseDown);
            form.MouseMove += new MouseEventHandler(form_OnMouseMove);

            form.DragDrop  += new DragEventHandler(form_OnDragDrop);
            form.DragEnter += new DragEventHandler(form_OnDragEnter);

            PresentParameters pp = new PresentParameters();

            try
            {
                pp.Windowed               = true;
                pp.SwapEffect             = SwapEffect.Discard;
                pp.BackBufferFormat       = Format.X8R8G8B8;
                pp.BackBufferCount        = 1;
                pp.EnableAutoDepthStencil = true;
                pp.AutoDepthStencilFormat = DepthFormat.D16;

                int adapter_ordinal = Manager.Adapters.Default.Adapter;

                int ret, quality;
                if (Manager.CheckDeviceMultiSampleType(adapter_ordinal, DeviceType.Hardware, pp.BackBufferFormat, pp.Windowed, MultiSampleType.FourSamples, out ret, out quality))
                {
                    pp.MultiSample        = MultiSampleType.FourSamples;
                    pp.MultiSampleQuality = quality - 1;
                }

                CreateFlags flags = CreateFlags.SoftwareVertexProcessing;
                Caps        caps  = Manager.GetDeviceCaps(adapter_ordinal, DeviceType.Hardware);
                if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
                {
                    flags = CreateFlags.HardwareVertexProcessing;
                }
                if (caps.DeviceCaps.SupportsPureDevice)
                {
                    flags |= CreateFlags.PureDevice;
                }
                device = new Device(adapter_ordinal, DeviceType.Hardware, form.Handle, flags, pp);

                FontDescription fd = new FontDescription();
                fd.Height   = 24;
                fd.FaceName = "MS Gothic";
                font        = new Direct3D.Font(device, fd);
            }
            catch (DirectXException ex)
            {
                Console.WriteLine("Error: " + ex);
                return(false);
            }

            Directory.SetCurrentDirectory(Application.StartupPath);

            boneMatrices = new Matrix[maxBones];

            string effect_file = @"toonshader.cgfx";

            if (!File.Exists(effect_file))
            {
                Console.WriteLine("File not found: " + effect_file);
                return(false);
            }
            string compile_error;

            effect = Effect.FromFile(device, effect_file, null, ShaderFlags.None, null, out compile_error);
            if (compile_error != null)
            {
                Console.WriteLine(compile_error);
                return(false);
            }
            handle_LocalBoneMats = effect.GetParameter(null, "LocalBoneMats");

            int devw = 0;
            int devh = 0;

            using (Surface surface = device.DepthStencilSurface)
            {
                devw = surface.Description.Width;
                devh = surface.Description.Height;
            }
            Console.WriteLine("dev {0}x{1}", devw, devh);

            dev_surface = device.GetRenderTarget(0);
            dev_zbuf    = device.DepthStencilSurface;

            camera.Update();
            camera.SetTranslation(camTranslation);

            Transform_Projection = Matrix.PerspectiveFovLH(
                Geometry.DegreeToRadian(30.0f),
                (float)device.Viewport.Width / (float)device.Viewport.Height,
                1.0f,
                1000.0f);

            // xxx: for w-buffering
            device.Transform.Projection = Transform_Projection;

            if (effect != null)
            {
                effect.SetValue("proj", Transform_Projection);
            }

            device.RenderState.Lighting = false;
            device.RenderState.CullMode = Cull.CounterClockwise;

            device.RenderState.AlphaBlendEnable = true;
            device.SetTextureStageState(0, TextureStageStates.AlphaOperation, (int)TextureOperation.Modulate);
            device.SetTextureStageState(0, TextureStageStates.AlphaArgument1, (int)TextureArgument.TextureColor);
            device.SetTextureStageState(0, TextureStageStates.AlphaArgument2, (int)TextureArgument.Current);

            device.RenderState.SourceBlend      = Blend.SourceAlpha;
            device.RenderState.DestinationBlend = Blend.InvSourceAlpha;

            device.RenderState.IndexedVertexBlendEnable = true;

            current_tmo = new TMOFile();
            return(true);
        }
 public static void DrawText(Font fnt, float xpos, float ypos, Color color, string text, int maxWidth, int fontHeight)
 {
   FontManagerDrawText draw;
   draw.fontHeight = fontHeight;
   draw.fnt = fnt;
   draw.xpos = xpos;
   draw.ypos = ypos;
   draw.color = (uint)color.ToArgb();
   draw.text = text;
   draw.matrix = (float[,])GUIGraphicsContext.GetFinalMatrix().Clone();
   draw.viewport = GUIGraphicsContext.DX9Device.Viewport;
   if (maxWidth >= 0)
   {
     draw.viewport.Width = ((int)GUIGraphicsContext.GetFinalTransform().TransformXCoord(xpos + maxWidth, 0, 0)) -
                           draw.viewport.X;
   }
   _listDrawText.Add(draw);
   _d3dxSpriteUsed = true;
 }
Beispiel #21
0
        /// <summary>
        /// Init the DirectX-Stuff here
        /// </summary>
        /// <param name="parent">parent of the DevicePanel</param>
        public void Init(Form parent)
        {
            try
            {
                _parent = parent;

                // Setup our D3D stuff
                presentParams            = new PresentParameters();
                presentParams.Windowed   = true;
                presentParams.SwapEffect = SwapEffect.Discard;

                Caps caps = Manager.GetDeviceCaps(Manager.Adapters.Default.Adapter, DeviceType.Hardware);

                CreateFlags createFlags;

                if (caps.DeviceCaps.SupportsHardwareTransformAndLight)
                {
                    createFlags = CreateFlags.HardwareVertexProcessing;
                }
                else
                {
                    createFlags = CreateFlags.SoftwareVertexProcessing;
                }

                if (caps.DeviceCaps.SupportsPureDevice && createFlags ==
                    CreateFlags.HardwareVertexProcessing)
                {
                    createFlags |= CreateFlags.PureDevice;
                }


                _device = new Device(0, DeviceType.Hardware, this,
                                     createFlags, presentParams);

                if (OnCreateDevice != null)
                {
                    OnCreateDevice(this, new DeviceEventArgs(_device));
                }

                parent.Show();
                parent.Focus();

                //vb = new VertexBuffer(typeof(CustomVertex.PositionTextured),
                //    4, _device, Usage.Dynamic | Usage.WriteOnly,
                //    CustomVertex.PositionTextured.Format, Pool.Default);

                sprite  = new Sprite(_device);
                sprite2 = new Sprite(_device);
                //_device.SetStreamSource(0, vb, 0);

                txb = new Bitmap(1, 1);
                using (Graphics g = Graphics.FromImage(txb))
                    g.Clear(Color.White);

                tx = new Texture(_device, txb, Usage.Dynamic, Pool.Default);

                tcircleb = new Bitmap(9, 9);
                using (Graphics g = Graphics.FromImage(tcircleb))
                    g.FillEllipse(Brushes.White, new Rectangle(0, 0, 9, 9));

                tcircle = new Texture(_device, tcircleb, Usage.Dynamic, Pool.Default);

                tecircleb = new Bitmap(14, 14);
                using (Graphics g = Graphics.FromImage(tecircleb))
                    g.DrawEllipse(new Pen(Brushes.White), new Rectangle(0, 0, 13, 13));

                tecircle = new Texture(_device, tecircleb, Usage.Dynamic, Pool.Default);

                hcursorb = new Bitmap(32, 32);
                using (Graphics g = Graphics.FromImage(hcursorb))
                    Cursors.NoMoveHoriz.Draw(g, new Rectangle(0, 0, 32, 32));

                MakeGray(hcursorb);

                hcursor = new Texture(_device, hcursorb, Usage.Dynamic, Pool.Default);

                vcursorb = new Bitmap(32, 32);
                using (Graphics g = Graphics.FromImage(vcursorb))
                    Cursors.NoMoveVert.Draw(g, new Rectangle(0, 0, 32, 32));

                MakeGray(vcursorb);

                vcursor = new Texture(_device, vcursorb, Usage.Dynamic, Pool.Default);

                hvcursorb = new Bitmap(32, 32);
                using (Graphics g = Graphics.FromImage(hvcursorb))
                    Cursors.NoMove2D.Draw(g, new Rectangle(0, 0, 32, 32));

                MakeGray(hvcursorb);

                hvcursor = new Texture(_device, hvcursorb, Usage.Dynamic, Pool.Default);


                font     = new Microsoft.DirectX.Direct3D.Font(_device, new System.Drawing.Font("Microsoft Sans Serif", 8.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(177))));
                fontBold = new Microsoft.DirectX.Direct3D.Font(_device, new System.Drawing.Font("Microsoft Sans Serif", 8.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(177))));

                while (Created)
                {
                    if (bRender)
                    {
                        Render();
                    }
                    if (mouseMoved)
                    {
                        OnMouseMove(lastEvent);
                        mouseMoved = false;
                    }
                    Application.DoEvents();
                }
            }
            catch (DirectXException ex)
            {
                throw new ArgumentException("Error initializing DirectX", ex);
            }
        }
Beispiel #22
0
 /// <summary>
 ///     Cambia la fuente del texto
 /// </summary>
 /// <param name="font">Fuente del sistema</param>
 public void changeFont(System.Drawing.Font font)
 {
     D3dFont = new Font(D3DDevice.Instance.Device, font);
 }
Beispiel #23
0
 public void LoadModelMeshs(string pModel3DsFile)
 {
     try
     {
         this.ModelMeshs.Clear();
         DataSet dataSet = new DataSet();
         dataSet.ReadXml(pModel3DsFile);
         DataTable dataTable = dataSet.Tables[0];
         string    pName     = "";
         string    text      = "";
         float     valueX    = 0f;
         float     valueY    = 0f;
         float     valueZ    = 0f;
         float     pScale    = 1f;
         float     pShiftX   = 0f;
         float     pShiftY   = 0f;
         float     pShiftZ   = 0f;
         int       pAutoTurn = 0;
         if (dataTable.Rows.Count > 0)
         {
             foreach (DataRow dataRow in dataTable.Rows)
             {
                 if (dataRow.ItemArray.GetUpperBound(0) == 9)
                 {
                     pName     = (string)dataRow[0];
                     text      = (string)dataRow[1];
                     valueX    = Geometry.DegreeToRadian(CHelper.myToSingle((string)dataRow[2]));
                     valueY    = Geometry.DegreeToRadian(CHelper.myToSingle((string)dataRow[3]));
                     valueZ    = Geometry.DegreeToRadian(CHelper.myToSingle((string)dataRow[4]));
                     pScale    = CHelper.myToSingle((string)dataRow[5]);
                     pShiftX   = CHelper.myToSingle((string)dataRow[6]);
                     pShiftY   = CHelper.myToSingle((string)dataRow[7]);
                     pShiftZ   = CHelper.myToSingle((string)dataRow[8]);
                     pAutoTurn = Convert.ToInt32(dataRow[9]);
                 }
                 else if (dataRow.ItemArray.GetUpperBound(0) == 7)
                 {
                     pName     = (string)dataRow[0];
                     text      = (string)dataRow[1];
                     valueX    = Geometry.DegreeToRadian(CHelper.myToSingle((string)dataRow[2]));
                     valueY    = Geometry.DegreeToRadian(CHelper.myToSingle((string)dataRow[3]));
                     valueZ    = Geometry.DegreeToRadian(CHelper.myToSingle((string)dataRow[4]));
                     pScale    = CHelper.myToSingle((string)dataRow[5]);
                     pShiftX   = 0f;
                     pShiftY   = 0f;
                     pShiftZ   = CHelper.myToSingle((string)dataRow[6]);
                     pAutoTurn = Convert.ToInt32(dataRow[7]);
                 }
                 Vector3 pAngle = new Vector3(valueX, valueY, valueZ);
                 if (File.Exists(text))
                 {
                     CModelMesh item = new CModelMesh(this.device, text, pName, pAngle, pScale, pShiftX, pShiftY, pShiftZ, pAutoTurn);
                     this.ModelMeshs.Add(item);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Beispiel #24
0
 private void InitializeFont()
 {
     System.Drawing.Font systemfont = new System.Drawing.Font("Arial", 10f, FontStyle.Regular);
     text = new Microsoft.DirectX.Direct3D.Font(device, systemfont);
 }
Beispiel #25
0
        public Game()
        {
            InitializeComponent();
            if (!InitializeDirect3D())
            {
                return;
            }

            sounds = new GameSound(this);
            sounds.Victory();

            font = new Microsoft.DirectX.Direct3D.Font(device,                         // Device we are drawing on
                                                       20,                             // Font height in pixels
                                                       0,                              // Font width in pixels or zero to match height
                                                       FontWeight.Bold,                // Font weight (Normal, Bold, etc.)
                                                       0,                              // mip levels (0 for default)
                                                       false,                          // italics?
                                                       CharacterSet.Default,           // Character set to use
                                                       Precision.Default,              // The font precision, try some of them...
                                                       FontQuality.Default,            // Quality?
                                                       PitchAndFamily.FamilyDoNotCare, // Pitch and family, we don't care
                                                       "Arial");                       // And the name of the font



            // To create a rectangle
            vertices = new VertexBuffer(typeof(CustomVertex.PositionColored), // Type of vertex
                                        4,                                    // How many
                                        device,                               // What device
                                        0,                                    // No special usage
                                        CustomVertex.PositionColored.Format,
                                        Pool.Managed);
            background = new Background(device, playingW, playingH);


            //draw floor /////////////////////////////////////////////////////////////
            Texture floor = TextureLoader.FromFile(device, "../../../floor.jpg");

            AddTexture(0, playingW / 3, 0, 1, Color.Transparent, floor, 0, 1, 0, 1);

            Texture poolTexture = TextureLoader.FromFile(device, "../../../pool.png");

            AddBadPoly(playingW / 3, playingW / 3 * (1 + 0.5f), 0, 0.7f, Color.Transparent, poolTexture, 0, 1, 0, 1);

            AddTexture(playingW / 3 * (1 + 0.5f), playingW, 0, 1, Color.Transparent, floor, 0, 1, 0, 1);


            //create a platform
            AddPlatform(3.2f, 3.9f, 1.8f, 2, Color.CornflowerBlue);

            //create a platform
            AddPlatform2(playingW / 3, playingW / 3 + 0.7f, 0.8f, 1, Color.Black);

            AddCoins();


            Texture c1 = TextureLoader.FromFile(device, "../../../candy1.png");
            Texture c2 = TextureLoader.FromFile(device, "../../../candy2.png");

            AddBadPoly(13.1f, 13.9f, 3.2f, 3.4f, Color.Transparent, c1, 0.3f, 1, 0.55f, 0.85f);

            AddBadPoly(7.1f, 8.1f, 2.2f, 2.8f, Color.Transparent, c2, 0.2f, 1, 0.05f, 0.45f);

            AddBadPoly(26, 27, 1.5f, 2.1f, Color.Transparent, c2, 0.2f, 1, 0.05f, 0.45f);

            AddObstacle(27.1f, 27.7f, 3.0f, 3.2f, Color.BlanchedAlmond);

            /////////////////////////////////////////////////////////////////////////////////////////////////////



            ////Game
            AddObstacle(4, 4.2f, 1, 2.1f, Color.Coral);
            AddObstacle(5, 6, 1.4f, 1.6f, Color.BurlyWood);
            AddObstacle(5.5f, 6.5f, 3.2f, 3.4f, Color.PeachPuff);
            AddObstacle(8.5f, 9.5f, 2.5f, 2.7f, Color.Brown);


            AddObstacle(10.5f, 11.5f, 1.5f, 1.7f, Color.AliceBlue);

            ///add

            AddObstacle(11.5f, 12.5f, 2.2f, 2.4f, Color.PeachPuff);
            // AddObstacle(13.5f, 15f, 3.2f, 3.4f, Color.BlanchedAlmond);
            AddObstacle(14.5f, 15.5f, 2f, 2.2f, Color.Aqua);

            AddObstacle(22.5f, 24f, 3.0f, 3.2f, Color.Crimson);//red
            AddObstacle(29.1f, 29.9f, 2.5f, 2.8f, Color.Chocolate);



            Platform platform = new Platform();

            platform.AddVertex(new Vector2(3.2f, 2));
            platform.AddVertex(new Vector2(3.9f, 2));
            platform.AddVertex(new Vector2(3.9f, 1.8f));
            platform.AddVertex(new Vector2(3.2f, 1.8f));
            platform.Color = Color.Black;
            world.Add(platform);


            ///OBJECT1
            Texture weird_texture = TextureLoader.FromFile(device, "../../../green.jpg");
            Weird   wd            = new Weird();

            wd.Tex = weird_texture;
            //triangle  offset=0
            wd.AddVertex(new Vector2(1.5f, 1.1f));
            wd.AddVertex(new Vector2(1f, 1.5f));
            wd.AddVertex(new Vector2(2f, 1.5f));
            world.Add(wd);



            ///OBJECT2
            Texture         texture = TextureLoader.FromFile(device, "../../../stone08.bmp");
            PolygonTextured pt      = new PolygonTextured();

            pt.Tex = texture;
            pt.AddVertex(new Vector2(17.5f, 1f));
            pt.AddTex(new Vector2(0, 0));
            pt.AddVertex(new Vector2(17f, 1.5f));
            pt.AddTex(new Vector2(0, 1));

            pt.AddVertex(new Vector2(19f, 1.5f));
            pt.AddTex(new Vector2(1, 1));

            pt.AddVertex(new Vector2(18.5f, 1f));
            pt.AddTex(new Vector2(1, 0));



            pt.Color = Color.Transparent;
            world.Add(pt);


            ///OBJECT3
            Texture         texture3 = TextureLoader.FromFile(device, "../../../brown.jpg");
            PolygonTextured pt3      = new PolygonTextured();

            pt3.Tex = texture3;
            pt3.AddVertex(new Vector2(20, 2.7f));            //A
            pt3.AddTex(new Vector2(0, 1));
            pt3.AddVertex(new Vector2(21, 2.7f));            //B
            pt3.AddTex(new Vector2(0.5f, 0));
            pt3.AddVertex(new Vector2(21, 2.5f));            //C
            pt3.AddTex(new Vector2(1, 0.5f));
            pt3.AddVertex(new Vector2((20 + 21) / 2.0f, 2)); //D
            pt3.AddTex(new Vector2(1, 1));
            pt3.AddVertex(new Vector2(20, 2.5f));
            pt3.AddTex(new Vector2(0, 0.5f));
            world.Add(pt3);



            ///Object4
            Texture         texture4 = TextureLoader.FromFile(device, "../../../green.jpg");
            PolygonTextured pt4      = new PolygonTextured();

            pt4.Tex = texture4;


            pt4.AddVertex(new Vector2(5.375f, 1f));
            pt4.AddTex(new Vector2(1, 0.5f));
            pt4.AddVertex(new Vector2(5f, 1.2f));
            pt4.AddTex(new Vector2(0, 0));
            pt4.AddVertex(new Vector2(5.5f, 1.4f));
            pt4.AddTex(new Vector2(0, 0.5f));
            pt4.AddVertex(new Vector2(5.5f, 1.2f));
            pt4.AddTex(new Vector2(0.5f, 0));
            pt4.AddVertex(new Vector2(6f, 1.2f));
            pt4.AddTex(new Vector2(0.5f, 0.5f));
            pt4.AddVertex(new Vector2(5.625f, 1f));
            pt4.AddTex(new Vector2(0.5f, 1));


            world.Add(pt4);


            Texture spritetexture = TextureLoader.FromFile(device, "../../../guy8.bmp");

            player.Transparent = true;
            player.P           = new Vector2(0.5f, 1);
            player.Tex         = spritetexture;
            player.AddVertex(new Vector2(-0.2f, 0));
            player.AddTex(new Vector2(0, 1));
            player.AddVertex(new Vector2(-0.2f, 1));
            player.AddTex(new Vector2(0, 0));
            player.AddVertex(new Vector2(0.2f, 1));
            player.AddTex(new Vector2(0.125f, 0));
            player.AddVertex(new Vector2(0.2f, 0));
            player.AddTex(new Vector2(0.125f, 1));
            player.Color = Color.Transparent;
            // Determine the last time
            stopwatch.Start();
            lastTime = stopwatch.ElapsedMilliseconds;
        }
Beispiel #26
0
        public virtual void Render(DrawArgs drawArgs)
        {
            if (!Visible)
            {
                return;
            }

            if (m_TextFont == null)
            {
                System.Drawing.Font localHeaderFont = new System.Drawing.Font("Arial", 12.0f, FontStyle.Italic | FontStyle.Bold);
                m_TextFont = new Font(drawArgs.Device, localHeaderFont);
            }

            if (m_WorldWindDingsFont == null)
            {
                AddFontResource(Path.Combine(Application.StartupPath, "World Wind Dings 1.04.ttf"));
                PrivateFontCollection fpc = new PrivateFontCollection();
                fpc.AddFontFile(Path.Combine(Application.StartupPath, "World Wind Dings 1.04.ttf"));
                System.Drawing.Font worldwinddings = new System.Drawing.Font(fpc.Families[0], 12.0f);

                m_WorldWindDingsFont = new Font(drawArgs.Device, worldwinddings);
            }

            if (DrawArgs.LastMousePosition.X > AbsoluteLocation.X - resizeBuffer && DrawArgs.LastMousePosition.X < AbsoluteLocation.X + resizeBuffer && DrawArgs.LastMousePosition.Y > AbsoluteLocation.Y - resizeBuffer &&
                DrawArgs.LastMousePosition.Y < AbsoluteLocation.Y + resizeBuffer)
            {
                DrawArgs.MouseCursor = CursorType.SizeNWSE;
            }
            else if (DrawArgs.LastMousePosition.X > AbsoluteLocation.X - resizeBuffer + ClientSize.Width && DrawArgs.LastMousePosition.X < AbsoluteLocation.X + resizeBuffer + ClientSize.Width && DrawArgs.LastMousePosition.Y > AbsoluteLocation.Y - resizeBuffer &&
                     DrawArgs.LastMousePosition.Y < AbsoluteLocation.Y + resizeBuffer)
            {
                DrawArgs.MouseCursor = CursorType.SizeNESW;
            }
            else if (DrawArgs.LastMousePosition.X > AbsoluteLocation.X - resizeBuffer && DrawArgs.LastMousePosition.X < AbsoluteLocation.X + resizeBuffer && DrawArgs.LastMousePosition.Y > AbsoluteLocation.Y - resizeBuffer + ClientSize.Height &&
                     DrawArgs.LastMousePosition.Y < AbsoluteLocation.Y + resizeBuffer + ClientSize.Height)
            {
                DrawArgs.MouseCursor = CursorType.SizeNESW;
            }
            else if (DrawArgs.LastMousePosition.X > AbsoluteLocation.X - resizeBuffer + ClientSize.Width && DrawArgs.LastMousePosition.X < AbsoluteLocation.X + resizeBuffer + ClientSize.Width && DrawArgs.LastMousePosition.Y > AbsoluteLocation.Y - resizeBuffer + ClientSize.Height &&
                     DrawArgs.LastMousePosition.Y < AbsoluteLocation.Y + resizeBuffer + ClientSize.Height)
            {
                DrawArgs.MouseCursor = CursorType.SizeNWSE;
            }
            else if ((DrawArgs.LastMousePosition.X > AbsoluteLocation.X - resizeBuffer && DrawArgs.LastMousePosition.X < AbsoluteLocation.X + resizeBuffer && DrawArgs.LastMousePosition.Y > AbsoluteLocation.Y - resizeBuffer && DrawArgs.LastMousePosition.Y < AbsoluteLocation.Y + resizeBuffer + ClientSize.Height) ||
                     (DrawArgs.LastMousePosition.X > AbsoluteLocation.X - resizeBuffer + ClientSize.Width && DrawArgs.LastMousePosition.X < AbsoluteLocation.X + resizeBuffer + ClientSize.Width && DrawArgs.LastMousePosition.Y > AbsoluteLocation.Y - resizeBuffer && DrawArgs.LastMousePosition.Y < AbsoluteLocation.Y + resizeBuffer + ClientSize.Height))
            {
                DrawArgs.MouseCursor = CursorType.SizeWE;
            }
            else if ((DrawArgs.LastMousePosition.X > AbsoluteLocation.X - resizeBuffer && DrawArgs.LastMousePosition.X < AbsoluteLocation.X + resizeBuffer + ClientSize.Width && DrawArgs.LastMousePosition.Y > AbsoluteLocation.Y - resizeBuffer && DrawArgs.LastMousePosition.Y < AbsoluteLocation.Y + resizeBuffer) ||
                     (DrawArgs.LastMousePosition.X > AbsoluteLocation.X - resizeBuffer && DrawArgs.LastMousePosition.X < AbsoluteLocation.X + resizeBuffer + ClientSize.Width && DrawArgs.LastMousePosition.Y > AbsoluteLocation.Y - resizeBuffer + ClientSize.Height && DrawArgs.LastMousePosition.Y < AbsoluteLocation.Y + resizeBuffer + ClientSize.Height))
            {
                DrawArgs.MouseCursor = CursorType.SizeNS;
            }

            if (ClientSize.Height
                > drawArgs.ParentControl.Height)
            {
                ClientSize = new Size(ClientSize.Width, drawArgs.ParentControl.Height);
            }

            if (ClientSize.Width
                > drawArgs.ParentControl.Width)
            {
                ClientSize = new Size(drawArgs.ParentControl.Width, ClientSize.Height);
            }

            if (!m_AutoHideHeader ||
                (DrawArgs.LastMousePosition.X >= m_Location.X && DrawArgs.LastMousePosition.X <= m_Location.X + m_Size.Width && DrawArgs.LastMousePosition.Y >= m_Location.Y && DrawArgs.LastMousePosition.Y <= m_Location.Y + m_Size.Height))
            {
                WidgetUtil.DrawBox(m_Location.X, m_Location.Y, m_Size.Width, m_HeaderHeight, 0.0f, m_HeaderColor.ToArgb(), drawArgs.Device);

                m_TextFont.DrawText(null, m_Text, new Rectangle(m_Location.X + 2, m_Location.Y, m_Size.Width, m_HeaderHeight), DrawTextFormat.None, m_TextColor.ToArgb());

                m_WorldWindDingsFont.DrawText(null, "E", new Rectangle(m_Location.X + m_Size.Width - 15, m_Location.Y + 2, m_Size.Width, m_Size.Height), DrawTextFormat.NoClip, Color.White.ToArgb());

                m_OutlineVertsHeader[0].X = AbsoluteLocation.X;
                m_OutlineVertsHeader[0].Y = AbsoluteLocation.Y;

                m_OutlineVertsHeader[1].X = AbsoluteLocation.X + ClientSize.Width;
                m_OutlineVertsHeader[1].Y = AbsoluteLocation.Y;

                m_OutlineVertsHeader[2].X = AbsoluteLocation.X + ClientSize.Width;
                m_OutlineVertsHeader[2].Y = AbsoluteLocation.Y + m_HeaderHeight;

                m_OutlineVertsHeader[3].X = AbsoluteLocation.X;
                m_OutlineVertsHeader[3].Y = AbsoluteLocation.Y + m_HeaderHeight;

                m_OutlineVertsHeader[4].X = AbsoluteLocation.X;
                m_OutlineVertsHeader[4].Y = AbsoluteLocation.Y;

                if (!m_HideBorder)
                {
                    WidgetUtil.DrawLine(m_OutlineVertsHeader, m_BorderColor.ToArgb(), drawArgs.Device);
                }
            }

            WidgetUtil.DrawBox(m_Location.X, m_Location.Y + m_HeaderHeight, m_Size.Width, m_Size.Height - m_HeaderHeight, 0.0f, m_BackgroundColor.ToArgb(), drawArgs.Device);

            for (int index = m_ChildWidgets.Count - 1; index >= 0; index--)
            {
                IWidget currentChildWidget = m_ChildWidgets[index] as IWidget;
                if (currentChildWidget != null)
                {
                    if (currentChildWidget.ParentWidget == null ||
                        currentChildWidget.ParentWidget != this)
                    {
                        currentChildWidget.ParentWidget = this;
                    }
                    currentChildWidget.Render(drawArgs);
                }
            }

            m_OutlineVerts[0].X = AbsoluteLocation.X;
            m_OutlineVerts[0].Y = AbsoluteLocation.Y + m_HeaderHeight;

            m_OutlineVerts[1].X = AbsoluteLocation.X + ClientSize.Width;
            m_OutlineVerts[1].Y = AbsoluteLocation.Y + m_HeaderHeight;

            m_OutlineVerts[2].X = AbsoluteLocation.X + ClientSize.Width;
            m_OutlineVerts[2].Y = AbsoluteLocation.Y + ClientSize.Height;

            m_OutlineVerts[3].X = AbsoluteLocation.X;
            m_OutlineVerts[3].Y = AbsoluteLocation.Y + ClientSize.Height;

            m_OutlineVerts[4].X = AbsoluteLocation.X;
            m_OutlineVerts[4].Y = AbsoluteLocation.Y + m_HeaderHeight;

            if (!m_HideBorder)
            {
                WidgetUtil.DrawLine(m_OutlineVerts, m_BorderColor.ToArgb(), drawArgs.Device);
            }
        }
Beispiel #27
0
 public virtual void Render2(DrawArgs drawArgs)
 {
     if (this.m_Visible)
     {
         if ((this.dblLatitude != double.MinValue) && ((drawArgs.WorldCamera.Altitude > 100.0) || (World.Settings.VerticalExaggeration >= 1f)))
         {
             try
             {
                 drawArgs.device.RenderState.ZBufferEnable = true;
                 Cull cullMode = drawArgs.device.RenderState.CullMode;
                 drawArgs.device.RenderState.CullMode           = Cull.None;
                 drawArgs.device.VertexFormat                   = VertexFormats.Diffuse | VertexFormats.Position;
                 drawArgs.device.TextureState[0].ColorOperation = TextureOperation.Disable;
                 Microsoft.DirectX.Matrix matrix = Microsoft.DirectX.Matrix.Translation((float)-drawArgs.WorldCamera.ReferenceCenter.X, (float)-drawArgs.WorldCamera.ReferenceCenter.Y, (float)-drawArgs.WorldCamera.ReferenceCenter.Z);
                 drawArgs.device.Transform.World = matrix;
                 Microsoft.DirectX.Vector3 vector  = MathEngine.SphericalToCartesian((double)this.dblLatitude, (double)this.dblLongitude, (this.ww.CurrentWorld.EquatorialRadius + (this.ww.CurrentWorld.TerrainAccessor.GetElevationAt((double)this.dblLatitude, (double)this.dblLongitude, 100.0) * World.Settings.VerticalExaggeration)) + this.dblAltitude);
                 Microsoft.DirectX.Vector3 vector2 = new Microsoft.DirectX.Vector3();
                 Microsoft.DirectX.Vector3 vector3 = new Microsoft.DirectX.Vector3();
                 vector2.X = this.m_Location.X + (((float)this.m_Size.Width) / 3f);
                 vector2.Y = (this.m_Location.Y + this.m_Size.Height) - 5;
                 vector2.Z = 0f;
                 vector2.Unproject(drawArgs.device.Viewport, drawArgs.WorldCamera.ProjectionMatrix, drawArgs.WorldCamera.ViewMatrix, drawArgs.device.Transform.World);
                 vector3.X = this.m_Location.X + (2f * (((float)this.m_Size.Width) / 3f));
                 vector3.Y = (this.m_Location.Y + this.m_Size.Height) - 5;
                 vector3.Z = 0f;
                 vector3.Unproject(drawArgs.device.Viewport, drawArgs.WorldCamera.ProjectionMatrix, drawArgs.WorldCamera.ViewMatrix, drawArgs.device.Transform.World);
                 CustomVertex.PositionColored[] vertexStreamZeroData = new CustomVertex.PositionColored[3];
                 vertexStreamZeroData[0].X     = vector.X;
                 vertexStreamZeroData[0].Y     = vector.Y;
                 vertexStreamZeroData[0].Z     = vector.Z;
                 vertexStreamZeroData[0].Color = this.m_BackgroundColor.ToArgb();
                 vertexStreamZeroData[1].X     = vector2.X;
                 vertexStreamZeroData[1].Y     = vector2.Y;
                 vertexStreamZeroData[1].Z     = vector2.Z;
                 vertexStreamZeroData[1].Color = this.m_BackgroundColor.ToArgb();
                 vertexStreamZeroData[2].X     = vector3.X;
                 vertexStreamZeroData[2].Y     = vector3.Y;
                 vertexStreamZeroData[2].Z     = vector3.Z;
                 vertexStreamZeroData[2].Color = this.m_BackgroundColor.ToArgb();
                 drawArgs.device.DrawUserPrimitives(PrimitiveType.TriangleStrip, vertexStreamZeroData.Length - 2, vertexStreamZeroData);
                 drawArgs.device.Transform.World                = drawArgs.WorldCamera.WorldMatrix;
                 drawArgs.device.RenderState.CullMode           = cullMode;
                 drawArgs.device.TextureState[0].ColorOperation = TextureOperation.Disable;
             }
             catch (Exception exception)
             {
                 MessageBox.Show(exception.Message);
             }
         }
         if (this.m_TextFont == null)
         {
             System.Drawing.Font font = new System.Drawing.Font("Arial", 12f, FontStyle.Italic | FontStyle.Bold);
             this.m_TextFont = new Microsoft.DirectX.Direct3D.Font(drawArgs.device, font);
         }
         if (this.m_WorldWindDingsFont == null)
         {
             AddFontResource(Path.Combine(Application.StartupPath, "World Wind Dings 1.04.ttf"));
             PrivateFontCollection fonts = new PrivateFontCollection();
             fonts.AddFontFile(Path.Combine(Application.StartupPath, "World Wind Dings 1.04.ttf"));
             System.Drawing.Font font2 = new System.Drawing.Font(fonts.Families[0], 12f);
             this.m_WorldWindDingsFont = new Microsoft.DirectX.Direct3D.Font(drawArgs.device, font2);
         }
         if (this.m_Resizeble)
         {
             if (((DrawArgs.LastMousePosition.X > (this.AbsoluteLocation.X - this.resizeBuffer)) && (DrawArgs.LastMousePosition.X < (this.AbsoluteLocation.X + this.resizeBuffer))) && ((DrawArgs.LastMousePosition.Y > (this.AbsoluteLocation.Y - this.resizeBuffer)) && (DrawArgs.LastMousePosition.Y < (this.AbsoluteLocation.Y + this.resizeBuffer))))
             {
                 DrawArgs.MouseCursor = CursorType.SizeNWSE;
             }
             else if (((DrawArgs.LastMousePosition.X > ((this.AbsoluteLocation.X - this.resizeBuffer) + this.ClientSize.Width)) && (DrawArgs.LastMousePosition.X < ((this.AbsoluteLocation.X + this.resizeBuffer) + this.ClientSize.Width))) && ((DrawArgs.LastMousePosition.Y > (this.AbsoluteLocation.Y - this.resizeBuffer)) && (DrawArgs.LastMousePosition.Y < (this.AbsoluteLocation.Y + this.resizeBuffer))))
             {
                 DrawArgs.MouseCursor = CursorType.SizeNESW;
             }
             else if (((DrawArgs.LastMousePosition.X > (this.AbsoluteLocation.X - this.resizeBuffer)) && (DrawArgs.LastMousePosition.X < (this.AbsoluteLocation.X + this.resizeBuffer))) && ((DrawArgs.LastMousePosition.Y > ((this.AbsoluteLocation.Y - this.resizeBuffer) + this.ClientSize.Height)) && (DrawArgs.LastMousePosition.Y < ((this.AbsoluteLocation.Y + this.resizeBuffer) + this.ClientSize.Height))))
             {
                 DrawArgs.MouseCursor = CursorType.SizeNESW;
             }
             else if (((DrawArgs.LastMousePosition.X > ((this.AbsoluteLocation.X - this.resizeBuffer) + this.ClientSize.Width)) && (DrawArgs.LastMousePosition.X < ((this.AbsoluteLocation.X + this.resizeBuffer) + this.ClientSize.Width))) && ((DrawArgs.LastMousePosition.Y > ((this.AbsoluteLocation.Y - this.resizeBuffer) + this.ClientSize.Height)) && (DrawArgs.LastMousePosition.Y < ((this.AbsoluteLocation.Y + this.resizeBuffer) + this.ClientSize.Height))))
             {
                 DrawArgs.MouseCursor = CursorType.SizeNWSE;
             }
             else if ((((DrawArgs.LastMousePosition.X > (this.AbsoluteLocation.X - this.resizeBuffer)) && (DrawArgs.LastMousePosition.X < (this.AbsoluteLocation.X + this.resizeBuffer))) && ((DrawArgs.LastMousePosition.Y > (this.AbsoluteLocation.Y - this.resizeBuffer)) && (DrawArgs.LastMousePosition.Y < ((this.AbsoluteLocation.Y + this.resizeBuffer) + this.ClientSize.Height)))) || (((DrawArgs.LastMousePosition.X > ((this.AbsoluteLocation.X - this.resizeBuffer) + this.ClientSize.Width)) && (DrawArgs.LastMousePosition.X < ((this.AbsoluteLocation.X + this.resizeBuffer) + this.ClientSize.Width))) && ((DrawArgs.LastMousePosition.Y > (this.AbsoluteLocation.Y - this.resizeBuffer)) && (DrawArgs.LastMousePosition.Y < ((this.AbsoluteLocation.Y + this.resizeBuffer) + this.ClientSize.Height)))))
             {
                 DrawArgs.MouseCursor = CursorType.SizeWE;
             }
             else if ((((DrawArgs.LastMousePosition.X > (this.AbsoluteLocation.X - this.resizeBuffer)) && (DrawArgs.LastMousePosition.X < ((this.AbsoluteLocation.X + this.resizeBuffer) + this.ClientSize.Width))) && ((DrawArgs.LastMousePosition.Y > (this.AbsoluteLocation.Y - this.resizeBuffer)) && (DrawArgs.LastMousePosition.Y < (this.AbsoluteLocation.Y + this.resizeBuffer)))) || (((DrawArgs.LastMousePosition.X > (this.AbsoluteLocation.X - this.resizeBuffer)) && (DrawArgs.LastMousePosition.X < ((this.AbsoluteLocation.X + this.resizeBuffer) + this.ClientSize.Width))) && ((DrawArgs.LastMousePosition.Y > ((this.AbsoluteLocation.Y - this.resizeBuffer) + this.ClientSize.Height)) && (DrawArgs.LastMousePosition.Y < ((this.AbsoluteLocation.Y + this.resizeBuffer) + this.ClientSize.Height)))))
             {
                 DrawArgs.MouseCursor = CursorType.SizeNS;
             }
         }
         if (this.ClientSize.Height > drawArgs.parentControl.Height)
         {
             this.ClientSize = new Size(this.ClientSize.Width, drawArgs.parentControl.Height);
         }
         if (this.ClientSize.Width > drawArgs.parentControl.Width)
         {
             this.ClientSize = new Size(drawArgs.parentControl.Width, this.ClientSize.Height);
         }
         if (!this.m_AutoHideHeader || (((DrawArgs.LastMousePosition.X >= this.m_Location.X) && (DrawArgs.LastMousePosition.X <= (this.m_Location.X + this.m_Size.Width))) && ((DrawArgs.LastMousePosition.Y >= this.m_Location.Y) && (DrawArgs.LastMousePosition.Y <= (this.m_Location.Y + this.m_Size.Height)))))
         {
             Utilities.DrawBox(this.m_Location.X, this.m_Location.Y, this.m_Size.Width, this.m_HeaderHeight, 0f, this.m_HeaderColor.ToArgb(), drawArgs.device);
             this.m_WorldWindDingsFont.DrawText(null, "E", new Rectangle((this.m_Location.X + this.m_Size.Width) - 15, this.m_Location.Y + 2, this.m_Size.Width, this.m_Size.Height), DrawTextFormat.NoClip, Color.White.ToArgb());
             this.m_OutlineVertsHeader[0].X = this.AbsoluteLocation.X;
             this.m_OutlineVertsHeader[0].Y = this.AbsoluteLocation.Y + this.m_HeaderHeight;
             this.m_OutlineVertsHeader[1].X = this.AbsoluteLocation.X;
             this.m_OutlineVertsHeader[1].Y = this.AbsoluteLocation.Y;
             this.m_OutlineVertsHeader[2].X = this.AbsoluteLocation.X + this.ClientSize.Width;
             this.m_OutlineVertsHeader[2].Y = this.AbsoluteLocation.Y;
             this.m_OutlineVertsHeader[3].X = this.AbsoluteLocation.X + this.ClientSize.Width;
             this.m_OutlineVertsHeader[3].Y = this.AbsoluteLocation.Y + this.m_HeaderHeight;
             if (!this.m_HideBorder)
             {
                 Utilities.DrawLine(this.m_OutlineVertsHeader, this.m_BorderColor.ToArgb(), drawArgs.device);
             }
         }
         Utilities.DrawBox(this.m_Location.X, this.m_Location.Y + this.m_HeaderHeight, this.m_Size.Width, this.m_Size.Height - this.m_HeaderHeight, 0f, this.m_BackgroundColor.ToArgb(), drawArgs.device);
         for (int i = this.m_ChildWidgets.Count - 1; i >= 0; i--)
         {
             IWidget widget = this.m_ChildWidgets[i];
             if (widget != null)
             {
                 if ((widget.ParentWidget == null) || (widget.ParentWidget != this))
                 {
                     widget.ParentWidget = this;
                 }
                 widget.Render(drawArgs);
             }
         }
         this.m_OutlineVerts[0].X = this.AbsoluteLocation.X + this.ClientSize.Width;
         this.m_OutlineVerts[0].Y = this.AbsoluteLocation.Y + this.m_HeaderHeight;
         this.m_OutlineVerts[1].X = this.AbsoluteLocation.X + this.ClientSize.Width;
         this.m_OutlineVerts[1].Y = this.AbsoluteLocation.Y + this.ClientSize.Height;
         this.m_OutlineVerts[2].X = this.AbsoluteLocation.X;
         this.m_OutlineVerts[2].Y = this.AbsoluteLocation.Y + this.ClientSize.Height;
         this.m_OutlineVerts[3].X = this.AbsoluteLocation.X;
         this.m_OutlineVerts[3].Y = this.AbsoluteLocation.Y + this.m_HeaderHeight;
         if (!this.m_HideBorder)
         {
             Utilities.DrawLine(this.m_OutlineVerts, this.m_BorderColor.ToArgb(), drawArgs.device);
         }
     }
 }
Beispiel #28
0
        public int Render(DrawArgs drawArgs, int x, int y, int yOffset, int width, int height,
                          Microsoft.DirectX.Direct3D.Font drawingFont,
                          Microsoft.DirectX.Direct3D.Font wingdingsFont,
                          Microsoft.DirectX.Direct3D.Font worldwinddingsFont,
                          LayerMenuItem mouseOverItem)
        {
            if (ParentControl == null)
            {
                ParentControl = drawArgs.parentControl;
            }

            this._x     = x;
            this._y     = y + yOffset;
            this._width = width;

            int consumedHeight = 20;

            System.Drawing.Rectangle textRect = drawingFont.MeasureString(null,
                                                                          m_renderableObject.Name,
                                                                          DrawTextFormat.None,
                                                                          System.Drawing.Color.White.ToArgb());

            consumedHeight = textRect.Height;

            if (m_renderableObject.Description != null && m_renderableObject.Description.Length > 0 && !(m_renderableObject is WorldWind.Renderable.Icon))
            {
                System.Drawing.SizeF rectF = DrawArgs.Graphics.MeasureString(
                    m_renderableObject.Description,
                    drawArgs.defaultSubTitleFont,
                    width - (this._itemXOffset + this._expandArrowXSize + this._checkBoxXOffset)
                    );

                consumedHeight += (int)rectF.Height + 15;
            }

            lastConsumedHeight = consumedHeight;
            // Layer manager client area height
            int totalHeight = height - y;

            updateList();

            if (yOffset >= -consumedHeight)
            {
                // Part of item or whole item visible
                int color = m_renderableObject.IsOn ? itemOnColor : itemOffColor;
                if (mouseOverItem == this)
                {
                    if (!m_renderableObject.IsOn)
                    {
                        // mouseover + inactive color (black)
                        color = 0xff << 24;
                    }
                    MenuUtils.DrawBox(m_parent.ClientLeft, _y, m_parent.ClientWidth, consumedHeight, 0,
                                      World.Settings.menuOutlineColor, drawArgs.device);
                }

                if (m_renderableObject is WorldWind.Renderable.RenderableObjectList)
                {
                    RenderableObjectList rol = (RenderableObjectList)m_renderableObject;
                    if (!rol.DisableExpansion)
                    {
                        worldwinddingsFont.DrawText(
                            null,
                            (this.isExpanded ? "L" : "A"),
                            new System.Drawing.Rectangle(x + this._itemXOffset, _y, this._expandArrowXSize, height),
                            DrawTextFormat.None,
                            color);
                    }
                }

                string checkSymbol = null;
                if (m_renderableObject.ParentList != null && m_renderableObject.ParentList.ShowOnlyOneLayer)
                {
                    // Radio check
                    checkSymbol = m_renderableObject.IsOn ? "O" : "P";
                }
                else
                {
                    // Normal check
                    checkSymbol = m_renderableObject.IsOn ? "N" : "F";
                }

                worldwinddingsFont.DrawText(
                    null,
                    checkSymbol,
                    new System.Drawing.Rectangle(
                        x + this._itemXOffset + this._expandArrowXSize,
                        _y,
                        this._checkBoxXOffset,
                        height),
                    DrawTextFormat.NoClip,
                    color);


                drawingFont.DrawText(
                    null,
                    m_renderableObject.Name,
                    new System.Drawing.Rectangle(
                        x + this._itemXOffset + this._expandArrowXSize + this._checkBoxXOffset,
                        _y,
                        width - (this._itemXOffset + this._expandArrowXSize + this._checkBoxXOffset),
                        height),
                    DrawTextFormat.None,
                    color);

                if (m_renderableObject.Description != null && m_renderableObject.Description.Length > 0 && !(m_renderableObject is WorldWind.Renderable.Icon))
                {
                    drawArgs.defaultSubTitleDrawingFont.DrawText(
                        null,
                        m_renderableObject.Description,
                        new System.Drawing.Rectangle(
                            x + this._itemXOffset + this._expandArrowXSize + this._checkBoxXOffset,
                            _y + textRect.Height,
                            width - (_itemXOffset + _expandArrowXSize + _checkBoxXOffset),
                            height),
                        DrawTextFormat.WordBreak,
                        System.Drawing.Color.Gray.ToArgb());
                }

                if (m_renderableObject.MetaData.Contains("InfoUri"))
                {
                    Vector2[] underlineVerts = new Vector2[2];
                    underlineVerts[0].X = x + this._itemXOffset + this._expandArrowXSize + this._checkBoxXOffset;
                    underlineVerts[0].Y = _y + textRect.Height;
                    underlineVerts[1].X = underlineVerts[0].X + textRect.Width;
                    underlineVerts[1].Y = _y + textRect.Height;

                    MenuUtils.DrawLine(underlineVerts, color, drawArgs.device);
                }
            }

            if (isExpanded)
            {
                for (int i = 0; i < m_subItems.Count; i++)
                {
                    int yRealOffset = yOffset + consumedHeight;
                    if (yRealOffset > totalHeight)
                    {
                        // No more space for items
                        break;
                    }
                    LayerMenuItem lmi = (LayerMenuItem)m_subItems[i];
                    consumedHeight += lmi.Render(
                        drawArgs,
                        x + _subItemXIndent,
                        y,
                        yRealOffset,
                        width - _subItemXIndent,
                        height,
                        drawingFont,
                        wingdingsFont,
                        worldwinddingsFont,
                        mouseOverItem);
                }
            }

            return(consumedHeight);
        }
Beispiel #29
0
 public void Init()
 {
     new MapGetter().ReadFromFile("TheFirstMap.txt", device, this);
     loadTextures();
     initSounds();
     for (short i = 0; i < pressedKeys.Length; i++)
         pressedKeys[i] = false;
     font = new Microsoft.DirectX.Direct3D.Font(device, new System.Drawing.Font("Arial", 12f));
     myPosY = 0.9f * size_of_one_rectangle;
     colDist = (znearPlane / (float)Math.Sin((telescopeMax * 0.5 * (float)Math.PI) / 180)) + transspeed;
     material = new Material();
     material.Diffuse = Color.White;
     material.Specular = Color.White;
     material.Ambient = Color.White;
     myView = Matrix.Translation(-myPosX, -myPosY, -myPosZ);
     lastFrame = Environment.TickCount;
     initSprite();
     startTime = System.Environment.TickCount;
 }
        /// <summary>
        /// Initializes Direct3D with a render target and backbuffer size.
        /// </summary>
        /// <param name="renderWindow">Window to render to.</param>
        /// <param name="screenWidth">Width of the screen in pixels.</param>
        /// <param name="screenHeight">Height of the screen in pixels.</param>
        /// <param name="vsync">Should the renderer wait for a vsync before drawing?</param>
        /// <returns>true if successful, false otherwise.</returns>
        public bool Initialize(Control renderWindow, int screenWidth, int screenHeight, bool vsync)
        {
            // Verify that the device has not been initialized
            if (m_Device != null)
            {
                return(false);
            }


            // Set up the Direct3D device
            try
            {
                // Set the present parameters
                m_PresentParams = new PresentParameters( );
                m_PresentParams.BackBufferWidth           = screenWidth;
                m_PresentParams.BackBufferHeight          = screenHeight;
                m_PresentParams.BackBufferFormat          = Format.Unknown;
                m_PresentParams.BackBufferCount           = 1;
                m_PresentParams.MultiSample               = MultiSampleType.None;
                m_PresentParams.MultiSampleQuality        = 0;
                m_PresentParams.SwapEffect                = SwapEffect.Copy;
                m_PresentParams.DeviceWindow              = renderWindow;
                m_PresentParams.Windowed                  = true;
                m_PresentParams.EnableAutoDepthStencil    = false;
                m_PresentParams.FullScreenRefreshRateInHz = 0;
                m_PresentParams.PresentationInterval      = (vsync) ? PresentInterval.Default : PresentInterval.Immediate;


                // Create the device
                m_Device = new Device(0, DeviceType.Hardware, renderWindow,
                                      CreateFlags.HardwareVertexProcessing, m_PresentParams);

                // Add the window to the render target list
                m_RenderTargets.Add(new RenderTarget(m_Device, m_PresentParams));
            }
            catch (Exception ex)
            {
                DialogResult r = MessageBox.Show("Failed to Create D3D Device\n\n" + ex.Message, "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return(false);
            }


            // Set up the Sprite object
            try
            {
                m_Sprite = new Sprite(m_Device);
            }
            catch (Exception ex)
            {
                DialogResult r = MessageBox.Show("Failed to Create the Sprite object\n\n" + ex.Message, "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return(false);
            }


            // Set up the Texture for rectangles & lines
            try
            {
                // Allocate the texture
                m_Texture = new Texture(m_Device, 1, 1, 1, Usage.None, Format.A8R8G8B8, Pool.Managed);

                // Set the pixel color to White
                GraphicsStream stream = m_Texture.LockRectangle(0, LockFlags.Discard);

                byte[] color = new byte[4];
                for (int i = 0; i < 4; i++)
                {
                    color[i] = 0xFF;
                }
                stream.Write(color, 0, 4);

                m_Texture.UnlockRectangle(0);
            }
            catch (Exception ex)
            {
                DialogResult r = MessageBox.Show("Failed to Create the Texture Object\n\n" + ex.Message, "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return(false);
            }


            // Set up the Font object
            try
            {
                m_FontDescription.FaceName = "Arial";
                m_FontDescription.Quality  = FontQuality.Default;
                m_FontDescription.Weight   = FontWeight.SemiBold;

                m_Font = new Microsoft.DirectX.Direct3D.Font(m_Device, m_FontDescription);
            }
            catch (Exception ex)
            {
                DialogResult r = MessageBox.Show("Failed to Create the font Object\n\n" + ex.Message, "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return(false);
            }

            return(true);
        }
Beispiel #31
0
		/// <summary>
		/// Initializes the button by loading the texture, creating the sprite and figure out the scaling.
		/// 
		/// Called on the GUI thread.
		/// </summary>
		/// <param name="drawArgs">The drawing arguments passed from the WW GUI thread.</param>
		public void Initialize(DrawArgs drawArgs)
		{
			if(!m_enabled)
				return;

			if (m_TitleFont == null)
			{
				System.Drawing.Font localHeaderFont = new System.Drawing.Font("Arial", 8.0f, FontStyle.Bold);
				m_TitleFont = new Microsoft.DirectX.Direct3D.Font(drawArgs.device, localHeaderFont);

				System.Drawing.Font wingdings = new System.Drawing.Font("Wingdings", 12.0f);
				m_wingdingsFont = new Microsoft.DirectX.Direct3D.Font(drawArgs.device, wingdings);

                AddFontResource(Path.Combine(Application.StartupPath, "World Wind Dings 1.04.ttf"));
                System.Drawing.Text.PrivateFontCollection fpc = new System.Drawing.Text.PrivateFontCollection();
                fpc.AddFontFile(Path.Combine(Application.StartupPath, "World Wind Dings 1.04.ttf"));
                System.Drawing.Font m_worldwinddings = new System.Drawing.Font(fpc.Families[0], 12.0f);
                m_worldwinddingsFont = new Microsoft.DirectX.Direct3D.Font(drawArgs.device, m_worldwinddings);
			}

			m_TextFont = drawArgs.defaultDrawingFont;

			UpdateLocation();

			m_isInitialized = true;
		}
Beispiel #32
0
 private void InitializeTitleFont(string pFontName, float pSize, FontStyle pFontStyle)
 {
     this.textTitle = new Microsoft.DirectX.Direct3D.Font(this.device, new System.Drawing.Font(pFontName, pSize, pFontStyle));
 }
Beispiel #33
0
        public override void OnRender(Canvas canvas)
        {
            if (!PauseRendering)
            {
                Rectangle PlayfieldRect = canvas.TargetControl.ClientRectangle;
                _playfield.ClientArea = PlayfieldRect;

                int bottom_left = (PlayfieldRect.Y + PlayfieldRect.Height);

                Rectangle SpriteRect = Rectangle.Empty;

                if (Map != null)
                {
                    SpriteRect = Map.ToRectangle();

                    // Prevent black from appearing on sides of map.
                    if (!SpriteRect.Contains(PlayfieldRect))
                    {
                        int right = (int)(Map.Position.X + (Map.TextureWidth * _playfield.Scale));
                        int bottom = (int)(Map.Position.Y + (Map.TextureHeight * _playfield.Scale));
                        if (right < PlayfieldRect.Width)
                        {
                            Pan(PlayfieldRect.Width - right, 0);
                        }
                        if (bottom < PlayfieldRect.Height)
                        {
                            Pan(0, PlayfieldRect.Height - bottom);
                        }
                        if (Map.Position.Y > PlayfieldRect.Y)
                        {
                            Pan(0, -(Map.Position.Y));
                        }
                        if (Map.Position.X > PlayfieldRect.X)
                        {
                            Pan(-(Map.Position.X), 0);
                        }
                    }
                }

                switch (MapScrollState)
                {
                    case MapPlayfieldScrollState.UP:
                        Pan(0, -10);
                        break;
                    case MapPlayfieldScrollState.DOWN:
                        Pan(0, 10);
                        break;
                    case MapPlayfieldScrollState.LEFT:
                        Pan(-10, 0);
                        break;
                    case MapPlayfieldScrollState.RIGHT:
                        Pan(10, 0);
                        break;
                }

                _playfield.OnRender(canvas);

                if (WBRoom != null)
                {
                    // Draw Whiteboard information from other selected rooms
                    List<string> otherWBNames = WBRoom.GetOtherWBRoomNames();
                    if (otherWBNames != null)
                    {
                        foreach (string otherWBName in otherWBNames)
                        {
                            DrawWhiteboardRoomObjects(WBRoom.GetOtherWBRoom(otherWBName), canvas);
                        }
                    }

                    // Draw Whiteboard information from current room
                    DrawWhiteboardRoomObjects(WBRoom, canvas);

                    // Draw any commands in progress
                    if ((WBRoom.DrawMode == DrawModes.Line) &&
                        (DrawDistanceLine == true) && (WhiteboardDrawing == true))
                    {
                        if ((WBRoom.DrawText != null) && (WBRoom.DrawText.Length > 0))
                        {
                            int lineTextSize = LineTextSize;

                            DrawShortenedLine(canvas, WBRoom.DrawColor, WBRoom.DrawPointSize, LineStartLocation.X, LineStartLocation.Y,
                                LineEndLocation.X, LineEndLocation.Y, 1f);

                            if (lineTextSize > MaxFontSize)
                            {
                                lineTextSize = MaxFontSize;
                            }
                            if (lineTextSize < 1)
                            {
                                lineTextSize = 1;
                            }
                            if (wbFonts[lineTextSize] == null)
                            {
                                wbFonts[lineTextSize] = canvas.CreateFont(new System.Drawing.Font("Arial", lineTextSize, FontStyle.Bold, GraphicsUnit.Pixel));
                            }
                            DrawCenteredText(wbFonts[lineTextSize], WBRoom.DrawText, LineEndLocation.X, LineEndLocation.Y, WBRoom.DrawColor);
                        }
                        else
                        {
                            canvas.DrawLine(WBRoom.DrawColor, WBRoom.DrawPointSize, LineStartLocation.X, LineStartLocation.Y,
                                LineEndLocation.X, LineEndLocation.Y);
                        }
                    }
                    else if ((WBRoom.DrawMode == DrawModes.Circle) &&
                        (DrawDistanceLine == true) && (WhiteboardDrawing == true))
                    {
                        canvas.DrawCircle(WBRoom.DrawColor, WBRoom.DrawPointSize, LineStartLocation.X, LineStartLocation.Y,
                            LineEndLocation.X, LineEndLocation.Y);
                    }
                    else if ((WBRoom.DrawMode == DrawModes.Arrow) &&
                        (DrawDistanceLine == true) && (WhiteboardDrawing == true))
                    {
                        canvas.DrawArrow(WBRoom.DrawColor, WBRoom.DrawPointSize, LineStartLocation.X, LineStartLocation.Y,
                            LineEndLocation.X, LineEndLocation.Y);
                    }
                    else if ((WBRoom.DrawMode == DrawModes.Text) &&
                        (DrawDistanceLine == true) && (WhiteboardDrawing == true))
                    {
                        if ((WBRoom.DrawText != null) && (WBRoom.DrawText.Length > 0))
                        {
                            int drawPointSize = WBRoom.DrawPointSize + 7;

                            if (drawPointSize > MaxFontSize)
                            {
                                drawPointSize = MaxFontSize;
                            }
                            if (wbFonts[drawPointSize] == null)
                            {
                                wbFonts[drawPointSize] = canvas.CreateFont(new System.Drawing.Font("Arial", drawPointSize, FontStyle.Bold, GraphicsUnit.Pixel));
                            }
                            DrawCenteredText(wbFonts[drawPointSize], WBRoom.DrawText, LineEndLocation.X, LineEndLocation.Y, WBRoom.DrawColor);
                        }
                    }
                    else if ((WBRoom.DrawMode == DrawModes.Selection) &&
                        (DrawDistanceLine == true) && (WhiteboardDrawing == true))
                    {
                        RectangleF selectionRect;

                        int selectionX = Math.Min(LineStartLocation.X, LineEndLocation.X);
                        int selectionY = Math.Min(LineStartLocation.Y, LineEndLocation.Y);

                        selectionRect = new RectangleF((float)selectionX, (float)selectionY,
                            (float)Math.Abs(LineStartLocation.X - LineEndLocation.X),
                            (float)Math.Abs(LineStartLocation.Y - LineEndLocation.Y));
                        canvas.DrawRect(selectionRect, Color.Orange);
                    }
                }

                // Draw Mini map
                _bottom_status_bar.Height = 35;
                _bottom_status_bar.Width = PlayfieldRect.Width;
                _bottom_status_bar.X = PlayfieldRect.X;
                _bottom_status_bar.Y = bottom_left - _bottom_status_bar.Height;
                canvas.DrawFillRect(_bottom_status_bar, _mini_map_background);
                
                if (true) //check DDD_Global or playfield
                {
                    if (_rangeFinderFont == null && this.Fonts.ContainsKey("RangeRing"))
                    {
                        _rangeFinderFont = this.Fonts["RangeRing"];
                    }
                    string rangeText = DDD_Global.Instance.GetRangeFinderDisplayString();

                    if (_rangeFinderFont != null && rangeText.Trim() != string.Empty)
                    {
                        _mouseoverRangeFinderDisplay = _rangeFinderFont.MeasureString(null, rangeText, DrawTextFormat.Center, Color.White);
                        _mouseoverRangeFinderDisplay.X = Convert.ToInt32(DDD_Global.Instance.RangeFinderXDisplay);// 500;
                        _mouseoverRangeFinderDisplay.Y = Convert.ToInt32(DDD_Global.Instance.RangeFinderYDisplay);// 400;
                        _mouseoverRangeFinderDisplay.Width += 10;
                        canvas.DrawFillRect(_mouseoverRangeFinderDisplay, _mini_map_background);//_rangeFinderMaterial);
                        _rangeFinderFont.DrawText(null, rangeText, _mouseoverRangeFinderDisplay, DrawTextFormat.Center, Color.White);

                        //DRAW LINE FROM OBJECT TO CURSOR

                        float objX = 0f;
                        float objY = 0f;
                        DDDObjects obj = _playfield.GetSelectedObject();
                        if (obj != null)
                        {
                            objX = obj.ScreenCoordinates.X;
                            objY = obj.ScreenCoordinates.Y;

                            canvas.DrawLine(Color.Black, 3, _mouseoverRangeFinderDisplay.X - 10, _mouseoverRangeFinderDisplay.Y - 15, objX, objY);
                        }
                    }
                }

                if (!MiniMapOverride)
                {
                    if ((!Map_IsContained_Horizontal(PlayfieldRect)) && (!Map_IsContained_Vertical(PlayfieldRect)))
                    {
                        ShowMiniMap = false;
                    }
                    else
                    {
                        ShowMiniMap = true;
                    }

                    if (WBRoom != null)
                    {
                        ShowMiniMap = true;
                    }
     
                    if (ShowMiniMap)
                    {
                        _mini_map.X = (PlayfieldRect.X + PlayfieldRect.Width) - _mini_map.Width;
                        _mini_map.Y = 0;
                        _mini_map.Height = (int)((Map.TextureHeight / Map.TextureWidth) * (float)_mini_map.Width);

                        _mini_map_thumb.X = (int)(-(Map.Position.X / (Map.TextureWidth * _playfield.Scale)) * (float)_mini_map.Width) + _mini_map.X;
                        _mini_map_thumb.Y = (int)(-(Map.Position.Y / (Map.TextureHeight * _playfield.Scale)) * (float)_mini_map.Height) + _mini_map.Y;
                        _mini_map_thumb.Width = (int)(_mini_map.Width * ((float)PlayfieldRect.Width / (Map.TextureWidth * _playfield.Scale)));
                        _mini_map_thumb.Height = (int)(_mini_map.Height * ((float)PlayfieldRect.Height / (Map.TextureHeight * _playfield.Scale)));

                        canvas.DrawFillRect(_mini_map, _mini_map_background);

                        // Draw rect for other users in a whiteboard room
                        if (wbRoom != null)
                        {
                            int originX = 0;
                            int originY = 0;
                            int screenSizeWidth = 0;
                            int screenSizeHeight = 0;
                            double screenZoom = 0.0;

                            foreach (string wbUser in wbRoom.MembershipList)
                            {
                                if (string.Compare(wbUser, DDD_Global.Instance.PlayerID) == 0)
                                {
                                    continue;
                                }

                                if (wbRoom.GetScreenViewInfo(wbUser, ref originX, ref originY, ref screenSizeWidth, ref screenSizeHeight,
                                        ref screenZoom))
                                {
                                    Rectangle userMiniMapRect = Rectangle.Empty;
                                    Vector2 _metersPerPixelValues = new Vector2();
                                    Vector2 userPosition = new Vector2();
                                    _metersPerPixelValues.X = UTM_Mapping.HorizonalMetersPerPixel;
                                    _metersPerPixelValues.Y = UTM_Mapping.VerticalMetersPerPixel;

                                    userPosition.X = (float) originX / _metersPerPixelValues.X;
                                    userPosition.Y = (float)originY  / _metersPerPixelValues.Y;
                                    userMiniMapRect.X = (int)((userPosition.X / (Map.TextureWidth)) * (float)_mini_map.Width) + _mini_map.X;
                                    userMiniMapRect.Y = (int)((userPosition.Y / (Map.TextureHeight)) * (float)_mini_map.Height) + _mini_map.Y;
                                    userMiniMapRect.Width = (int)((float)screenSizeWidth / _metersPerPixelValues.X /
                                        Map.TextureWidth * (float)_mini_map.Width);
                                    userMiniMapRect.Height = (int)((float)screenSizeHeight / _metersPerPixelValues.Y /
                                        Map.TextureHeight * (float)_mini_map.Height);

                                    // Draw rect for this a whiteboard user
                                    if (DMColorMap.ContainsKey(wbUser))
                                    {
                                        canvas.DrawRect(userMiniMapRect, Color.FromArgb(DMColorMap[wbUser]));
                                    }
                                    else
                                    {
                                        canvas.DrawRect(userMiniMapRect, Color.DarkBlue);
                                    }
                                }

                            }
                        }

                        // Draw rect for this user
                        if ((wbRoom != null) && DMColorMap.ContainsKey(DDD_Global.Instance.PlayerID))
                        {
                            canvas.DrawRect(_mini_map_thumb, Color.FromArgb(DMColorMap[DDD_Global.Instance.PlayerID]));
                        }
                        else
                        {
                            canvas.DrawRect(_mini_map_thumb, Color.Red);
                        }

                        lock (this)
                        {
                            DDDObjects selected = GetSelectedObject();
                            foreach (string obj_name in _playfield.PlayfieldObjects)
                            {
                                DDDObjects obj = (DDDObjects)_playfield.GetMappableObject(obj_name);
                                if (obj != null)
                                {
                                    _mini_map_track.X = (int)(((_mini_map.Width / Map.TextureWidth) * obj.Position.X) + _mini_map.X) - (int)(.5 * _mini_map_track.Width);
                                    _mini_map_track.Y = (int)(((_mini_map.Height / Map.TextureHeight) * obj.Position.Y) + _mini_map.Y) - (int)(.5 * _mini_map_track.Height);
                                    if (selected != null)
                                    {
                                        if ((selected.ID == obj.ID) && !ShowUnitColorOnMiniMap)
                                        {
                                            canvas.DrawTri(_mini_map_track, Color.Yellow, DIRECTION.UP);
                                            continue;
                                        }
                                    }

                                    if (!ShowUnitColorOnMiniMap)
                                    {
                                        canvas.DrawTri(_mini_map_track, Color.DodgerBlue, DIRECTION.UP);
                                    }
                                    else
                                    {
                                        canvas.DrawTri(_mini_map_track, obj.TextBoxColor, DIRECTION.UP);
                                    }

                                }
                            }


                            foreach (string obj_name in _playfield.PlayfieldObjects)
                            {
                                DDDObjects obj = (DDDObjects)_playfield.GetMappableObject(obj_name);
                                if (obj != null)
                                {
                                    _mini_map_track.X = (int)(((_mini_map.Width / Map.TextureWidth) * obj.Position.X) + _mini_map.X) - (int)(.5 * _mini_map_track.Width);
                                    _mini_map_track.Y = (int)(((_mini_map.Height / Map.TextureHeight) * obj.Position.Y) + _mini_map.Y) - (int)(.5 * _mini_map_track.Height);

                                    if (obj.IsBeingAttacked)
                                    {
                                        if (GameFramework.ElapsedSeconds(AnimationTimer, AnimationCycle))
                                        {
                                            AnimationTimer = GameFramework.QueryPerformanceTimer();
                                        }
                                        if (GameFramework.ElapsedSeconds(AnimationTimer, BlinkCycle))
                                        {
                                            canvas.DrawTri(_mini_map_track, Color.White, DIRECTION.UP);
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }



                if (ShowPosition)
                {

                    DDDObjects obj = _playfield.GetSelectedObject();
                    if (obj != null)
                    {
                        if (obj.IsPathCalculatorRunning())
                        {
                            canvas.DrawFillRect(_bottom_status_bar, _mini_map_background);
                            SizeF size = obj.DrawIcon(canvas, PlayfieldRect.X, _bottom_status_bar.Y, 30, 30);

                            int font_height = (Fonts["Arial8B"].MeasureString(null, obj.FullVelocityStr, DrawTextFormat.None, Color.White)).Height;

                            Fonts["Arial8B"].DrawText(null, obj.FullVelocityStr, PlayfieldRect.X + (int)size.Width + 2, _bottom_status_bar.Y, Color.White);
                            Fonts["Arial8B"].DrawText(null, obj.FullTTDStr, PlayfieldRect.X + (int)size.Width + 2, (_bottom_status_bar.Y + font_height), Color.White);
                            Fonts["Arial8B"].DrawText(null, obj.FullDestinationStr, PlayfieldRect.X + (int)size.Width + 2, (_bottom_status_bar.Y + (2 * font_height)), Color.White);
                        }
                        else
                        {
                            SizeF size = obj.DrawIcon(canvas, PlayfieldRect.X, _bottom_status_bar.Y, 30, 30);

                            int font_height = (Fonts["Arial10B"].MeasureString(null, obj.ObjectID, DrawTextFormat.None, Color.White)).Height;
                            Fonts["Arial10B"].DrawText(null, obj.ObjectID, PlayfieldRect.X + (int)size.Width, (_bottom_status_bar.Bottom - font_height), Color.White);
                        }
                    }
                }


                int width;
                String str = String.Empty;
                if (!IsPaused)
                {
                    if (DDD_Global.Instance.IsForkReplay)
                    {
                        str = String.Format("Fork Replay {0}", Time);
                    }
                    else
                    {
                        str = Time;
                    }
                }
                else
                {
                    str = "Paused";
                }
                width = (Fonts["Arial10B"].MeasureString(null, str, DrawTextFormat.None, Color.Yellow)).Width + 5;
                Fonts["Arial10B"].DrawText(null, str, _bottom_status_bar.X + (_bottom_status_bar.Width - width), _bottom_status_bar.Y + 5, Color.Yellow);
                //if (!IsPaused)
                //{
                //    if (DDD_Global.Instance.IsForkReplay)
                //    {
                //        width = (Fonts["Arial10B"].MeasureString(null, Time, DrawTextFormat.None, Color.Yellow)).Width + 5;
                //        Fonts["Arial10B"].DrawText(null, String.Format("Fork Replay {0}",Time), _bottom_status_bar.X + (_bottom_status_bar.Width - width), _bottom_status_bar.Y + 5, Color.Yellow);
                //    }
                //    else
                //    {
                //        width = (Fonts["Arial10B"].MeasureString(null, Time, DrawTextFormat.None, Color.Yellow)).Width + 5;
                //        Fonts["Arial10B"].DrawText(null, Time, _bottom_status_bar.X + (_bottom_status_bar.Width - width), _bottom_status_bar.Y + 5, Color.Yellow);
                //    }
                //}
                //else
                //{
                //    width = (Fonts["Arial10B"].MeasureString(null, Time, DrawTextFormat.None, Color.Yellow)).Width + 5;
                //    Fonts["Arial10B"].DrawText(null, "Paused", _bottom_status_bar.X + (_bottom_status_bar.Width - width), _bottom_status_bar.Y + 5, Color.Yellow);
                //}

            }

        }
Beispiel #34
0
        public void Initialize(DrawArgs drawArgs)
        {
            // Initialize fonts
            if (m_drawingFont == null)
            {
                System.Drawing.Font localHeaderFont = new System.Drawing.Font("Arial", 12.0f, FontStyle.Italic | FontStyle.Bold);
                m_drawingFont = new Microsoft.DirectX.Direct3D.Font(drawArgs.device, localHeaderFont);
            }

            if (m_wingdingsFont == null)
            {
                System.Drawing.Font wingdings = new System.Drawing.Font("Wingdings", 12.0f);
                m_wingdingsFont = new Microsoft.DirectX.Direct3D.Font(drawArgs.device, wingdings);
            }

            if (m_worldwinddingsFont == null)
            {
                AddFontResource(Path.Combine(Application.StartupPath, "World Wind Dings 1.04.ttf"));
                System.Drawing.Text.PrivateFontCollection fpc = new System.Drawing.Text.PrivateFontCollection();
                fpc.AddFontFile(Path.Combine(Application.StartupPath, "World Wind Dings 1.04.ttf"));
                System.Drawing.Font m_worldwinddings = new System.Drawing.Font(fpc.Families[0], 12.0f);
                m_worldwinddingsFont = new Microsoft.DirectX.Direct3D.Font(drawArgs.device, m_worldwinddings);
            }

            // Initialize icon if any
            if (m_imageName.Trim() != string.Empty)
            {
                object key = null;

                // Icon image from file
                m_iconTexture = (IconTexture)DrawArgs.Textures[m_imageName];
                if (m_iconTexture == null)
                {
                    key           = m_imageName;
                    m_iconTexture = new IconTexture(drawArgs.device, m_imageName);
                }

                if (m_iconTexture != null)
                {
                    m_iconTexture.ReferenceCount++;

                    if (key != null)
                    {
                        // New texture, cache it
                        DrawArgs.Textures.Add(key, m_iconTexture);
                    }

                    if (m_size.Width == 0)
                    {
                        m_size.Width = m_iconTexture.Width;
                    }

                    if (m_size.Height == 0)
                    {
                        m_size.Height = m_iconTexture.Height;
                    }

                    this.XScale = (float)m_size.Width / m_iconTexture.Width;
                    this.YScale = (float)m_size.Height / m_iconTexture.Height;
                }

                if (m_sprite == null)
                {
                    m_sprite = new Sprite(drawArgs.device);
                }
            }

            m_isInitialized = true;
        }
 /*-------------------------------------------------------------------------
  *
  * ---------------------------------------------------------------------------*/
 public textured_font(d3d_device device, string str, Microsoft.DirectX.Direct3D.Font font)
     : this(device, str, font, Format.A8R8G8B8)
 {
 }
Beispiel #36
0
        public override void Init()
        {
            var d3dDevice = D3DDevice.Instance.Device;

            MyShaderDir = ShadersDir;

            wav_files = Directory.GetFiles(MediaDir + "sound");

            //sound.Create(MediaDir + "sound\\smokeonthewater.wav");
            //sound.Create(MediaDir + "sound\\rolemu_-_neogauge.wav");        // super dificl
            //sound.Create(MediaDir + "sound\\rolem_-_Neoishiki.wav");            // buenisimo (dificil)
            //sound.Create(MediaDir + "sound\\Azureflux_-_06_-_Kinetic_Sands.wav");
            //sound.Create(MediaDir + "sound\\Azureflux_-_01_-_BOMB.wav");
            //sound.Create(MediaDir + "sound\\Azureflux_-_02_-_Waves.wav");       // muy bueno, facil
            //sound.Create(MediaDir + "sound\\Monplaisir_-_03_-_Level_0.wav");
            //sound.Create(MediaDir + "sound\\Monplaisir_-_04_-_Level_1.wav");           // monotono
            //sound.Create(MediaDir + "sound\\Monplaisir_-_05_-_Level_2.wav");           // monotono
            //sound.Create(MediaDir + "sound\\Monplaisir_-_06_-_Level_3.wav");
            //sound.Create(MediaDir + "sound\\Monplaisir_-_07_-_Level_4.wav");            // bueno
            //sound.Create(MediaDir + "sound\\tecno1.wav");                         // dificil
            //sound.Create(MediaDir + "sound\\ScoobyDooPaPa.wav");                         // interesante
            //sound.Create(MediaDir + "sound\\highway intro.wav");                // se va de escala
            //sound.Create(MediaDir + "sound\\Shook_Me_All_Night.wav");           // bajo volumen
            //sound.Create(MediaDir + "sound\\ACDC.wav");


            //Cargar Shader personalizado
            string compilationErrors;

            effect = Effect.FromFile(D3DDevice.Instance.Device, MyShaderDir + "shaders.fx",
                                     null, null, ShaderFlags.PreferFlowControl, null, out compilationErrors);
            if (effect == null)
            {
                throw new Exception("Error al cargar shader. Errores: " + compilationErrors);
            }
            //Configurar Technique dentro del shader
            effect.Technique = "DefaultTechnique";


            // para capturar el mouse
            var focusWindows = D3DDevice.Instance.Device.CreationParameters.FocusWindow;

            mouseCenter   = focusWindows.PointToScreen(new Point(focusWindows.Width / 2, focusWindows.Height / 2));
            mouseCaptured = false;
            //Cursor.Hide();

            // stencil
            g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(d3dDevice.PresentationParameters.BackBufferWidth,
                                                                  d3dDevice.PresentationParameters.BackBufferHeight,
                                                                  DepthFormat.D24S8, MultiSampleType.None, 0, true);
            g_pDepthStencilOld = d3dDevice.DepthStencilSurface;
            // inicializo el render target
            g_pRenderTarget = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth
                                          , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                                          Format.X8R8G8B8, Pool.Default);
            g_pRenderTarget2 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth
                                           , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                                           Format.X8R8G8B8, Pool.Default);
            g_pRenderTarget3 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth
                                           , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                                           Format.X8R8G8B8, Pool.Default);
            g_pRenderTarget4 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth
                                           , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                                           Format.X8R8G8B8, Pool.Default);
            g_pRenderTarget5 = new Texture(d3dDevice, d3dDevice.PresentationParameters.BackBufferWidth
                                           , d3dDevice.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget,
                                           Format.X8R8G8B8, Pool.Default);

            // Resolucion de pantalla
            effect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth);
            effect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight);

            CustomVertex.PositionTextured[] vertices =
            {
                new CustomVertex.PositionTextured(-1,  1, 1, 0, 0),
                new CustomVertex.PositionTextured(1,   1, 1, 1, 0),
                new CustomVertex.PositionTextured(-1, -1, 1, 0, 1),
                new CustomVertex.PositionTextured(1,  -1, 1, 1, 1)
            };
            //vertex buffer de los triangulos
            g_pVBV3D = new VertexBuffer(typeof(CustomVertex.PositionTextured),
                                        4, d3dDevice, Usage.Dynamic | Usage.WriteOnly,
                                        CustomVertex.PositionTextured.Format, Pool.Default);
            g_pVBV3D.SetData(vertices, 0, LockFlags.None);

            time = 0;

            sprite = new Sprite(d3dDevice);
            // ajusto las letras para que se vean mas o menos igual en todas las resoluciones.
            float kx = (float)d3dDevice.PresentationParameters.BackBufferWidth / 1366.0f;
            float ky = (float)d3dDevice.PresentationParameters.BackBufferHeight / 768.0f;
            float k  = Math.Min(kx, ky);

            // Fonts
            font = new Microsoft.DirectX.Direct3D.Font(d3dDevice, (int)(24 * k), 0, FontWeight.Light, 0, false, CharacterSet.Default,
                                                       Precision.Default, FontQuality.Default, PitchAndFamily.DefaultPitch, "Lucida Console");
            font.PreloadGlyphs('0', '9');
            font.PreloadGlyphs('a', 'z');
            font.PreloadGlyphs('A', 'Z');

            s_font = new Microsoft.DirectX.Direct3D.Font(d3dDevice, (int)(18 * k), 0, FontWeight.Light, 0, false, CharacterSet.Default,
                                                         Precision.Default, FontQuality.Default, PitchAndFamily.DefaultPitch, "Lucida Console");
            s_font.PreloadGlyphs('0', '9');
            s_font.PreloadGlyphs('a', 'z');
            s_font.PreloadGlyphs('A', 'Z');

            c64_font = new Microsoft.DirectX.Direct3D.Font(d3dDevice, (int)(40 * k), (int)(30 * k), FontWeight.Light, 0, false, CharacterSet.Default,
                                                           Precision.Default, FontQuality.Default, PitchAndFamily.DefaultPitch, "System");
            c64_font.PreloadGlyphs('0', '9');
            c64_font.PreloadGlyphs('a', 'z');
            c64_font.PreloadGlyphs('A', 'Z');
        }
Beispiel #37
0
 /// <summary>
 /// Initialize scene objects.
 /// </summary>
 protected override void InitializeDeviceObjects()
 {
     drawingFont = new Direct3D.Font(device, actualFont);                //.InitializeDeviceObjects(device);
 }
Beispiel #38
0
        /*-------------------------------------------------------------------------
         * 初期化
         * ---------------------------------------------------------------------------*/
        public d3d_device(System.Windows.Forms.Form form)
            : base()
        {
            // 작성パラメータ
            PresentParameters param = new PresentParameters();

            param.Windowed               = true;
            param.SwapEffect             = SwapEffect.Discard;
            param.PresentationInterval   = PresentInterval.Immediate;
            param.EnableAutoDepthStencil = true;
            param.AutoDepthStencilFormat = DepthFormat.D16;
            param.BackBufferCount        = 1;
            param.BackBufferFormat       = Format.Unknown;

            // デバイスを작성
            try{
                base.Create(form, param);
            }catch {
                MessageBox.Show("DirectX 초기화에 실패하였습니다. ", "초기화오류");
                return;
            }

            try{
                // リセット時のデリゲート추가
                base.device.DeviceReset += new System.EventHandler(device_reset);
                // 쉐이더の버전を調べる
                check_shader_support();

                // フォントを작성
                m_font       = new Microsoft.DirectX.Direct3D.Font(base.device, new System.Drawing.Font("MS UI Gothic", 9));
                m_font_small = new Microsoft.DirectX.Direct3D.Font(base.device, new System.Drawing.Font("MS UI Gothic", 8));
// CreaTypeで그리기できないのでメイリオはやめ
//				m_font			= new Microsoft.DirectX.Direct3D.Font(base.device, new System.Drawing.Font("メイリオ", 9));
//				m_font_small	= new Microsoft.DirectX.Direct3D.Font(base.device, new System.Drawing.Font("メイリオ", 7));

                m_font_sprite        = new Sprite(base.device);
                m_is_use_font_sprite = false;

                // 라인그리기
                m_line = new Line(base.device);

                // ステートの初期化
                device_reset(this, null);

                // 그리기支援
                m_points = new d3d_point(device);
                m_sprite = new d3d_sprite(device, is_use_ve1_1_ps1_1);

                // 시스템フォント
                m_systemfont = new d3d_systemfont(this);
                // 텍스쳐化されたフォント
                // あまり変動しない문자열그리기용
                m_textured_font = new d3d_textured_font(this, m_font);

                // デバイスの정보を得る
                get_device_information();
                // クライアント사이즈更新
                UpdateClientSize();
            }catch {
                MessageBox.Show("DirectX 초기화후 설정에 실패하였습니다. ", "초기화오류");
                base.Dispose();
            }

            m_skip_count   = 0;
            m_skip_max     = 0;
            m_is_must_draw = false;
        }
Beispiel #39
0
 public FontListElement(Microsoft.DirectX.Direct3D.Font font)
 {
     this.font = font;
 }
Beispiel #40
0
 public void InitializeDescTrenFont(string pFontName, float pSize, FontStyle pFontStyle, Color pDescColor)
 {
     this.textDescTren  = new Microsoft.DirectX.Direct3D.Font(this.device, new System.Drawing.Font(pFontName, pSize, pFontStyle));
     this.DescTrenColor = pDescColor;
 }
        private void Form1_Load(object sender, EventArgs e)
        {
            SetWindowLong(this.Handle, GWL_EXSTYLE,
            (IntPtr)(GetWindowLong(this.Handle, GWL_EXSTYLE) ^ WS_EX_LAYERED ^ WS_EX_TRANSPARENT));

            //Set the Alpha on the Whole Window to 255 (solid)
            SetLayeredWindowAttributes(this.Handle, 0, 255, LWA_ALPHA);

            //Init DirectX
            //This initializes the DirectX device. It needs to be done once.
            //The alpha channel in the backbuffer is critical.
            PresentParameters presentParameters = new PresentParameters();
            presentParameters.Windowed = true;
            presentParameters.SwapEffect = SwapEffect.Discard;
            presentParameters.BackBufferFormat = Format.A8R8G8B8;

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

            drawLine = new D3D.Line(this.device);
            drawBoxLine = new D3D.Line(this.device);
            drawCircleLine = new D3D.Line(this.device);
            drawFilledBoxLine = new D3D.Line(this.device);
            drawTriLine = new D3D.Line(this.device);

            CenterX = (float)this.ClientSize.Width / 2;
            CenterY = (float)this.ClientSize.Height / 2;

            CenterrX = this.ClientSize.Width / 2;
            CenterrY = this.ClientSize.Height / 2;

            font = new D3D.Font(device, new System.Drawing.Font("Fixedsys Regular", 15, FontStyle.Bold));

            Thread dx = new Thread(new ThreadStart(this.dxThread));
            dx.IsBackground = true;
            dx.Start();
        }
Beispiel #42
0
 public virtual void Dispose()
 {
     m_Font.Dispose();
     m_Font = null;
     m_Disposed = true;
 }
        private void InitializeGUI()
        {
            System.Drawing.Font localFont = new System.Drawing.Font("Arial", 8.0f, FontStyle.Regular);

              // Create a font we can draw with
              font = new Microsoft.DirectX.Direct3D.Font(device, localFont);
        }
Beispiel #44
0
 private void InitializeFont(string pFontName, float pSize, FontStyle pFontStyle)
 {
     this.text       = new Microsoft.DirectX.Direct3D.Font(this.device, new System.Drawing.Font(pFontName, pSize, pFontStyle));
     this.CounterPos = (int)this.MenuFontSize + 18;
 }
        private void OnNewDevice()
        {
            if (outSettings != null)
                outSettings.CreateDevice(this, out device, out pParams);

            if (device != null)
            {
                pipeline = new GraphicsFixedPipeline3D(device);
                deviceFont = new Microsoft.DirectX.Direct3D.Font(device, Font);

                sceneManger = new MoleculeSceneManager(device, outSettings);
            }
            else
            {
            }
        }
Beispiel #46
0
 private void InitFont()
 {
     System.Drawing.Font f = new System.Drawing.Font("Arial", 16f, FontStyle.Regular);
     font = new Microsoft.DirectX.Direct3D.Font(device, f);
 }
Beispiel #47
0
        private void init_gui()
        {
            ///////////////SYSTEM GUI///////////////////////////

            GUI_DEBUG = new gui_form_DEBUG(ref ENGINE.DEVICE, 800, 0, 514, 190);
            GUI_DEBUG.initialize_form(ref ENGINE.INPUT, RESOURCES.Pfad);
            GUI_DEBUG.REF_sprite = new Sprite(ENGINE.DEVICE);
            GUI_DEBUG.Text = "DEBUG";
            //////////////////CURSOR///////////////////////////
            CURSOR = new c_sprite(1, 1);

            CURSOR.box.Width = 51;
            CURSOR.box.Height = 51;
            CURSOR.Destbox.Width = 51;
            CURSOR.Destbox.Height = 51;
            ///////////////////////////////////////////////////
            ENERGY = new c_sprite(1, 3);

            ENERGY.box.Width = 120;
            ENERGY.box.Height = 120;
            ENERGY.Destbox.Width = 120;
            ENERGY.Destbox.Height = 120;

            //////VERWALTUNGSMENU/////////////////////////
            GUI_VERWALTUNG = new gui_form_VERWALTUNG(ref ENGINE.DEVICE, 350, 300, 350, 190);
            GUI_VERWALTUNG.REF_sprite = GUI_DEBUG.REF_sprite;
            GUI_VERWALTUNG.initialize_form(ref ENGINE.INPUT, RESOURCES.Pfad);
            GUI_VERWALTUNG.visible = false;
             ///////////////////////////////////////////////////////

            line = new c_line_list(ref ENGINE.DEVICE, 111, 100, 555, 555, Color.Yellow.ToArgb());

            firstFont = new Microsoft.DirectX.Direct3D.Font(ENGINE.DEVICE, 20, 5, FontWeight.Medium, 0, false, CharacterSet.Default, Precision.Default, FontQuality.Default, PitchAndFamily.DefaultPitch | PitchAndFamily.FamilyDoNotCare, "Verdana");

            ////////////////GUI FÜR GESPRÄCHE/////////////////////////
            GUI_TALK = new gui_form_INFO(ref ENGINE.DEVICE, 300, 300, 514, 190);
            GUI_TALK.REF_sprite = GUI_DEBUG.REF_sprite;
            GUI_TALK.initialize_form(ref ENGINE.INPUT, RESOURCES.Pfad);

            GUI_TALK.Text = "Hallo so siehts hier aus bei uns in unserer (noch) bescheidenen Welt!";
        }
Beispiel #48
0
 public void InitDevice(Device device, bool isReset)
 {
     infoD3DFont = new D3DFont(device, new System.Drawing.Font("Arial", 12));
 }
    public static void MeasureText(Font fnt, string text, ref float textwidth, ref float textheight, int fontSize)
    {
      if (text[0] == ' ') // anti-trim
      {
        text = "_" + text.Substring(1);
      }
      if (text[text.Length - 1] == ' ')
      {
        text = text.Substring(0, text.Length - 1) + '_';
      }

      // Text drawing doesnt work with DX9Ex & sprite
      if (GUIGraphicsContext.IsDirectX9ExUsed())
      {
        MeasureText(text, ref textwidth, ref textheight, fontSize);
      }
      else
      {
        if (_d3dxSprite == null)
        {
          _d3dxSprite = new Sprite(GUIGraphicsContext.DX9Device);
        }
        Rectangle rect = fnt.MeasureString(_d3dxSprite, text, DrawTextFormat.NoClip, Color.Black);
        textwidth = rect.Width;
        textheight = rect.Height;
      }
      return;
    }
Beispiel #50
0
        private D3D2DRender()
        {
            m_d3dDevice = D3DDeviceService.Instance.DeviceInstance;
            m_pVBRect = new VertexBuffer(typeof(CustomVertex.TransformedColored), 5, m_d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.TransformedColored.Format, Pool.Default);
            m_pVBFilledRect = new VertexBuffer(typeof(CustomVertex.TransformedColored), 4, m_d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.TransformedColored.Format, Pool.Default);
            m_pVBLine = new VertexBuffer(typeof(CustomVertex.TransformedColored), 2, m_d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.TransformedColored.Format, Pool.Default);

            m_pFont = new Microsoft.DirectX.Direct3D.Font(m_d3dDevice, new System.Drawing.Font("Verdana", 9.0f));

            GC.SuppressFinalize(m_pFont);
        }
        /// <summary>
        /// Initializes the Managed Direct3D Wrapper.
        /// 
        /// This overload is designed for displaying a diferent resolution then the controls size.
        /// </summary>
        /// <param name="renderWindow">Window to render to.</param>
        /// <param name="screenWidth">Width of the screen in pixels.</param>
        /// <param name="screenHeight">Height of the screen in pixels.</param>
        /// <param name="vsync">Should the renderer wait for a vsync before drawing?</param>
        /// <returns>true if successful, false otherwise.</returns>
        public bool InitManagedDirect3D(System.Windows.Forms.Control renderWindow, int screenWidth, int screenHeight, bool vsync)
        {
            try
            {
                // Now  setup our D3D present parameters
                presentParams = new PresentParameters();
                presentParams.BackBufferWidth = screenWidth;
                presentParams.BackBufferHeight = screenHeight;
                //taking out the option for fullscreen mode
                //presentParams.BackBufferFormat = (isWindowed) ? Format.Unknown : Format.R5G6B5;
                presentParams.BackBufferFormat = Format.Unknown;
                presentParams.BackBufferCount = 1;
                presentParams.MultiSample = MultiSampleType.None;
                presentParams.MultiSampleQuality = 0;
                presentParams.SwapEffect = SwapEffect.Copy;// Discard;
                presentParams.DeviceWindow = renderWindow;
                //taking out the option for fullscreen mode
                //presentParams.Windowed = isWindowed;
                presentParams.Windowed = true;
                presentParams.EnableAutoDepthStencil = false;
                presentParams.FullScreenRefreshRateInHz = 0;
                presentParams.PresentationInterval = (vsync) ? PresentInterval.Default : PresentInterval.Immediate;

                // only Create if we haven't done so already
                if(device == null)
                device = new Device(0, DeviceType.Hardware, renderWindow,
                        CreateFlags.HardwareVertexProcessing, presentParams);

                //Create the SwapChain
            lSwapChains.Add(new ManagedSwapChain(device, presentParams));
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create D3D Device", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return false;
            }

            try
            {
                sprite = new Microsoft.DirectX.Direct3D.Sprite(device);
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create the Sprite object", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return false;
            }

            try
            {
                line = new Microsoft.DirectX.Direct3D.Line(device);

                line.Antialias = true;
                line.Width = 3.0f;
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create the Line Object", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return false;
            }

            try
            {
                fontDescription.FaceName = "arial";
                fontDescription.Quality = FontQuality.Default;
                fontDescription.Weight = FontWeight.Bold;

                font = new Microsoft.DirectX.Direct3D.Font(device, fontDescription);

                line.Antialias = true;
                line.Width = 3.0f;
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create the font Object", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return false;
            }

            return true;
        }
Beispiel #52
0
 /// <summary>
 /// Measures the rectangle dimensions of the specified text string when
 /// drawn with the specified <see cref="Microsoft.DirectX.Direct3D.Sprite">
 /// Microsoft.DirectX.Direct3D.Sprite</see> object.
 /// </summary>
 /// <param name="font">
 /// The Direct3D font for which to measure the specified text.
 /// </param>
 /// <param name="sprite">
 /// A <see cref="Microsoft.DirectX.Direct3D.Sprite">Sprite</see> object that
 /// contains the string.
 /// </param>
 /// <param name="text">String to measure.</param>
 /// <param name="width">Maximum width of the string.</param>
 /// <param name="color">Color of the text.</param>
 /// <returns>
 /// A Rectangle structure that contains the rectangle, in logical coordinates, that
 /// encompasses the formatted text string.
 /// </returns>
 public static Rectangle MeasureString(Direct3D.Font font, Sprite sprite, String text, int width, Color color)
 {
     return(font.MeasureString(sprite, WrapString(sprite, font, text, width, color), DrawTextFormat.None, color));
 }
Beispiel #53
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DXWindow"/> class.
 /// </summary>
 /// <param name="controlHost"></param>
 public DXWindow(IDirectXControlHost controlHost)
     : base(controlHost)
 {
     this.Font      = new System.Drawing.Font("Veranda", 24F, FontStyle.Bold);
     this.titleFont = new Microsoft.DirectX.Direct3D.Font(controlHost.Device, this.Font);
 }
Beispiel #54
0
        public override void RenderContents(DrawArgs drawArgs)
        {
            m_DrawArgs = drawArgs;
            try
            {
                if (itemFont == null)
                {
                    itemFont = drawArgs.CreateFont(World.Settings.LayerManagerFontName,
                                                   World.Settings.LayerManagerFontSize, World.Settings.LayerManagerFontStyle);

                    // TODO: Fix wingdings menu problems
                    System.Drawing.Font localHeaderFont = new System.Drawing.Font("Arial", 12.0f, FontStyle.Italic | FontStyle.Bold);
                    headerFont = new Microsoft.DirectX.Direct3D.Font(drawArgs.device, localHeaderFont);

                    System.Drawing.Font wingdings = new System.Drawing.Font("Wingdings", 12.0f);
                    wingdingsFont = new Microsoft.DirectX.Direct3D.Font(drawArgs.device, wingdings);

                    AddFontResource(Path.Combine(Application.StartupPath, "World Wind Dings 1.04.ttf"));
                    System.Drawing.Text.PrivateFontCollection fpc = new System.Drawing.Text.PrivateFontCollection();
                    fpc.AddFontFile(Path.Combine(Application.StartupPath, "World Wind Dings 1.04.ttf"));
                    System.Drawing.Font worldwinddings = new System.Drawing.Font(fpc.Families[0], 12.0f);
                    worldwinddingsFont = new Microsoft.DirectX.Direct3D.Font(drawArgs.device, worldwinddings);
                }

                this.updateList();

                this.worldwinddingsFont.DrawText(
                    null,
                    "E",
                    new System.Drawing.Rectangle(this.Right - 16, this.Top + 2, 20, topBorder),
                    DrawTextFormat.None,
                    TextColor);

                int numItems    = GetNumberOfUncollapsedItems();
                int totalHeight = GetItemsHeight(drawArgs);                //numItems * ItemHeight;
                showScrollbar = totalHeight > ClientHeight;
                if (showScrollbar)
                {
                    double percentHeight   = (double)ClientHeight / totalHeight;
                    int    scrollbarHeight = (int)(ClientHeight * percentHeight);

                    int maxScroll = totalHeight - ClientHeight;

                    if (scrollBarPosition < 0)
                    {
                        scrollBarPosition = 0;
                    }
                    else if (scrollBarPosition > maxScroll)
                    {
                        scrollBarPosition = maxScroll;
                    }

                    // Smooth scroll
                    const float scrollSpeed       = 0.3f;
                    float       smoothScrollDelta = (scrollBarPosition - scrollSmoothPosition) * scrollSpeed;
                    float       absDelta          = Math.Abs(smoothScrollDelta);
                    if (absDelta > 100f || absDelta < 3f)
                    {
                        // Scroll > 100 pixels and < 1.5 pixels faster
                        smoothScrollDelta = (scrollBarPosition - scrollSmoothPosition) * (float)Math.Sqrt(scrollSpeed);
                    }

                    scrollSmoothPosition += smoothScrollDelta;

                    if (scrollSmoothPosition > maxScroll)
                    {
                        scrollSmoothPosition = maxScroll;
                    }

                    int scrollPos = (int)((float)percentHeight * scrollBarPosition);

                    int color = isScrolling ? World.Settings.scrollbarHotColor : World.Settings.scrollbarColor;
                    MenuUtils.DrawBox(
                        Right - ScrollBarSize + 2,
                        ClientTop + scrollPos,
                        ScrollBarSize - 3,
                        scrollbarHeight + 1,
                        0.0f,
                        color,
                        drawArgs.device);

                    scrollbarLine[0].X = this.Right - ScrollBarSize;
                    scrollbarLine[0].Y = this.ClientTop;
                    scrollbarLine[1].X = this.Right - ScrollBarSize;
                    scrollbarLine[1].Y = this.Bottom;
                    MenuUtils.DrawLine(scrollbarLine,
                                       DialogColor,
                                       drawArgs.device);
                }

                this.headerFont.DrawText(
                    null, "Layer Manager",
                    new System.Drawing.Rectangle(Left + 5, Top + 1, Width, topBorder - 2),
                    DrawTextFormat.VerticalCenter, TextColor);

                Microsoft.DirectX.Vector2[] headerLinePoints = new Microsoft.DirectX.Vector2[2];
                headerLinePoints[0].X = this.Left;
                headerLinePoints[0].Y = this.Top + topBorder - 1;

                headerLinePoints[1].X = this.Right;
                headerLinePoints[1].Y = this.Top + topBorder - 1;

                MenuUtils.DrawLine(headerLinePoints, DialogColor, drawArgs.device);

                int runningItemHeight = 0;
                if (showScrollbar)
                {
                    runningItemHeight = -(int)Math.Round(scrollSmoothPosition);
                }

                // Set the Direct3D viewport to match the layer manager client area
                // to clip the text to the window when scrolling
                Viewport lmClientAreaViewPort = new Viewport();
                lmClientAreaViewPort.X      = ClientLeft;
                lmClientAreaViewPort.Y      = ClientTop;
                lmClientAreaViewPort.Width  = ClientWidth;
                lmClientAreaViewPort.Height = ClientHeight;
                Viewport defaultViewPort = drawArgs.device.Viewport;
                drawArgs.device.Viewport = lmClientAreaViewPort;
                for (int i = 0; i < _itemList.Count; i++)
                {
                    if (runningItemHeight > ClientHeight)
                    {
                        // No more space for items
                        break;
                    }
                    LayerMenuItem lmi = (LayerMenuItem)_itemList[i];
                    runningItemHeight += lmi.Render(
                        drawArgs,
                        ClientLeft,
                        ClientTop,
                        runningItemHeight,
                        ClientWidth,
                        ClientBottom,
                        itemFont,
                        wingdingsFont,
                        worldwinddingsFont,
                        MouseOverItem);
                }
                drawArgs.device.Viewport = defaultViewPort;
            }
            catch (Exception caught)
            {
                Log.Write(caught);
            }
        }
        public Form1()
        {
            InitializeComponent();
            this.Text = GetUniqueKey(20);
            //Make the window's border completely transparant
            SetWindowLong(this.Handle, GWL_EXSTYLE,
                    (IntPtr)(GetWindowLong(this.Handle, GWL_EXSTYLE) ^ WS_EX_LAYERED ^ WS_EX_TRANSPARENT));

            //Set the Alpha on the Whole Window to 255 (solid)
            SetLayeredWindowAttributes(this.Handle, 0, 255, LWA_ALPHA);

            //Init DirectX
            //This initializes the DirectX device. It needs to be done once.
            //The alpha channel in the backbuffer is critical.
            D3D.PresentParameters presentParameters = new D3D.PresentParameters();
            presentParameters.Windowed = true;
            presentParameters.SwapEffect = D3D.SwapEffect.Discard;
            presentParameters.BackBufferFormat = D3D.Format.A8R8G8B8;

            this.device = new D3D.Device(0, D3D.DeviceType.Hardware, this.Handle,
            D3D.CreateFlags.HardwareVertexProcessing, presentParameters);

            line = new D3D.Line(this.device);
            font = new D3D.Font(device, new System.Drawing.Font("Tahoma", 9, FontStyle.Regular));

            Thread dx = new Thread(new ThreadStart(this.dxThread));
            dx.IsBackground = true;
            dx.Start();
        }
Beispiel #56
0
        /// <summary>
        /// Initializes the Managed Direct3D Wrapper.
        /// </summary>
        /// <param name="renderWindow">Window to render to.</param>
        /// <param name="screenWidth">Width of the screen in pixels.</param>
        /// <param name="screenHeight">Height of the screen in pixels.</param>
        /// <param name="isWindowed">Is the application windowed or not (!!ALWAYS PASS true FOR NOW!!).</param>
        /// <param name="vsync">Should the renderer wait for a vsync before drawing?</param>
        /// <returns>true if successful, false otherwise.</returns>
        public bool InitManagedDirect3D(System.Windows.Forms.Control renderWindow, int screenWidth, int screenHeight, bool isWindowed, bool vsync)
        {
            try
            {
                // Now  setup our D3D present parameters
                presentParams = new PresentParameters();
                presentParams.BackBufferWidth           = screenWidth;
                presentParams.BackBufferHeight          = screenHeight;
                presentParams.BackBufferFormat          = (isWindowed) ? Format.Unknown : Format.R5G6B5;
                presentParams.BackBufferCount           = 1;
                presentParams.MultiSample               = MultiSampleType.None;
                presentParams.MultiSampleQuality        = 0;
                presentParams.SwapEffect                = SwapEffect.Copy;// Discard;
                presentParams.DeviceWindow              = renderWindow;
                presentParams.Windowed                  = isWindowed;
                presentParams.EnableAutoDepthStencil    = false;
                presentParams.FullScreenRefreshRateInHz = 0;
                presentParams.PresentationInterval      = (vsync) ? PresentInterval.Default : PresentInterval.Immediate;

                device = new Device(0, DeviceType.Hardware, renderWindow,
                                    CreateFlags.HardwareVertexProcessing, presentParams);
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create D3D Device", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return(false);
            }

            try
            {
                sprite = new Microsoft.DirectX.Direct3D.Sprite(device);
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create the Sprite object", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return(false);
            }

            try
            {
                line = new Microsoft.DirectX.Direct3D.Line(device);

                line.Antialias = true;
                line.Width     = 3.0f;
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create the Line Object", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return(false);
            }

            try
            {
                fontDescription.FaceName = "arial";
                fontDescription.Quality  = FontQuality.Default;
                fontDescription.Weight   = FontWeight.Bold;

                font = new Microsoft.DirectX.Direct3D.Font(device, fontDescription);

                line.Antialias = true;
                line.Width     = 3.0f;
            }
            catch (Exception)
            {
                DialogResult r = MessageBox.Show("Failed to Create the font Object", "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                return(false);
            }

            return(true);
        }
Beispiel #57
0
        ////////////////////////////////////////////////////////////////////////////////////
        void ResetAll(string fn)
        {
            ////////////////////////////////////////////////////////////////////////////////////
            //所有关键变量的清空和初始化
            EnableColoring       = true;
            EnableLights         = false;
            DisplayWireFrame     = true;
            DisplayHorizonalMesh = true;
            DisplayVerticalMesh  = true;
            DisplayInfoHUD       = true;

            //挤压Mesh的球面中心点
            center = new Vector3();

            //当前选中的多边形编号及其质心
            curr_district = 0;
            curr_centroid = new Vector3();

            //world中的平移矢量
            world_translation = new Vector3();                  //其值要么等于center,要么等于当前选择的面质心坐标

            //World等比放大系数,暂时不用
            scaling = 1F;

            //Direct3D相关
            device         = null;
            device_lost    = false;
            present_params = null;
            batch          = 0;

            //Direct3D资源相关
            font_selected    = font_hud = null;
            d3dfont_selected = d3dfont_hud = null;
            bmp_hud          = null;
            bkground_hud     = null;
            sprite           = null;

            //显示信息相关
            filename = message = null;

            //窗口状态相关
            onpaint_enabled = true;

            ////////////////////////////////////////////////////////////////////////////////////
            //生成原始数据和所有点、面和线框
            sec = new Sec(fn);
            ms  = new ExtrusionMesh(sec, Color.White, EnableColoring);
            ws  = new WallMesh(sec, Color.Gainsboro);
            pl  = new PartitionLines(ms.polys, Color.Red);
            wpl = new WallPartitionLines(sec, Color.Blue);

            //对sl采取的管理策略是不同的,其VertexBuffer和其自身将被同时创建或删除
            //这里无需初始化,InitializeGraphics中自然会初始化
            sl = null;

            //初始化当前选中的多边形的质心
            curr_centroid = ms.polys[curr_district].GetCentroid();

            //设置标题栏
            FileInfo fi = new FileInfo(fn);

            filename = fn; // fi.Name.ToLower();
            Text     = "3D .Sec Viewer - " + filename;

            //初始化信息字符串
            GenerateMessageString();
        }
Beispiel #58
0
 private void InitializeFont()
 {
     System.Drawing.Font systemfont = new System.Drawing.Font("Tahoma", 12f, FontStyle.Regular);
     text = new D3D.Font(device, systemfont);
 }
        /// <summary>
        /// Initializes Direct3D with a render target and backbuffer size.
        /// </summary>
        /// <param name="renderWindow">Window to render to.</param>
        /// <param name="screenWidth">Width of the screen in pixels.</param>
        /// <param name="screenHeight">Height of the screen in pixels.</param>
        /// <param name="vsync">Should the renderer wait for a vsync before drawing?</param>
        /// <returns>true if successful, false otherwise.</returns>
        public bool Initialize( Control renderWindow, int screenWidth, int screenHeight, bool vsync )
        {
            // Verify that the device has not been initialized
            if( m_Device != null )
                return false;

            // Set up the Direct3D device
            try
            {
                // Set the present parameters
                m_PresentParams = new PresentParameters( );
                m_PresentParams.BackBufferWidth = screenWidth;
                m_PresentParams.BackBufferHeight = screenHeight;
                m_PresentParams.BackBufferFormat = Format.Unknown;
                m_PresentParams.BackBufferCount = 1;
                m_PresentParams.MultiSample = MultiSampleType.None;
                m_PresentParams.MultiSampleQuality = 0;
                m_PresentParams.SwapEffect = SwapEffect.Copy;
                m_PresentParams.DeviceWindow = renderWindow;
                m_PresentParams.Windowed = true;
                m_PresentParams.EnableAutoDepthStencil = false;
                m_PresentParams.FullScreenRefreshRateInHz = 0;
                m_PresentParams.PresentationInterval = (vsync) ? PresentInterval.Default : PresentInterval.Immediate;

                // Create the device
                m_Device = new Device( 0, DeviceType.Hardware, renderWindow,
                            CreateFlags.HardwareVertexProcessing, m_PresentParams );

                // Add the window to the render target list
                m_RenderTargets.Add( new RenderTarget( m_Device, m_PresentParams ) );
            }
            catch( Exception ex)
            {
                DialogResult r = MessageBox.Show( "Failed to Create D3D Device\n\n" + ex.Message, "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation );

                return false;
            }

            // Set up the Sprite object
            try
            {
                m_Sprite = new Sprite( m_Device );
            }
            catch( Exception ex)
            {
                DialogResult r = MessageBox.Show( "Failed to Create the Sprite object\n\n" + ex.Message, "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation );

                return false;
            }

            // Set up the Texture for rectangles & lines
            try
            {
                // Allocate the texture
                m_Texture = new Texture( m_Device, 1, 1, 1, Usage.None, Format.A8R8G8B8, Pool.Managed );

                // Set the pixel color to White
                GraphicsStream stream = m_Texture.LockRectangle( 0, LockFlags.Discard );

                byte[] color = new byte[4];
                for( int i = 0; i < 4; i++ )
                    color[ i ] = 0xFF;
                stream.Write( color, 0, 4 );

                m_Texture.UnlockRectangle( 0 );
            }
            catch( Exception ex )
            {
                DialogResult r = MessageBox.Show( "Failed to Create the Texture Object\n\n" + ex.Message, "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation );

                return false;
            }

            // Set up the Font object
            try
            {
                m_FontDescription.FaceName = "Arial";
                m_FontDescription.Quality = FontQuality.Default;
                m_FontDescription.Weight = FontWeight.SemiBold;

                m_Font = new Microsoft.DirectX.Direct3D.Font( m_Device, m_FontDescription );
            }
            catch( Exception ex )
            {
                DialogResult r = MessageBox.Show( "Failed to Create the font Object\n\n" + ex.Message, "ManagedDirect3D::Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation );

                return false;
            }

            return true;
        }
Beispiel #60
0
 public Rectangle MeasureStringIfIncreasedBy(string addition)
 {
     return(Font.MeasureString(UI.CurrentHud.SpriteManager, text + addition, style.Flags, normal));
 }