Jump to content

  • Log In with Google      Sign In   
  • Create Account

Awesome job so far everyone! Please give us your feedback on how our article efforts are going. We still need more finished articles for our May contest theme: Remake the Classics

yahastu

Member Since 25 Apr 2007
Offline Last Active Dec 29 2012 04:29 PM
-----

Topics I've Started

Avoiding address already in use

25 August 2012 - 04:45 PM

I wrote my server in C++ and put it on am amazon ec2-micro instance, listening for connections on port 1234. Tested it over period of weeks with no issues. I left it running indefinitely for several months and after some period of time (unknown) discovered it was no longer running. I logged in and tried to restart and got the "address already in use" error when attempting to bind the listensocket to port 1234. Note that SO_REUSEADDR was already set. Over a period of several days I continued to try and it has never been released. I suppose this amazon instance is set with TIME_WAIT=infinity so it will wait until server reboots, but I am afraid to reboot it due to posts like this: http://blog.9minutes...ot-t1micro-ec2/

I have discovered that whenever I kill the server process when it is currently connected to a client, this error will occur when I try to restart the server..so I need to change the port that it waits on to get it back up. But thats not viable solution, because clients need to hardcode the port to connect to. What do I do?

bool resume_listening()
  {
   std::cout << "Listening for new connections..\n";
   if ( ::listen( listenSocket, SOMAXCONN ) == SOCKET_ERROR )
   {
	perror("listen listenSocket");
	std::cout << "Error listening on socket\n";
	closesocket(listenSocket);
	return false;
   }
   return true;
  }
  bool create_listen_socket(int port)
  {
   std::cout << "Creating listener socket..\n";
   //create listen socket
   listenSocket = socket( AF_INET, SOCK_STREAM, 0 );
   if (listenSocket == INVALID_SOCKET) {
	perror("create listenSocket");
	std::cout << "Unable to create listenSocket\n";
	return false;
   }
   //----------------------
   // The sockaddr_in structure specifies the address family,
   // IP address, and port of the client to be connected to.
   struct sockaddr_in service;
   service.sin_family = AF_INET;
   service.sin_addr.s_addr = INADDR_ANY;
   service.sin_port = htons(port);
   // Enable address reuse
   //discussion: http://hea-www.harvard.edu/~fine/Tech/addrinuse.html
   int on = 1;
   setsockopt( listenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on) );
   //setup
   if ( bind(listenSocket, (SOCKADDR*)&service, sizeof(service) ) == SOCKET_ERROR )
   {
	perror("bind listenSocket");
	std::cout << "Unable to bind listenSocket\n";
	closesocket(listenSocket);
	return false;
   }
   return resume_listening();
  }

Geometry triangle problem

10 March 2012 - 07:24 PM

Imagine a camera orbiting an spherical object.  For a given orbit rotation, I'm trying to find out what the maximum change in the observed image angle of any point on the surface of the spherical object would be.  I've reduced the problem to the diagram shown below.

The object is centered at A.  B is the original camera location and D is the rotated camera location after orbiting.  C is the point on the surface of the object.  The original observed angle is ABC = atan( r/d).  However, I can't figure out how to calculate Theta2 = angle ADC.

Intersecting two angular ranges

20 October 2011 - 05:34 PM

Suppose that an "angular range" is specified by a starting and ending angle, proceeding clockwise.

The first angular range is (a,b) and the second is (c,d).  If both angular ranges span more than 180 degrees then it is possible that there are two intersection ranges.  However if they do not EACH span more than 180 degrees, then the intersection can be represented as a single angular range denoted by (e,f).  What is it?

In all cases, it is clear that e = a or c, and f = b or d.  

A few examples to begin with:

intersection of (a=45, b=10) with (c=350, d=30) is (e=350, f=10)
intersection of (a=45, b=10) with (c=270, d=300) is (e=270, f=300)
intersection of (a=45, b=95) with (c=55, d=80) is (e=55, f=80)

Progress:
--------

After much mucking about looking for a simple analytical solution that doesn't seem to exist, I realized that if you  sort all four angles (a,b,c,d) radially, then  find the index "i" such that the angle between "i" and "i-1" (using  modular indices) does not belong to either of the input angular ranges, then the intersection should be given by angles at indices "i+1" and "i+2".

Finding this index requires checking whether an angle belongs within a given angular range, and that requires a more mathematical definition of the set of angles in an angular range.  
My first thought was that an angular range could be defined by the cross product.  

That is, the range (a,b) could be written as the set  

{ p \in (0,2pi) | cross(vec(a),vec(p)) > 0 && cross(vec(p), vec(b)) > 0 }

where vec(a) is the 2D cartesian vector represented by the angle 'a', and cross is the 2D analog of the cross product (ie, the z-component of the 3D cross product).

However, then I realized that this definition only works for angular ranges spanning less than 180 degrees.  I'm having difficulty coming up with a simple mathematical definition that can be used to test whether a point is inside of an arbitrary angular range which might span more than 180 degrees.

Also, if anyone can think of a simpler overall approach, I'd be happy to hear it.

slimdx control inside winform

03 September 2011 - 01:51 PM

