Sharpdx D3D9 nothing draw - c#

I try to follow their examples on github and i just want to draw a line. But when the window opens, there only a blackscreen. I dont know what i did wrong.
Here is my source code.
Thank you for helping !
static void Main()
{
var form = new RenderForm("Test");
int width = form.ClientSize.Width;
int height = form.ClientSize.Height;
var device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(width, height) { PresentationInterval = PresentInterval.One });
Line line = new Line(device);
RawVector2[] vertices =
{
new RawVector2(10, 10),
new RawVector2(10, 10)
};
RenderLoop.Run(form, () =>
{
device.Clear(ClearFlags.Target, new RawColorBGRA(0, 0, 0, 1), 1.0f, 0);
device.BeginScene();
line.Width = 10;
line.GLLines = true;
line.Antialias = false;
line.Draw(vertices, new RawColorBGRA(254, 254, 254, 1));
device.EndScene();
device.Present();
});
}

This might not be your error but it won't help matters because even if there are no errors you will see very little. I have used it but only in a window context and I followed https://github.com/Dan6040/SharpDX-Rastertek-Tutorials because I was coming from C++ Unreal, Raw DX9, and C# Unity, XNA framework.
Your vertices are drawing a 1-pixel dot because you need 2 vectors at different locations to draw a line
[
new RawVector2(10, 10),
new RawVector2(10, 10)
]
That is saying draw from x:10 y:10 to x:10 y:10
try:
[
new RawVector2(10, 10),
new RawVector2(30, 30)
]
So to better explain to draw a triangle you need 3 points and 3 lines, but to draw each line you need points in your ordering
[
new RawVector2(10, 10),
new RawVector2(10, 30),
new RawVector2(30, 30),
new RawVector2(10, 10)
]
So that works by saying draw from 10,10 to 10,30 then to 30,30 and finally back to 10,10
Just to note this is why Games engines don't work through arrays of points they are arrays of pointers to points so you only have the point objects in memory once and you just using pointers to them E.G
static void Main()
{
var form = new RenderForm("Test");
int width = form.ClientSize.Width;
int height = form.ClientSize.Height;
var device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(width, height) { PresentationInterval = PresentInterval.One });
Line line = new Line(device);
RawVector2[] TrianglePoints=
{
new RawVector2(10, 10),
new RawVector2(10, 30),
new RawVector2(30, 30)
};
RawVector2[] vertices = {
TrianglePoints[0],
TrianglePoints[1],
TrianglePoints[2],
TrianglePoints[0]
}
RenderLoop.Run(form, () =>
{
device.Clear(ClearFlags.Target, new RawColorBGRA(0, 0, 0, 1), 1.0f, 0);
device.BeginScene();
line.Width = 10;
line.GLLines = true;
line.Antialias = false;
line.Draw(vertices, new RawColorBGRA(254, 254, 254, 1));
device.EndScene();
device.Present();
});
}

Related

SharpDX is filling entire form instead of drawing triangle