I have searched but haven't been able to find any actual code examples showing how to use slimdx on a control within a windows form.

I created a simple panel control and passed the handle to slimdx.

Then I tried to adapt the slimdx tutorial code for triangle rendering onto the control by doing the following:

a) put all the global variables needed for rendering onto the main winform class
b) put all the setup code inside the winform constructor after InitializeComponent
c) made a destructor for the winform and put all the directx cleanup code there
d) made a RenderFrame() function and hooked it up with MessagePump.Run(this, RenderFrame) in the end of the winform constructor.

Problems I'm having:
1) The triangle is not visible, although the back buffer is cleared to the clear color
2) When the application exits, it throws some crash exception
3) If I click the minimize button on the winform, the computer immediately freezes and must be re manually rebooted

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;

using SlimDX;
using SlimDX.D3DCompiler;
using SlimDX.Direct3D11;
using SlimDX.DXGI;
using SlimDX.Windows;
using Device = SlimDX.Direct3D11.Device;
using Resource = SlimDX.Direct3D11.Resource;

namespace MyNamespace
{
	public partial class frmMain : Form
	{
    	Device device;
    	SwapChain swapChain;
    	DeviceContext context;
    	Viewport viewport;
    	RenderTargetView renderTarget;

    	ShaderSignature inputSignature;
    	VertexShader vertexShader;
    	PixelShader pixelShader;
    	DataStream vertices;
    	SlimDX.Direct3D11.Buffer vertexBuffer;
    	InputLayout layout;

    	public frmMain()
    	{
        	InitializeComponent();

         	//this should make slimdx render onto "gPanel" control

        	var description = new SwapChainDescription()
        	{
            	BufferCount = 1,
            	Usage = Usage.RenderTargetOutput,
            	OutputHandle = gPanel.Handle,
            	IsWindowed = true,
            	ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
            	SampleDescription = new SampleDescription(1, 0),
            	Flags = SwapChainFlags.AllowModeSwitch,
            	SwapEffect = SwapEffect.Discard
        	};

        	Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out device, out swapChain);

        	// create a view of our render target, which is the backbuffer of the swap chain we just created
        	using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0))
            	renderTarget = new RenderTargetView(device, resource);

        	// prevent DXGI handling of alt+enter, which doesn't work properly with Winforms
        	using (var factory = swapChain.GetParent<Factory>())
            	factory.SetWindowAssociation(gPanel.Handle, WindowAssociationFlags.IgnoreAltEnter);


        	// setting a viewport is required if you want to actually see anything
        	context = device.ImmediateContext;
        	viewport = new Viewport(0.0f, 0.0f, gPanel.ClientSize.Width, gPanel.ClientSize.Height);
        	context.OutputMerger.SetTargets(renderTarget);
        	context.Rasterizer.SetViewports(viewport);
        	
        	


        	// load and compile the vertex shader
        	using (var bytecode = ShaderBytecode.CompileFromFile("triangle.fx", "VShader", "vs_4_0", ShaderFlags.None, EffectFlags.None))
        	{
            	inputSignature = ShaderSignature.GetInputSignature(bytecode);
            	vertexShader = new VertexShader(device, bytecode);
        	}

        	// load and compile the pixel shader
        	using (var bytecode = ShaderBytecode.CompileFromFile("triangle.fx", "PShader", "ps_4_0", ShaderFlags.None, EffectFlags.None))
            	pixelShader = new PixelShader(device, bytecode);

        	// create test vertex data, making sure to rewind the stream afterward
        	vertices = new DataStream(12 * 3, true, true);
        	vertices.Write(new Vector3(0.0f, 0.5f, 0.5f));
        	vertices.Write(new Vector3(0.5f, -0.5f, 0.5f));
        	vertices.Write(new Vector3(-0.5f, -0.5f, 0.5f));
        	vertices.Position = 0;

        	// create the vertex layout and buffer
        	var elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0) };
        	layout = new InputLayout(device, inputSignature, elements);
        	vertexBuffer = new SlimDX.Direct3D11.Buffer(device, vertices, 12 * 3, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

        	// configure the Input Assembler portion of the pipeline with the vertex data
        	context.InputAssembler.InputLayout = layout;
        	context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
        	context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 12, 0));

        	// set the shaders
        	context.VertexShader.Set(vertexShader);
        	context.PixelShader.Set(pixelShader);

        	MessagePump.Run(this, RenderFrame);
    	}

    	~frmMain()
    	{

        	// clean up all resources
        	// anything we missed will show up in the debug output
        	vertices.Close();
        	vertexBuffer.Dispose();
        	layout.Dispose();
        	inputSignature.Dispose();
        	vertexShader.Dispose();
        	pixelShader.Dispose();
        	renderTarget.Dispose();
        	swapChain.Dispose();
        	device.Dispose();
    	}

    	private void RenderFrame()
    	{
        	// clear the render target to a soothing blue
        	context.ClearRenderTargetView(renderTarget, new Color4(0.5f, 0.5f, 1.0f));

        	context.Draw(3, 0);
        	
        	swapChain.Present(0, PresentFlags.None);
    	}
}


PARTNERS