I'm trying to write simple DirectX 11 app using C# and SharpDX. I wanted to test basic drawing but when i run the program, i will get entire form filled with red color. When i change the vertices its drawing unwanted shapes. Clear color works.
I tried changing some properties but nothing helps.
Here is the code:
private Vector3[] Vertices = new Vector3[]
{
new Vector3(-0.5f, 0.5f, 0), new Vector3(0.5f, 0.5f, 0), new Vector3(0, -0.5f, 0)
};
private D3D11.Buffer VertexBuffer;
public Game()
{
RenderForm = new RenderForm("Test Form");
RenderForm.ClientSize = new Size(Width, Height);
RenderForm.AllowUserResizing = false;
InitDeviceResources();
InitShaders();
InitVertexBuffer();
}
public void Run()
{
RenderLoop.Run(RenderForm, RenderCallback);
}
private void InitVertexBuffer()
{
VertexBuffer = D3D11.Buffer.Create<Vector3>(Device, BindFlags.VertexBuffer, Vertices);
}
private void InitShaders()
{
using (ShaderBytecode vertexShaderBytecode = ShaderBytecode.CompileFromFile("vertexShader.hlsl", "main", "vs_4_0", ShaderFlags.Debug))
{
InputSignature = ShaderSignature.GetInputSignature(vertexShaderBytecode);
VertexShader = new VertexShader(Device, vertexShaderBytecode);
}
using (ShaderBytecode pixelShaderBytecode = ShaderBytecode.CompileFromFile("pixelShader.hlsl", "main", "ps_4_0", ShaderFlags.Debug))
{
PixelShader = new PixelShader(Device, pixelShaderBytecode);
}
Context.VertexShader.Set(VertexShader);
Context.PixelShader.Set(PixelShader);
Context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
InputLayout = new InputLayout(Device, InputSignature, InputElements);
Context.InputAssembler.InputLayout = InputLayout;
}
private void InitDeviceResources()
{
ModeDescription backBufferDesc = new ModeDescription(Width, Height, new Rational(60, 1), Format.B8G8R8A8_UNorm);
SwapChainDescription swapChainDesc = new SwapChainDescription()
{
BufferCount = 1,
IsWindowed = true,
OutputHandle = RenderForm.Handle,
ModeDescription = backBufferDesc,
SampleDescription = new SampleDescription(1, 0),
Usage = Usage.RenderTargetOutput
};
D3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out Device, out SwapChain);
Context = Device.ImmediateContext;
Viewport = new Viewport(0, 0, Width, Height);
Context.Rasterizer.SetViewport(Viewport);
using (Texture2D backBuffer = SwapChain.GetBackBuffer<Texture2D>(0))
{
RenderTarget = new RenderTargetView(Device, backBuffer);
}
}
private void RenderCallback()
{
Draw();
}
private void Draw()
{
Context.OutputMerger.SetRenderTargets(RenderTarget);
Context.ClearRenderTargetView(RenderTarget, new Color4(0, 0, 1, 1));
Context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(VertexBuffer, Utilities.SizeOf<Vector3>(), 0));
Context.Draw(Vertices.Count(), 0);
SwapChain.Present(1, PresentFlags.None);
}
I finally solved this. There must be Format.R32G32B32_Float instead of Format.R32G32B32A32_Float

Extracting Text from Camera in opencv (c#)

I wrote some code for finding text from a camera. Actually I first wrote code for finding text in an image and I succeeded but I cant find text from the camera.
Thank you in advance.
In addition I wrote this code in classlibrary so I can't test it well.
public string GetImageText(string imgPath)
{
pathImage = imgPath;
//CvCapture cap = new CvCapture(0);
CvCapture cap;
//CvCapture cap = new CvCapture(imgPath);
cap = CvCapture.FromFile(imgPath);
cap= CvCapture.FromCamera(CaptureDevice.Any);
// img = new IplImage(imgPath, LoadMode.Color);
// cap =CvCapture.FromFile(imgPath);
// IplImage frame = new IplImage();
// imgPath=cap.QueryFrame(frame);
frame = cap.QueryFrame();
// IplImage frame = new IplImage();
// BitmapConverter.ToBitmap(frame);
//frame = new IplImage(imgPath, LoadMode.Color);
if (frame != null)
{
IplImage img1 = new IplImage(frame.Size, BitDepth.U8, 1);
IplConvKernel element = Cv.CreateStructuringElementEx(21, 3, 10, 2, ElementShape.Rect, null);
aimg = new IplImage(frame.Size, BitDepth.U8, 1);
IplImage temp = aimg.Clone();
IplImage dest = aimg.Clone();
frame.CvtColor(aimg, ColorConversion.RgbaToGray);
bimg = aimg.Clone();
Cv.Smooth(aimg, aimg, SmoothType.Gaussian);
Cv.MorphologyEx(aimg, temp, dest, element, MorphologyOperation.TopHat, 1);
Cv.Threshold(dest, aimg, 128, 255, ThresholdType.Binary | ThresholdType.Otsu);
Cv.Smooth(aimg, dest, SmoothType.Median);
Cv.Dilate(dest, dest, element, 2);
Cv.ReleaseImage(temp);
Cv.ReleaseImage(dest);
IplImage labelImage = new IplImage(frame.Size, CvBlobLib.DepthLabel, 1);
labelImage = new IplImage(frame.Size, BitDepth.U8, 1);
frame = new IplImage(frame.Size, BitDepth.U8, 1);
blob = new CvBlobs();
text.Clear();
CvBlobLib.Label(labelImage, blob);
CvBlobLib.FilterByArea(blob, 6, 10);
IplImage imgtemp = frame.Clone();
foreach (var item in blob)
{
item.Value.SetImageRoiToBlob(bimg);
double ratio = (double)item.Value.Rect.Width / item.Value.Rect.Height;
double angle = (double)item.Value.Angle();
if (ratio > 3.5 && ratio < 5.4 && angle > -15 && angle < 15)
{
IplImage texttemp = new IplImage(new CvSize(140, 27), bimg.Depth, bimg.NChannels);
// texttemp.Flip( null , FlipMode.X );
Cv.Resize(bimg, texttemp);
text.Add(texttemp);
frame.Rectangle(item.Value.Rect, new CvScalar(0, 0, 255), 2, LineType.Link4);
// frame.Flip(null, FlipMode.X);
// frame.Rectangle(item.Value.Rect, new CvScalar(0, 0, 255), 2, LineType.Link4)=RotateFlipType.Rotate180FlipNone()
// RotateFlipType.Rotate180FlipX(frame.Rectangle(item.Value.Rect, new CvScalar(0, 0, 255), 2, LineType.Link4));
// flipImage=frame.Rectangle(item.Value.Rect, new CvScalar(0, 0, 255), 2, LineType.Link4);
}
}
textList.Clear();
}
return pathImage;
}
I don't have the reputation needed to comment, so this will have to be in the form of an answer. It looks like pathImage doesn't get any value after you do all the processing to find the text - it keeps the value of imgPath, so you just return the same value you put in.

UIScrollView Scroll Not working Xamarin IOS

Create the scroll view added to UIViewController View
UIScroll scroll_View;
scroll_View = new UIScrollView {
BackgroundColor = UIColor.Black,
Frame = View.Frame,
ContentSize = new SizeF(320,720),
};
View.addSubView(scroll_View);// Added to Regisration ViewController
// Created text Fields
firstName = new UITextField {
Placeholder = "Enter firstName",
BorderStyle = UITextBorderStyle.None,
VerticalAlignment = UIControlContentVerticalAlignment.Center,
AutocorrectionType = UITextAutocorrectionType.No,
AutocapitalizationType = UITextAutocapitalizationType.None,
ClearButtonMode = UITextFieldViewMode.WhileEditing,
Background = TextFieldBackground,
LeftView = new UIView (new RectangleF (0, 0,8, 8)),
LeftViewMode = UITextFieldViewMode.Always,
ReturnKeyType = UIReturnKeyType.Next,
ShouldReturn = delegate {
lastName.BecomeFirstResponder ();
return true;
}
};
// Like this created 9 textfields and one submit button. added to ScrollView
Frame TextField.
firstName.Frame = new RectangleF(80, 20, 200, 41);
lastName.Frame = new RectangleF(80, 70, 200, 41);
middle.Frame = new RectangleF(80, 120, 200, 41);
email.Frame = new RectangleF(80, 127, 200, 41);
password.Frame = new RectangleF(80, 220, 200, 41);
conformPassword.Frame = new RectangleF(80, 270, 200, 41);
phoneNumber.Frame = new RectangleF(80, 320, 200, 41);
description.Frame = new RectangleF(80, 370, 200, 41);
other.Frame = new RectangleF(80, 420, 200, 41);
buttonSubmit.Frame = new RectangleF(80, 470, 420, 41);
Adding textfield to ScrollView
scroll_View.addSubView(firstName);
scroll_View.addSubView(lastName);
scroll_View.addSubView(middleName);
scroll_View.addSubView(email);
scroll_View.addSubView(Password);
scroll_View.addSubView(conformaPassword);
scroll_View.addSubView(phoneNumber);
scroll_View.addSubView(description);
scroll_View.addSubView(other);
scroll_View.addSubView(buttonSubmit);
Added Scroll View UIViewController View.
View.AddSubview (scroll_View);
When scrolling scrolling effect is not working. Xamarin IOS.
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
float h = 50.0f;
float w = 50.0f;
float padding = 10.0f;
int n = 25;
_scrollView = new UIScrollView {
Frame = new RectangleF (0, 0, View.Frame.Width, h + 2 * padding),
ContentSize = new SizeF ((w + padding) * n, h),
BackgroundColor = UIColor.DarkGray,
AutoresizingMask = UIViewAutoresizing.FlexibleWidth
};
for (int i=0; i<n; i++) {
var button = UIButton.FromType (UIButtonType.RoundedRect);
button.SetTitle (i.ToString (), UIControlState.Normal);
button.Frame = new RectangleF (padding * (i + 1) + (i * w), padding, w, h);
_scrollView.AddSubview (button);
_buttons.Add (button);
}
View.AddSubview (_scrollView);
}
Try to use "ContentSize " property in UIScrollView.
If you want to enable "Horizontal Scroll on UIScrollView" , need to increase the width of contentsize.
If you want to enable "Vertical Scroll on UIScrollView" , need to increase the height of contentsize.
UIScrollView *scrollView =[[UIScrollView
alloc]initWithFrame:CGRectMake(0, 40, 500, 300)];
scrollView.contentSize=CGSizeMake(1500, 200); //Horizontal scrolling
UIScrollView *scrollView =[[UIScrollView
alloc]initWithFrame:CGRectMake(0, 40, 500, 300)];
scrollView.contentSize=CGSizeMake(200, 1500); //vertical scrolling
Not a real answer yet it seems on this old question, but for future references: The problem in these cases is mostly that the ContentSize is equal to or smaller then the frame of the ScrollView. Therefore the ScrollView is unaware of the need to scroll.
In your case you should verify that the ContentSize of 320x720 is larger than the View.Frame you assign to the ScrollView Frame...
public class FirstTab : UIViewController
{
private UIView content1;
private UIView content2;
private UIView content3;
private UIView containerView;
private UIScrollView scrollView;
CoreGraphics.CGSize contentViewSize;
public FirstTab()
{
content1 = new UIView();
content2 = new UIView();
content3 = new UIView();
containerView = new UIView();
scrollView = new UIScrollView();
contentViewSize = new CoreGraphics.CGSize(View.Frame.Width, View.Frame.Height + 800);
}
public override void ViewWillLayoutSubviews()
{
base.ViewWillLayoutSubviews();
scrollView.ContentSize = contentViewSize;
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
content1.BackgroundColor = UIColor.Red;
content2.BackgroundColor = UIColor.Black;
content3.BackgroundColor = UIColor.Brown;
Constraint();
}
private void Constraint()
{
containerView.AddSubviews(content1, content2, content3);
containerView.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
containerView.AddConstraints(
content1.Width().EqualTo(300),
content1.Height().EqualTo(300),
content1.AtTopOf(containerView).Plus(20),
content1.WithSameCenterX(containerView),
content2.Width().EqualTo(300),
content2.Height().EqualTo(300),
content2.Below(content1).Plus(20),
content2.WithSameCenterX(containerView),
content3.Width().EqualTo(300),
content3.Height().EqualTo(300),
content3.Below(content2).Plus(20),
content3.WithSameCenterX(containerView)
);
scrollView.AddSubviews(containerView);
scrollView.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
scrollView.AddConstraints(
containerView.WithSameHeight(scrollView).Plus(300),
containerView.WithSameWidth(scrollView)
);
View.AddSubviews(scrollView);
View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
View.AddConstraints(
scrollView.WithSameWidth(View),
scrollView.WithSameHeight(View).Plus(400)
);
}
}
UIScrollView will work when You put the ScrollView.ContentSize into ViewWillLayoutSubview() method.
It took me very long time to find this simple trick for a working UIScrollView. I have used Cirrious.FluentLayout for autolayout.
In this case u need better work with UITableView not UIScrollView.

Why am I not seeing my instanced blue boxes drawn in XNA?

What's wrong with my instancing below? I'm trying to draw multiple instances of a single box with vertex colors. The examples I adapted this code from used textures and a shader rather than vertex colors. So I suspect that I'm going wrong with VertexPositionColor or my use of BasicEffect. I don't need a texture so I tried to remove the shader. I should also mention this is part of a winforms application.
What I get out of this code is a big red X indicating something went terribly wrong.
What am I missing here? Obviously there's something I'm not understanding.
namespace Die
{
class DieRender
{
VertexDeclaration instanceVertexDeclaration;
VertexBuffer dieGeometryBuffer;
IndexBuffer dieIndexBuffer;
VertexBuffer instanceBuffer;
VertexBufferBinding[] bindings;
InstanceInfo[] instances;
int instanceCount = 3;
struct InstanceInfo
{
public Vector4 World;
};
public void Initialize(GraphicsDevice device) {
GenerateInstanceVertexDeclaration();
GenerateDieGeometry(device, Color.Blue);
GenerateInstanceInformation(device, instanceCount);
bindings = new VertexBufferBinding[2];
bindings[0] = new VertexBufferBinding(dieGeometryBuffer);
bindings[1] = new VertexBufferBinding(instanceBuffer, 0, 1);
}
private void GenerateInstanceVertexDeclaration() {
VertexElement[] instanceStreamElements = new VertexElement[1];
instanceStreamElements[0] =
new VertexElement(0, VertexElementFormat.Vector4,
VertexElementUsage.Position, 1);
instanceVertexDeclaration = new VertexDeclaration(instanceStreamElements);
}
public void GenerateDieGeometry(GraphicsDevice device, Color color) {
VertexPositionColor[] vertices = new VertexPositionColor[4];
int[] indices = new int[6];
vertices[0].Position = new Vector3(-1, 1, 0);
vertices[1].Position = new Vector3(1, 1, 0);
vertices[2].Position = new Vector3(-1, -1, 0);
vertices[3].Position = new Vector3(1, -1, 0);
for (int i = 0; i < vertices.Count(); i++)
vertices[i].Color = color;
dieGeometryBuffer = new VertexBuffer(device,VertexPositionColor.VertexDeclaration,
4, BufferUsage.WriteOnly);
dieGeometryBuffer.SetData(vertices);
indices[0] = 0; indices[1] = 1; indices[2] = 2;
indices[3] = 1; indices[4] = 3; indices[5] = 2;
dieIndexBuffer = new IndexBuffer(device, typeof(int), 6, BufferUsage.WriteOnly);
dieIndexBuffer.SetData(indices);
}
private void GenerateInstanceInformation(GraphicsDevice device, Int32 count) {
instances = new InstanceInfo[count];
Random rnd = new Random();
for (int i = 0; i < count; i++) {
instances[i].World = new Vector4(-rnd.Next(20),
-rnd.Next(20),
-rnd.Next(20), 0);
}
instanceBuffer = new VertexBuffer(device, instanceVertexDeclaration,
count, BufferUsage.WriteOnly);
instanceBuffer.SetData(instances);
}
public void Draw(Matrix world, Matrix view, Matrix projection, GraphicsDevice device) {
device.Clear(Color.White);
BasicEffect effect = new BasicEffect(device);
effect.EnableDefaultLighting();
effect.TextureEnabled = false;
effect.World = world;
effect.View = view;
effect.Projection = projection;
effect.VertexColorEnabled = true;
device.Indices = dieIndexBuffer;
device.SetVertexBuffers(bindings);
foreach (EffectPass pass in effect.CurrentTechnique.Passes) {
pass.Apply();
device.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0, 4, 0, 2, instanceCount);
}
}
}
}
Ah! I found it... struggled with this for days and found the problem just as soon as I posted the question.
After enabling the exceptions from the CLR I caught the exception and found this similar question: XNA: The current vertex declaration does not include all the elements required by the current vertex shader. Normal0 is missing
Sorry if I wasted anybody's time.
Now... on to the next bug.

ZedGraph filling areas

I am using the ZedGraph control and want to fill one side of the graph function with some color and other side with other color.
PointPairList list1 = new PointPairList();
list1.Add(0, 4);
list1.Add(4, 0);
LineItem myCurve = myPane.AddCurve("y(n)", list1, Color.Red, SymbolType.Diamond);
//This filling bottom side.
myCurve.Line.Fill = new Fill(Color.White, Color.FromArgb(113, 255, 0, 0), 90F);
//How to fill the top side?
I'm not very clear on what you're asking - but hopefully the below will help. You said in comments
Can I fill some polygon area in Zedgraph?
So here's how...
var zed = new ZedGraph.ZedGraphControl { Dock = System.Windows.Forms.DockStyle.Fill };
var poly = new ZedGraph.PolyObj
{
Points = new[]
{
new ZedGraph.PointD(0, 0),
new ZedGraph.PointD(0.5, 1),
new ZedGraph.PointD(1, 0.5),
new ZedGraph.PointD(0, 0)
},
Fill = new ZedGraph.Fill(Color.Blue),
ZOrder = ZedGraph.ZOrder.E_BehindCurves
};
var poly1 = new ZedGraph.PolyObj
{
Points = new[]
{
new ZedGraph.PointD(1, 0),
new ZedGraph.PointD(0.25, 1),
new ZedGraph.PointD(0.5, 0),
new ZedGraph.PointD(1, 0)
},
Fill = new ZedGraph.Fill(Color.Red),
ZOrder = ZedGraph.ZOrder.E_BehindCurves
};
zed.GraphPane.AddCurve("Line", new[] { 0.0, 1.0 }, new[] { 0.0, 1.0 }, Color.Green);
zed.GraphPane.GraphObjList.Add(poly1);
zed.GraphPane.GraphObjList.Add(poly);
Results in
Hopefully this will point you in the right direction!
(Code in VB as requested via http://converter.telerik.com/ - no guarentee of the VB code working or even compiling!)

Categories

Resources