Search Results

Search found 80 results on 4 pages for 'theta'.

Page 2/4 | < Previous Page | 1 2 3 4  | Next Page >

  • correcting fisheye distortion programmatically

    - by Will
    I have some points that describe positions in a picture taken with a fisheye lens. I've found this description of how to generate a fisheye effect, but not how to reverse it. How do you calculate the radial distance from the centre to go from fisheye to rectilinear? My function stub looks like this: Point correct_fisheye(const Point& p,const Size& img) { // to polar const Point centre = {img.width/2,img.height/2}; const Point rel = {p.x-centre.x,p.y-centre.y}; const double theta = atan2(rel.y,rel.x); double R = sqrt((rel.x*rel.x)+(rel.y*rel.y)); // fisheye undistortion in here please //... change R ... // back to rectangular const Point ret = Point(centre.x+R*cos(theta),centre.y+R*sin(theta)); fprintf(stderr,"(%d,%d) in (%d,%d) = %f,%f = (%d,%d)\n",p.x,p.y,img.width,img.height,theta,R,ret.x,ret.y); return ret; } Alternatively, I could somehow convert the image from fisheye to rectilinear before finding the points, but I'm completely befuddled by the OpenCV documentation. Is there a straightforward way to do it in OpenCV, and does it perform well enough to do it to a live video feed?

    Read the article

  • How can I work around the fact that in C++, sin(M_PI) is not 0?

    - by Adam Doyle
    In C++, const double Pi = 3.14159265; cout << sin(Pi); // displays: 3.58979e-009 it SHOULD display the number zero I understand this is because Pi is being approximated, but is there any way I can have a value of Pi hardcoded into my program that will return 0 for sin(Pi)? (a different constant maybe?) In case you're wondering what I'm trying to do: I'm converting polar to rectangular, and while there are some printf() tricks I can do to print it as "0.00", it still doesn't consistently return decent values (in some cases I get "-0.00") The lines that require sin and cosine are: x = r*sin(theta); y = r*cos(theta); BTW: My Rectangular - Polar is working fine... it's just the Polar - Rectangular Thanks! edit: I'm looking for a workaround so that I can print sin(some multiple of Pi) as a nice round number to the console (ideally without a thousand if-statements) edit: In case anyone's curious, this was what I landed on: double sin2(double theta) // in degrees { double s = sin(toRadians(theta)); if (fabs(s - (int)s) < 0.000001) { return floor(s + 0.5); } return s; } where toRadians() is a macro that converts to radians

    Read the article

  • Object disapear/don't scale in the Z-AXIS of OPENGL.

    - by user315684
    This code is susposed to have a QUAD orbit around a center point in basically a circle. The problem is while it does the X rotation fine it disapears when it moves in Z axis and doesn't appear to change in size. It feel like it's rendering everything in Orthagraphic view or something. This is my first OpenGL project. OPENGL CODE START HERE glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode (GL_PROJECTION); glPushMatrix(); //glRotatef(theta, 0.0f, 0.0f, 1.0f); glScalef(0.75f, 0.75f, 0.75f); glTranslatef(planeX, -0.0f, 0.0f); glBegin(GL_QUADS); glColor3f(1.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, planeZ); glColor3f(0.0f, 1.0f, 0.0f); glVertex3f(0.0f, 1.0f, planeZ); glColor3f(0.0f, 0.0f, 1.0f); glVertex3f(1.0f, 1.0f, planeZ); glColor3f(0.0f, 0.0f, 1.0f); glVertex3f(1.0f, 0.0f, planeZ); glEnd(); glPopMatrix(); SwapBuffers(hDC); theta += 1.0f; planeX = (sin(0.0314159265f*theta)); planeZ = (cos(0.0314159265f*theta)); Sleep (1); ENDS HERE

    Read the article

  • DisplayObject.rotation not matching trig functions

    - by futuraprime
    I'm trying to label an animated pie chart, and I've been having a great deal of trouble getting rotated objects to line up with trigonometrically-positioned objects. So, for example, if I have a pie piece that's middle is angle theta and has been rotated n degrees in a tween, and then I try to position a label with code like this: label.x = center.x + Math.cos((theta + n)/180 * Math.PI) * radius; label.y = center.y + Math.sin((theta + n)/180 * Math.PI) * radius; the label is often not aligned with the center of the pie slice. Since I am also zooming in to the pie chart a great deal, the error becomes significant enough that it occasionally causes the label to miss the pie slice altogether. The error seems relatively unpredictable, and it looks a great deal like a rounding error, but I don't see any obvious rounding going on (the trig functions evaluate to ten or so decimal places, which should be more than enough here). How can I get these labels to position correctly?

    Read the article

  • How do I use texture-mapping in a simple ray tracer?

    - by fastrack20
    I am attempting to add features to a ray tracer in C++. Namely, I am trying to add texture mapping to the spheres. For simplicity, I am using an array to store the texture data. I obtained the texture data by using a hex editor and copying the correct byte values into an array in my code. This was just for my testing purposes. When the values of this array correspond to an image that is simply red, it appears to work close to what is expected except there is no shading. The bottom right of the image shows what a correct sphere should look like. This sphere's colour using one set colour, not a texture map. Another problem is that when the texture map is of something other than just one colour pixels, it turns white. My test image is a picture of water, and when it maps, it shows only one ring of bluish pixels surrounding the white colour. When this is done, it simply appears as this: Here are a few code snippets: Color getColor(const Object *object,const Ray *ray, float *t) { if (object->materialType == TEXTDIF || object->materialType == TEXTMATTE) { float distance = *t; Point pnt = ray->origin + ray->direction * distance; Point oc = object->center; Vector ve = Point(oc.x,oc.y,oc.z+1) - oc; Normalize(&ve); Vector vn = Point(oc.x,oc.y+1,oc.z) - oc; Normalize(&vn); Vector vp = pnt - oc; Normalize(&vp); double phi = acos(-vn.dot(vp)); float v = phi / M_PI; float u; float num1 = (float)acos(vp.dot(ve)); float num = (num1 /(float) sin(phi)); float theta = num /(float) (2 * M_PI); if (theta < 0 || theta == NAN) {theta = 0;} if (vn.cross(ve).dot(vp) > 0) { u = theta; } else { u = 1 - theta; } int x = (u * IMAGE_WIDTH) -1; int y = (v * IMAGE_WIDTH) -1; int p = (y * IMAGE_WIDTH + x)*3; return Color(TEXT_DATA[p+2],TEXT_DATA[p+1],TEXT_DATA[p]); } else { return object->color; } }; I call the colour code here in Trace: if (object->materialType == MATTE) return getColor(object, ray, &t); Ray shadowRay; int isInShadow = 0; shadowRay.origin.x = pHit.x + nHit.x * bias; shadowRay.origin.y = pHit.y + nHit.y * bias; shadowRay.origin.z = pHit.z + nHit.z * bias; shadowRay.direction = light->object->center - pHit; float len = shadowRay.direction.length(); Normalize(&shadowRay.direction); float LdotN = shadowRay.direction.dot(nHit); if (LdotN < 0) return 0; Color lightColor = light->object->color; for (int k = 0; k < numObjects; k++) { if (Intersect(objects[k], &shadowRay, &t) && !objects[k]->isLight) { if (objects[k]->materialType == GLASS) lightColor *= getColor(objects[k], &shadowRay, &t); // attenuate light color by glass color else isInShadow = 1; break; } } lightColor *= 1.f/(len*len); return (isInShadow) ? 0 : getColor(object, &shadowRay, &t) * lightColor * LdotN; } I left out the rest of the code as to not bog down the post, but it can be seen here. Any help is greatly appreciated. The only portion not included in the code, is where I define the texture data, which as I said, is simply taken straight from a bitmap file of the above image. Thanks.

    Read the article

  • Best Upper Bound & Best Lower Bound of an Algorithm

    - by Nayefc
    I am studying for a final exam and I came past a question I had on an earlier test. The questions asks us to find the minimum value in an unsorted array of integers. We must provide the best upper bound and the best lower bound that you can for the problem in the worst case. First, in such an example, the upper and lower bound are the same (hence, we can talk in terms of Big-Theta). In the worst case, we would have to go through the whole list as the minimum value would be at the end of the list. Therefore, the answer is Big-Theta(n). Is this a correct & good explanation?

    Read the article

  • Render 2 images that uses different shaders

    - by Code Vader
    Based on the giawa/nehe tutorials, how can I render 2 images with different shaders. I'm pretty new to OpenGl and shaders so I'm not completely sure whats happening in my code, but I think the shaders that is called last overwrites the first one. private static void OnRenderFrame() { // calculate how much time has elapsed since the last frame watch.Stop(); float deltaTime = (float)watch.ElapsedTicks / System.Diagnostics.Stopwatch.Frequency; watch.Restart(); // use the deltaTime to adjust the angle of the cube angle += deltaTime; // set up the OpenGL viewport and clear both the color and depth bits Gl.Viewport(0, 0, width, height); Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); // use our shader program and bind the crate texture Gl.UseProgram(program); //<<<<<<<<<<<< TOP PYRAMID // set the transformation of the top_pyramid program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube)); program["enable_lighting"].SetValue(lighting); // bind the vertex positions, UV coordinates and element array Gl.BindBufferToShaderAttribute(top_pyramid, program, "vertexPosition"); Gl.BindBufferToShaderAttribute(top_pyramidNormals, program, "vertexNormal"); Gl.BindBufferToShaderAttribute(top_pyramidUV, program, "vertexUV"); Gl.BindBuffer(top_pyramidTrianlges); // draw the textured top_pyramid Gl.DrawElements(BeginMode.Triangles, top_pyramidTrianlges.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); //<<<<<<<<<< CUBE // set the transformation of the cube program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube)); program["enable_lighting"].SetValue(lighting); // bind the vertex positions, UV coordinates and element array Gl.BindBufferToShaderAttribute(cube, program, "vertexPosition"); Gl.BindBufferToShaderAttribute(cubeNormals, program, "vertexNormal"); Gl.BindBufferToShaderAttribute(cubeUV, program, "vertexUV"); Gl.BindBuffer(cubeQuads); // draw the textured cube Gl.DrawElements(BeginMode.Quads, cubeQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); //<<<<<<<<<<<< BOTTOM PYRAMID // set the transformation of the bottom_pyramid program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube)); program["enable_lighting"].SetValue(lighting); // bind the vertex positions, UV coordinates and element array Gl.BindBufferToShaderAttribute(bottom_pyramid, program, "vertexPosition"); Gl.BindBufferToShaderAttribute(bottom_pyramidNormals, program, "vertexNormal"); Gl.BindBufferToShaderAttribute(bottom_pyramidUV, program, "vertexUV"); Gl.BindBuffer(bottom_pyramidTrianlges); // draw the textured bottom_pyramid Gl.DrawElements(BeginMode.Triangles, bottom_pyramidTrianlges.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); //<<<<<<<<<<<<< STAR Gl.Disable(EnableCap.DepthTest); Gl.Enable(EnableCap.Blend); Gl.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One); Gl.BindTexture(starTexture); //calculate the camera position using some fancy polar co-ordinates Vector3 position = 20 * new Vector3(Math.Cos(phi) * Math.Sin(theta), Math.Cos(theta), Math.Sin(phi) * Math.Sin(theta)); Vector3 upVector = ((theta % (Math.PI * 2)) > Math.PI) ? Vector3.Up : Vector3.Down; program_2["view_matrix"].SetValue(Matrix4.LookAt(position, Vector3.Zero, upVector)); // make sure the shader program and texture are being used Gl.UseProgram(program_2); // loop through the stars, drawing each one for (int i = 0; i < stars.Count; i++) { // set the position and color of this star program_2["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(stars[i].dist, 0, 0)) * Matrix4.CreateRotationZ(stars[i].angle)); program_2["color"].SetValue(stars[i].color); Gl.BindBufferToShaderAttribute(star, program_2, "vertexPosition"); Gl.BindBufferToShaderAttribute(starUV, program_2, "vertexUV"); Gl.BindBuffer(starQuads); Gl.DrawElements(BeginMode.Quads, starQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); // update the position of the star stars[i].angle += (float)i / stars.Count * deltaTime * 2 * rotate_stars; stars[i].dist -= 0.2f * deltaTime * rotate_stars; // if we've reached the center then move this star outwards and give it a new color if (stars[i].dist < 0f) { stars[i].dist += 5f; stars[i].color = new Vector3(generator.NextDouble(), generator.NextDouble(), generator.NextDouble()); } } Glut.glutSwapBuffers(); } The same goes for the textures, whichever one I mention last gets applied to both object?

    Read the article

  • Recompiling an old fortran 2/4\66 program that was compiled for os\2 need it to run in dos

    - by Mike Hansen
    I am helping an old scientist with some problems and have 1 program that he found and modified about 20 yrs. ago, and runs fine as a 32 bit os\2 executable but i need it to run under dos! I am not a programmer but a good hardware & software man, so I'am pretty stupid about this problem, but here go's I have downloaded 6 different compilers watcom77,silverfrost ftn95,gfortran,2 versions of g77 and f80. Watcom says it is to old of program,find older compiler,silverfrost opens it,debugs, etc. but is changing all the subroutines from "real" to "complex" and vice-vesa,and the g77's seem to install perfectly (library links and etc.) but wont even compile the test.f programs.My problem is 1; to recompile "as is" or "upgrade" the code? PROGRAM xconvlv INTEGER N,N2,M PARAMETER (N=2048,N2=2048,M=128) INTEGER i,isign REAL data(n),respns(m),resp(n),ans(n2),t3(n),DUMMY OPEN(UNIT=1, FILE='C:\QKBAS20\FDATA1.DAT') DO 1 i=1,N READ(1,*) T3(i), data(i), DUMMY continue CLOSE(UNIT-1) do 12 i=1,N respns(i)=data(i) resp(i)=respns(i) continue isign=-1 call convlv(data,N,resp,M,isign,ans) OPEN(UNIT=1,FILE='C:\QKBAS20\FDATA9.DAT') DO 14 i=1,N WRITE(1,*) T3(i), ans(i) continue END SUBROUTINE CONVLV(data,n,respns,m,isign,ans) INTEGER isign,m,n,NMAX REAL data(n),respns(n) COMPLEX ans(n) PARAMETER (NMAX=4096) * uses realft, twofft INTEGER i,no2 COMPLEX fft (NMAX) do 11 i=1, (m-1)/2 respns(n+1-i)=respns(m+1-i) continue do 12 i=(m+3)/2,n-(m-1)/2 respns(i)=0.0 continue call twofft (data,respns,fft,ans,n) no2=n/2 do 13 i=1,no2+1 if (isign.eq.1) then ans(i)=fft(i)*ans(i)/no2 else if (isign.eq.-1) then if (abs(ans(i)) .eq.0.0) pause ans(i)=fft(i)/ans(i)/no2 else pause 'no meaning for isign in convlv' endif continue ans(1)=cmplx(real (ans(1)),real (ans(no2+1))) call realft(ans,n,-1) return END SUBROUTINE realft(data,n,isign) INTEGER isign,n REAL data(n) * uses four1 INTEGER i,i1,i2,i3,i4,n2p3 REAL c1,c2,hli,hir,h2i,h2r,wis,wrs DOUBLE PRECISION theta,wi,wpi,wpr,wr,wtemp theta=3.141592653589793d0/dble(n/2) cl=0.5 if (isign.eq.1) then c2=-0.5 call four1(data,n/2,+1) else c2=0.5 theta=-theta endif (etc.,etc., etc.) SUBROUTINE twofft(data,data2,fft1,fft2,n) INTEGER n REAL data1(n,data2(n) COMPLEX fft1(n), fft2(n) * uses four1 INTEGER j,n2 COMPLEX h1,h2,c1,c2 c1=cmplx(0.5,0.0) c2=cmplx(0.0,-0.5) do 11 j=1,n fft1(j)=cmplx(data1(j),data2(j) continue call four1 (fft1,n,1) fft2(1)=cmplx(aimag(fft1(1)),0.0) fft1(1)=cmplx(real(fft1(1)),0.0) n2=n+2 do 12 j=2,n/2+1 h1=c1*(fft1(j)+conjg(fft1(n2-j))) h2=c2*(fft1(j)-conjg(fft1(n2-j))) fft1(j)=h1 fft1(n2-j)=conjg(h1) fft2(j)=h2 fft2(n2-j)=conjg(h2) continue return END SUBROUTINE four1(data,nn,isign) INTEGER isign,nn REAL data(2*nn) INTEGER i,istep,j,m,mmax,n REAL tempi,tempr DOUBLE PRECISION theta, wi,wpi,wpr,wr,wtemp n=2*nn j=1 do 11 i=1,n,2 if(j.gt.i)then tempr=data(j) tempi=data(j+1) (etc.,etc.,etc.,) continue mmax=istep goto 2 endif return END There are 4 subroutines with this that are about 3 pages of code and whould be much easier to e-mail to someone if their able to help me with this.My e-mail is [email protected] , or if someone could tell me where to get a "working" compiler that could recompile this? THANK-YOU, THANK-YOU,and THANK-YOU for any help with this! The errors Iam getting are; 1.In a call to CONVLV from another procedure,the first argument was of a type REAL(kind=1), it is now a COMPLEX(kind=1) 2.In a call to REALFT from another procedure, ... COMPLEX(kind=1) it is now a REAL(kind=1) 3.In a call to TWOFFT from...COMPLEX(kind-1) it is now a REAL(kind=1) 4.In a previous call to FOUR1, the first argument was of a type REAL(kind=1) it is now a COMPLEX(kind=1).

    Read the article

  • Using the masters method

    - by Roarke
    On my midterm I had the problem: t(n) = 8T(n/2) +n^3 and I am supposed to find its big theta notation using either the masters or alternative method. So what i did was a = 8, b = 2 k = 3 log8 (base 2) = 3 = k therefore, T(n) is big theta n^3. I got 1/3 points so i must be wrong. What did I do wrong?

    Read the article

  • Help understanding some OpenGL stuff

    - by shinjuo
    I am working with some code to create a triangle that moves with arrow keys. I want to create a second object that moves independently. This is where I am having trouble, I have created the second actor, but cannot get it to move. There is too much code to post it all so I will just post a little and see if anyone can help at all. ogl_test.cpp #include "platform.h" #include "srt/scheduler.h" #include "model.h" #include "controller.h" #include "model_module.h" #include "graphics_module.h" class blob : public actor { public: blob(float x, float y) : actor(math::vector2f(x, y)) { } void render() { transform(); glBegin(GL_TRIANGLES); glVertex3f(0.25f, 0.0f, -5.0f); glVertex3f(-.5f, 0.25f, -5.0f); glVertex3f(-.5f, -0.25f, -5.0f); glEnd(); end_transform(); } void update(controller& c, float dt) { if (c.left_key) { rho += pi / 9.0f * dt; c.left_key = false; } if (c.right_key) { rho -= pi / 9.0f * dt; c.right_key = false; } if (c.up_key) { v += .1f * dt; c.up_key = false; } if (c.down_key) { v -= .1f * dt; if (v < 0.0) { v = 0.0; } c.down_key = false; } actor::update(c, dt); } }; class enemyOne : public actor { public: enemyOne(float x, float y) : actor(math::vector2f(x, y)) { } void render() { transform(); glBegin(GL_TRIANGLES); glVertex3f(0.25f, 0.0f, -5.0f); glVertex3f(-.5f, 0.25f, -5.0f); glVertex3f(-.5f, -0.25f, -5.0f); glEnd(); end_transform(); } void update(controller& c, float dt) { if (c.left_key) { rho += pi / 9.0f * dt; c.left_key = false; } if (c.right_key) { rho -= pi / 9.0f * dt; c.right_key = false; } if (c.up_key) { v += .1f * dt; c.up_key = false; } if (c.down_key) { v -= .1f * dt; if (v < 0.0) { v = 0.0; } c.down_key = false; } actor::update(c, dt); } }; int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, char* lpCmdLine, int nCmdShow ) { model m; controller control(m); srt::scheduler scheduler(33); srt::frame* model_frame = new srt::frame(scheduler.timer(), 0, 1, 2); srt::frame* render_frame = new srt::frame(scheduler.timer(), 1, 1, 2); model_frame->add(new model_module(m, control)); render_frame->add(new graphics_module(m)); scheduler.add(model_frame); scheduler.add(render_frame); blob* prime = new blob(0.0f, 0.0f); m.add(prime); m.set_prime(prime); enemyOne* primeTwo = new enemyOne(2.0f, 0.0f); m.add(primeTwo); m.set_prime(primeTwo); scheduler.start(); control.start(); return 0; } model.h #include <vector> #include "vec.h" const double pi = 3.14159265358979323; class controller; using math::vector2f; class actor { public: vector2f P; float theta; float v; float rho; actor(const vector2f& init_location) : P(init_location), rho(0.0), v(0.0), theta(0.0) { } virtual void render() = 0; virtual void update(controller&, float dt) { float v1 = v; float theta1 = theta + rho * dt; vector2f P1 = P + v1 * vector2f(cos(theta1), sin(theta1)); if (P1.x < -4.5f || P1.x > 4.5f) { P1.x = -P1.x; } if (P1.y < -4.5f || P1.y > 4.5f) { P1.y = -P1.y; } v = v1; theta = theta1; P = P1; } protected: void transform() { glPushMatrix(); glTranslatef(P.x, P.y, 0.0f); glRotatef(theta * 180.0f / pi, 0.0f, 0.0f, 1.0f); //Rotate about the z-axis } void end_transform() { glPopMatrix(); } }; class model { private: typedef std::vector<actor*> actor_vector; actor_vector actors; public: actor* _prime; model() { } void add(actor* a) { actors.push_back(a); } void set_prime(actor* a) { _prime = a; } void update(controller& control, float dt) { for (actor_vector::iterator i = actors.begin(); i != actors.end(); ++i) { (*i)->update(control, dt); } } void render() { for (actor_vector::iterator i = actors.begin(); i != actors.end(); ++i) { (*i)->render(); } } };

    Read the article

  • Draw multiple circles in Google Maps

    - by snorpey
    Hi. I want to draw multiple circles on a map, using the Google Maps API anj jQuery. The following code works as long as the line with drawMapCircle() is commented out (The markers are positioned correctly). What's wrong with my code? $.getJSON( "ajax/show.php", function(data) { $.each(data.points, function(i, point) { map.addOverlay(new GMarker(new GLatLng(point.lat, point.lng))); drawMapCircle(point.lat, point.lng, 0.01, '#0066ff', 2, 0.8, '#0cf', 0.1); }); } ); function drawMapCircle(lat, lng, radius, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity) { var d2r = Math.PI / 180; var r2d = 180 / Math.PI; var Clat = radius * 0.014483; // statute miles into degrees latitude conversion var Clng = Clat/Math.cos(lat * d2r); var Cpoints = []; for (var i = 0; i < 33; i++) { var theta = Math.PI * (i / 16); Cy = lat + (Clat * Math.sin(theta)); Cx = lng + (Clng * Math.cos(theta)); var P = new GLatLng(Cy, Cx); Cpoints.push(P); } var polygon = new GPolygon(Cpoints, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity); map.addOverlay(polygon); }

    Read the article

  • OpenGL circle rotation

    - by user350632
    I'm using following code to draw my circles: double theta = 2 * 3.1415926 / num_segments; double c = Math.Cos(theta);//precalculate the sine and cosine double s = Math.Sin(theta); double t; double x = r;//we start at angle = 0 double y = 0; GL.glBegin(GL.GL_LINE_LOOP); for(int ii = 0; ii < num_segments; ii++) { float first = (float)(x * scaleX + cx) / xyFactor; float second = (float)(y * scaleY + cy) / xyFactor; GL.glVertex2f(first, second); // output Vertex //apply the rotation matrix t = x; x = c * x - s * y; y = s * t + c * y; } GL.glEnd(); The problem is that when scaleX is different from scaleY then circles are transformed in the right way except for the rotation. In my code sequence looks like this: circle.Scale(tmp_p.scaleX, tmp_p.scaleY); circle.Rotate(tmp_p.rotateAngle); My question is what other calculations should i perform for circle to rotate properly when scaleX and scaleY are not equal?

    Read the article

  • Rotating a NetBeans Visual Library Widget

    - by Geertjan
    Trying to create a widget which, when clicked, rotates slightly further on each subsequent click: Above, the bird where the mouse is visible has been clicked a few times and so has rotated a bit further on each click. The code isn't quite right yet and I'm hoping someone will take this code, try it out, and help with a nice solution! public class BirdScene extends Scene {     public BirdScene() {         addChild(new LayerWidget(this));         getActions().addAction(ActionFactory.createAcceptAction(new AcceptProvider() {             public ConnectorState isAcceptable(Widget widget, Point point, Transferable transferable) {                 Image dragImage = getImageFromTransferable(transferable);                 if (dragImage != null) {                     JComponent view = getView();                     Graphics2D g2 = (Graphics2D) view.getGraphics();                     Rectangle visRect = view.getVisibleRect();                     view.paintImmediately(visRect.x, visRect.y, visRect.width, visRect.height);                     g2.drawImage(dragImage,                             AffineTransform.getTranslateInstance(point.getLocation().getX(),                             point.getLocation().getY()),                             null);                     return ConnectorState.ACCEPT;                 } else {                     return ConnectorState.REJECT;                 }             }             public void accept(Widget widget, final Point point, Transferable transferable) {                 addChild(new BirdWidget(getScene(), getImageFromTransferable(transferable), point));             }         }));     }     private Image getImageFromTransferable(Transferable transferable) {         Object o = null;         try {             o = transferable.getTransferData(DataFlavor.imageFlavor);         } catch (IOException ex) {         } catch (UnsupportedFlavorException ex) {         }         return o instanceof Image ? (Image) o : null;     }     private class BirdWidget extends IconNodeWidget {         private int theta = 0;         public BirdWidget(Scene scene, Image imageFromTransferable, Point point) {             super(scene);             setImage(imageFromTransferable);             setPreferredLocation(point);             setCheckClipping(true);             getActions().addAction(ActionFactory.createMoveAction());             getActions().addAction(ActionFactory.createSelectAction(new SelectProvider() {                 public boolean isAimingAllowed(Widget widget, Point localLocation, boolean invertSelection) {                     return true;                 }                 public boolean isSelectionAllowed(Widget widget, Point localLocation, boolean invertSelection) {                     return true;                 }                 public void select(final Widget widget, Point localLocation, boolean invertSelection) {                     theta = (theta + 100) % 360;                     repaint();                     getScene().validate();                 }             }));         }         @Override         public void paintWidget() {             final Image image = getImageWidget().getImage();             Graphics2D g = getGraphics();             g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);             Rectangle bounds = getClientArea();             AffineTransform newXform = g.getTransform();             int xRot = image.getWidth(null) / 2;             int yRot = image.getWidth(null) / 2;             newXform.rotate(theta * Math.PI / 180, xRot, yRot);             g.setTransform(newXform);             g.drawImage(image, bounds.x, bounds.y, null);         }     } } The problem relates to refreshing the scene after the rotation. But it would help if someone would just take the code above, add it to their own application, try it out, see the problem for yourself, and develop it a bit further!

    Read the article

  • Why does my Opengl es android testbed app not render anything besides a red screen?

    - by nathan
    For some reason my code here (this is the entire thing) doesnt actually render anything besides a red screen.. can anyone tell me why? package com.ntu.way2fungames.earth.testbed; import java.nio.FloatBuffer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.app.Activity; import android.content.Context; import android.opengl.GLSurfaceView; import android.opengl.GLSurfaceView.Renderer; import android.os.Bundle; public class projectiles extends Activity { GLSurfaceView lGLView; Renderer lGLRenderer; float projectilesX[]= new float[5001]; float projectilesY[]= new float[5001]; float projectilesXa[]= new float[5001]; float projectilesYa[]= new float[5001]; float projectilesTheta[]= new float[5001]; float projectilesSpeed[]= new float[5001]; private static FloatBuffer drawBuffer; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SetupProjectiles(); Context mContext = this.getWindow().getContext(); lGLView= new MyView(mContext); lGLRenderer= new MyRenderer(); lGLView.setRenderer(lGLRenderer); setContentView(lGLView); } private void SetupProjectiles() { int i=0; for (i=5000;i>0;i=i-1){ projectilesX[i] = 240; projectilesY[i] = 427; float theta = (float) ((i/5000)*Math.PI*2); projectilesXa[i] = (float) Math.cos(theta); projectilesYa[i] = (float) Math.sin(theta); projectilesTheta[i]= theta; projectilesSpeed[i]= (float) (Math.random()+1); } } public class MyView extends GLSurfaceView{ public MyView(Context context) { super(context); // TODO Auto-generated constructor stub } } public class MyRenderer implements Renderer{ private float[] projectilecords = new float[] { .0f, .5f, 0, -.5f, 0f, 0, .5f, 0f, 0, 0, -5f, 0, }; @Override public void onDrawFrame(GL10 gl) { gl.glClear(GL10.GL_COLOR_BUFFER_BIT); gl.glMatrixMode(GL10.GL_MODELVIEW); //gl.glLoadIdentity(); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); for (int i=5000;i>4500;i=i-1){ //drawing section gl.glLoadIdentity(); gl.glColor4f(.9f, .9f,.9f,.9f); gl.glTranslatef(projectilesY[i], projectilesX[i],1); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, drawBuffer); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 12); //physics section projectilesX[i]=projectilesX[i]+projectilesXa[i]; projectilesY[i]=projectilesY[i]+projectilesYa[i]; } gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { if (height == 0) height = 1; // draw on the entire screen gl.glViewport(0, 0, width, height); // setup projection matrix gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glOrthof(0,width,height,0, -100, 100); } @Override public void onSurfaceCreated(GL10 gl, EGLConfig arg1) { gl.glShadeModel(GL10.GL_SMOOTH); gl.glClearColor(1f, .01f, .01f, 1f); gl.glClearDepthf(1.0f); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glDepthFunc(GL10.GL_LEQUAL); gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); drawBuffer = FloatBuffer.wrap(projectilecords); } } }

    Read the article

  • Win32 and Win64 programming in C sources?

    - by Nick Rosencrantz
    I'm learning OpenGL with C and that makes me include the windows.h file in my project. I'd like to look at some more specific windows functions and I wonder if you can cite some good sources for learning the basics of Win32 and Win64 programming in C (or C++). I use MS Visual C++ and I prefer to stick with C even though much of the Windows API seems to be C++. I'd like my program to be portable and using some platform-indepedent graphics library like OpenGL I could make my program portable with some slight changes for window management. Could you direct me with some pointers to books or www links where I can find more info? I've already studied the OpenGL red book and the C programming language, what I'm looking for is the platform-dependent stuff and how to handle that since I run both Linux and Windows where I find the development environment Visual Studio is pretty good but the debugger gdb is not available on windows so it's a trade off which environment i'll choose in the end - Linux with gcc or Windows with MSVC. Here is the program that draws a graphics primitive with some use of windows.h This program is also runnable on Linux without changing the code that actually draws the graphics primitive: #include <windows.h> #include <gl/gl.h> LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM); void EnableOpenGL(HWND hwnd, HDC*, HGLRC*); void DisableOpenGL(HWND, HDC, HGLRC); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wcex; HWND hwnd; HDC hDC; HGLRC hRC; MSG msg; BOOL bQuit = FALSE; float theta = 0.0f; /* register window class */ wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_OWNDC; wcex.lpfnWndProc = WindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wcex.lpszMenuName = NULL; wcex.lpszClassName = "GLSample"; wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);; if (!RegisterClassEx(&wcex)) return 0; /* create main window */ hwnd = CreateWindowEx(0, "GLSample", "OpenGL Sample", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 256, 256, NULL, NULL, hInstance, NULL); ShowWindow(hwnd, nCmdShow); /* enable OpenGL for the window */ EnableOpenGL(hwnd, &hDC, &hRC); /* program main loop */ while (!bQuit) { /* check for messages */ if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { /* handle or dispatch messages */ if (msg.message == WM_QUIT) { bQuit = TRUE; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } else { /* OpenGL animation code goes here */ glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); glPushMatrix(); glRotatef(theta, 0.0f, 0.0f, 1.0f); glBegin(GL_TRIANGLES); glColor3f(1.0f, 0.0f, 0.0f); glVertex2f(0.0f, 1.0f); glColor3f(0.0f, 1.0f, 0.0f); glVertex2f(0.87f, -0.5f); glColor3f(0.0f, 0.0f, 1.0f); glVertex2f(-0.87f, -0.5f); glEnd(); glPopMatrix(); SwapBuffers(hDC); theta += 1.0f; Sleep (1); } } /* shutdown OpenGL */ DisableOpenGL(hwnd, hDC, hRC); /* destroy the window explicitly */ DestroyWindow(hwnd); return msg.wParam; } LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CLOSE: PostQuitMessage(0); break; case WM_DESTROY: return 0; case WM_KEYDOWN: { switch (wParam) { case VK_ESCAPE: PostQuitMessage(0); break; } } break; default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0; } void EnableOpenGL(HWND hwnd, HDC* hDC, HGLRC* hRC) { PIXELFORMATDESCRIPTOR pfd; int iFormat; /* get the device context (DC) */ *hDC = GetDC(hwnd); /* set the pixel format for the DC */ ZeroMemory(&pfd, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 24; pfd.cDepthBits = 16; pfd.iLayerType = PFD_MAIN_PLANE; iFormat = ChoosePixelFormat(*hDC, &pfd); SetPixelFormat(*hDC, iFormat, &pfd); /* create and enable the render context (RC) */ *hRC = wglCreateContext(*hDC); wglMakeCurrent(*hDC, *hRC); } void DisableOpenGL (HWND hwnd, HDC hDC, HGLRC hRC) { wglMakeCurrent(NULL, NULL); wglDeleteContext(hRC); ReleaseDC(hwnd, hDC); }

    Read the article

  • Laplacian of Gaussian

    - by Don
    I am having trouble implementing a LoG kernel. I am trying to implement 9x9 kernal with theta = 1.4 as shown in this link http://homepages.inf.ed.ac.uk/rbf/HIPR2/log.htm. However, I am having difficulty with the formula itself.For whatever values I input into the formula, I don't get any of the values in a 9x9 LoG kernel with theta = 1. 4. If someone can provide an example of how they got one of the big values ie -40 or -23, or the code to implement it, It'd be greatly appreciated. Thank you

    Read the article

  • How can I work around the fact that in C++, sin(3.14159265) is not 0?

    - by Adam Doyle
    In C++, const double Pi = 3.14159265; cout << sin(Pi); // displays: 3.58979e-009 it SHOULD display the number zero I understand this is because Pi is being approximated, but is there any way I can have a value of Pi hardcoded into my program that will return 0 for sin(Pi)? (a different constant maybe?) In case you're wondering what I'm trying to do: I'm converting polar to rectangular, and while there are some printf() tricks I can do to print it as "0.00", it still doesn't consistently return decent values (in some cases I get "-0.00") The lines that require sin and cosine are: x = r*sin(theta); y = r*cos(theta); BTW: My Rectangular - Polar is working fine... it's just the Polar - Rectangular Thanks! edit: I'm looking for a workaround so that I can print sin(some multiple of Pi) as a nice round number to the console (ideally without a thousand if-statements)

    Read the article

  • recursion tree and binary tree cost calculation

    - by Tony
    Hi all, I've got the following recursion: T(n) = T(n/3) + T(2n/3) + O(n) The height of the tree would be log3/2 of 2. Now the recursion tree for this recurrence is not a complete binary tree. It has missing nodes lower down. This makes sense to me, however I don't understand how the following small omega notation relates to the cost of all leaves in the tree. "... the total cost of all leaves would then be Theta (n^log3/2 of 2) which, since log3/2 of 2 is a constant strictly greater then 1, is small omega(n lg n)." Can someone please help me understand how the Theta(n^log3/2 of 2) becomes small omega(n lg n)?

    Read the article

  • Collision point of 2 curves in a 3d-room

    - by Frank
    Hello, i am programming a small game for quite some time. We started coding a small FPS-Shooter inside of a project at school to get a bit experience using directX. I dont know why, but i couldnt stop the project and started programming at home aswell. At the moment i am trying to create some small AI. Of cause thats definatlly not easy, but thats my personal goal anyways. The topic could prolly fill multiple books hehe. I've got the walking part of my bots done so far. They walk along a scriped path. I am not working on the "aiming" of the bots. While programming that i hit on some math problem i couldnt solve yet. I hope of your input on this to help me get further. Concepts, ideas and everything else are highly appreciated. Problem: Calculate the position (D3DXVECTOR3) where the curve of the projectile (depends on gravity, speed), hit the curved of the enemys walking path (depends on speed). We assume that the enemy walks in a constant line. Known variables: float projectilSpeed = 2000 m/s //speed of the projectile per second float gravitation = 9.81 m/s^2 //of cause the gravity lol D3DXVECTOR3 targetPosition //position of the target stored in a vector (x,y,z) D3DXVECTOR3 projectilePosition //position of the projectile D3DXVECTOR3 targetSpeed //stores the change of the targets position in the last second Variabledefinition ProjectilePosition at time of collision = ProjectilePos_t TargetPosition at time of collision = TargetPos_t ProjectilePosition at time 0, now = ProjectilePos_0 TargetPosition at time 0, now = TargetPos_0 Time to impact = t Aim-angle = theta My try: Found a formular to calculate "drop" (Drop of the projectile based on the gravity) on Wikipedia: float drop = 0.5f * gravity * t * t The speed of the projectile has a horizontal and a vertical part.. Found a formular for that on wikipedia aswell: ProjectilVelocity.x = projectilSpeed * cos(theta) ProjectilVelocity.y = projectilSpeed * sin(theta) So i would assume this is true for the projectile curve: ProjectilePos_t.x = ProjectilePos_0.x + ProjectileSpeed * t ProjectilePos_t.y = ProjectilePos_0.y + ProjectileSpeed * t + 0.5f * gravity * t * t ProjectilePos_t.z = ProjectilePos_0.z + ProjectileSpeed * t The target walk with a constant speed, so we can determine his curve by this: TargetPos_t = TargetPos_0 + TargetSpeed * D3DXVECTOR3(t, t, t) Now i dont know how to continue. I have to solve it somehow to get a hold on the time to impact somehow. As a basic formular i could use: float time = distanz / projectileSpeed But that wouldnt be truly correct as it would assume a linear "Trajectory". We just find this behaivor when using a rocket. I hope i was able to explain the problem as much as possible. If there are questions left, feel free to ask me! Greets from germany, Frank

    Read the article

  • Communicate multiple times with a process without breaking the pipe?

    - by Manux
    Hello, it's not the first time I'm having this problem and its really bugging me. Whenever I open a pipe using the Python subprocess module, I can only communicate with it once, as the documentation specifies: Read data from stdout and stderr, until end-of-file is reached proc = sub.Popen("psql -h darwin -d main_db".split(),stdin=sub.PIPE,stdout=sub.PIPE) print proc.communicate("select a,b,result from experiment_1412;\n")[0] print proc.communicate("select theta,zeta,result from experiment_2099\n")[0] The problem here is that the second time, Python isn't happy. Indeed, he decided to close the file after the first communicate: Traceback (most recent call last): File "a.py", line 30, in <module> print proc.communicate("select theta,zeta,result from experiment_2099\n")[0] File "/usr/lib64/python2.5/subprocess.py", line 667, in communicate return self._communicate(input) File "/usr/lib64/python2.5/subprocess.py", line 1124, in _communicate self.stdin.flush() ValueError: I/O operation on closed file So... multiple communications aren't allowed? I hope not ;) Please enlighten me.

    Read the article

  • LWJGL Circle program create's an oval-like shape

    - by N1ghtk1n9
    I'm trying to draw a circle in LWJGL, but when I draw I try to draw it, it makes a shape that's more like an oval rather than a circle. Also, when I change my circleVertexCount 350+, the shape like flips out. I'm really not sure how the code works that creates the vertices(I have taken Geometry and I know the basic trig ratios). I haven't really found that good of tutorials on creating circles. Here's my code: public class Circles { // Setup variables private int WIDTH = 800; private int HEIGHT = 600; private String title = "Circle"; private float fXOffset; private int vbo = 0; private int vao = 0; int circleVertexCount = 300; float[] vertexData = new float[(circleVertexCount + 1) * 4]; public Circles() { setupOpenGL(); setupQuad(); while (!Display.isCloseRequested()) { loop(); adjustVertexData(); Display.update(); Display.sync(60); } Display.destroy(); } public void setupOpenGL() { try { Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT)); Display.setTitle(title); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); System.exit(-1); } glClearColor(0.0f, 0.0f, 0.0f, 0.0f); } public void setupQuad() { float r = 0.1f; float x; float y; float offSetX = 0f; float offSetY = 0f; double theta = 2.0 * Math.PI; vertexData[0] = (float) Math.sin(theta / circleVertexCount) * r + offSetX; vertexData[1] = (float) Math.cos(theta / circleVertexCount) * r + offSetY; for (int i = 2; i < 400; i += 2) { double angle = theta * i / circleVertexCount; x = (float) Math.cos(angle) * r; vertexData[i] = x + offSetX; } for (int i = 3; i < 404; i += 2) { double angle = Math.PI * 2 * i / circleVertexCount; y = (float) Math.sin(angle) * r; vertexData[i] = y + offSetY; } FloatBuffer vertexBuffer = BufferUtils.createFloatBuffer(vertexData.length); vertexBuffer.put(vertexData); vertexBuffer.flip(); vao = glGenVertexArrays(); glBindVertexArray(vao); vbo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER,vertexBuffer, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } public void loop() { glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLE_FAN, 0, vertexData.length / 2); glDisableVertexAttribArray(0); glBindVertexArray(0); } public static void main(String[] args) { new Circles(); } private void adjustVertexData() { float newData[] = new float[vertexData.length]; System.arraycopy(vertexData, 0, newData, 0, vertexData.length); if(Keyboard.isKeyDown(Keyboard.KEY_W)) { fXOffset += 0.05f; } else if(Keyboard.isKeyDown(Keyboard.KEY_S)) { fXOffset -= 0.05f; } for(int i = 0; i < vertexData.length; i += 2) { newData[i] += fXOffset; } FloatBuffer newDataBuffer = BufferUtils.createFloatBuffer(newData.length); newDataBuffer.put(newData); newDataBuffer.flip(); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferSubData(GL_ARRAY_BUFFER, 0, newDataBuffer); glBindBuffer(GL_ARRAY_BUFFER, 0); } } 300 Vertex Count(This is my main problem) 400 Vertex Count - I removed this image, it's bugged out, should be a tiny sliver cut out from the right, like a secant 500 Vertex Count Each 100, it removes more and more of the circle, and so on.

    Read the article

  • Solving a recurrence T(n) = 2T(n/2) + n^4

    - by user563454
    I am studying using the MIT Courseware and the CLRS book Introduction to Algorithms. Solving recurrence T(n) = 2T(n/2) + n4 (page 107) If I make a recurrence tree I get: level 0 n^4 level 1 2(n/2)^4 level 2 4(n/4)^4 level 3 8(n/8)^4 The tree has lg(n) levels. Therefore the recurrence is T(n) = Theta(lg(n)n^4)) But, If I use the Master method I get. Apply case 3: T(n) = Theta(n^4) If I apply the substitution method both seem to hold. Which one is ri?

    Read the article

  • Improving Comparison Operators and Window Functions

    It is dangerous to assume that your data is sound. SQL already has intrinsic ways to cope with missing, or unknown data in its comparison predicate operators, or Theta operators. Can SQL be more effective in the way it deals with data quality? Joe Celko describes how the SQL Standard could soon evolve to deal with data in ways that allow aggregation and windowing in cases where the data quality is less than perfect

    Read the article

  • Libgdx - 2D Mesh rendering overlap glitch

    - by user46858
    I am trying to render a 2D circle segment mesh (quarter circle)using Libgdx/Opengl ES 2.0 but I seem to be getting an overlapping issue as seen in the picture attached. I cant seem to find the cause of the problem but the overlapping disappears/reappears if I drag and resize the window to random sizes. The problem occurs on both pc and android. The strange thing is the first two segments atleast dont seem to be causing any overlapping only the third and/or forth segment.......even though they are all rendered using the same mesh object..... I have spent ages trying to find the cause of the problem before posting here for help so ANY help/advice in finding the cause of this problem would be really appreciated. public class MyGdxGame extends Game { private SpriteBatch batch; private Texture texture; private OrthographicCamera myCamera; private float w; private float h; private ShaderProgram circleSegShader; private Mesh circleScaleSegMesh; private Stage stage; private float TotalSegments; Vector3 virtualres; @Override public void create() { w = Gdx.graphics.getWidth(); h = Gdx.graphics.getHeight(); batch = new SpriteBatch(); ViewPortsize = new Vector2(); TotalSegments = 4.0f; virtualres = new Vector3(1280.0f, 720.0f, 0.0f); myCamera = new OrthographicCamera(); myCamera.setToOrtho(false, w, h); texture = new Texture(Gdx.files.internal("data/libgdx.png")); texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); circleScaleSegMesh = createCircleMesh_V3(0.0f,0.0f,200.0f, 30.0f,3, (360.0f /TotalSegments) ); circleSegShader = loadShaderFromFile(new String("circleseg.vert"), new String("circleseg.frag")); shaderProgram.pedantic = false; stage = new Stage(); stage.setViewport(new ExtendViewport(w, h)); Gdx.input.setInputProcessor(stage); } @Override public void render() { .... //render renderInit(); renderCircleScaledSegment(); } @Override public void resize(int width, int height) { stage.getViewport().update(width, height, true); myCamera.position.set( virtualres.x/2.0f, virtualres.y/2.0f, 0.0f); myCamera.update(); } public void renderInit(){ Gdx.gl20.glClearColor(1.0f, 1.0f, 1.0f, 0.0f); Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); batch.setShader(null); batch.setProjectionMatrix(myCamera.combined); } public void renderCircleScaledSegment(){ Gdx.gl20.glEnable(GL20.GL_DEPTH_TEST); Gdx.gl20.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); Gdx.gl20.glEnable(GL20.GL_BLEND); batch.begin(); circleSegShader.begin(); Matrix4 modelMatrix = new Matrix4(); Matrix4 cameraMatrix = new Matrix4(); Matrix4 cameraMatrix2 = new Matrix4(); Matrix4 cameraMatrix3 = new Matrix4(); Matrix4 cameraMatrix4 = new Matrix4(); cameraMatrix = myCamera.combined.cpy(); modelMatrix.idt().rotate(new Vector3(0.0f,0.0f,1.0f), 0.0f - ((360.0f /TotalSegments)/ 2.0f)).trn(virtualres.x/2.0f,virtualres.y/2.0f, 0.0f); cameraMatrix.mul(modelMatrix); cameraMatrix2 = myCamera.combined.cpy(); modelMatrix.idt().rotate(new Vector3(0.0f,0.0f,1.0f), 0.0f - ((360.0f /TotalSegments)/ 2.0f) +(360.0f /TotalSegments) ).trn(virtualres.x/2.0f,virtualres.y/2.0f, 0.0f); cameraMatrix2.mul(modelMatrix); cameraMatrix3 = myCamera.combined.cpy(); modelMatrix.idt().rotate(new Vector3(0.0f,0.0f,1.0f), 0.0f - ((360.0f /TotalSegments)/ 2.0f) +(2*(360.0f /TotalSegments))).trn(virtualres.x/2.0f,virtualres.y/2.0f, 0.0f); cameraMatrix3.mul(modelMatrix); cameraMatrix4 = myCamera.combined.cpy(); modelMatrix.idt().rotate(new Vector3(0.0f,0.0f,1.0f),0.0f - ((360.0f /TotalSegments)/ 2.0f) +(3*(360.0f /TotalSegments)) ).trn(virtualres.x/2.0f,virtualres.y/2.0f, 0.0f); cameraMatrix4.mul(modelMatrix); Vector3 box2dpos = new Vector3(0.0f, 0.0f, 0.0f); circleSegShader.setUniformMatrix("u_projTrans", cameraMatrix); circleSegShader.setUniformf("u_box2dpos", box2dpos); circleSegShader.setUniformi("u_texture", 0); texture.bind(); circleScaleSegMesh.render(circleSegShader, GL20.GL_TRIANGLES); circleSegShader.setUniformMatrix("u_projTrans", cameraMatrix2); circleSegShader.setUniformf("u_box2dpos", box2dpos); circleSegShader.setUniformi("u_texture", 0); texture.bind(); circleScaleSegMesh.render(circleSegShader, GL20.GL_TRIANGLES); circleSegShader.setUniformMatrix("u_projTrans", cameraMatrix3); circleSegShader.setUniformf("u_box2dpos", box2dpos); circleSegShader.setUniformi("u_texture", 0); texture.bind(); circleScaleSegMesh.render(circleSegShader, GL20.GL_TRIANGLES); circleSegShader.setUniformMatrix("u_projTrans", cameraMatrix4); circleSegShader.setUniformf("u_box2dpos", box2dpos); circleSegShader.setUniformi("u_texture", 0); texture.bind(); circleScaleSegMesh.render(circleSegShader, GL20.GL_TRIANGLES); circleSegShader.end(); batch.flush(); batch.end(); Gdx.gl20.glDisable(GL20.GL_DEPTH_TEST); Gdx.gl20.glDisable(GL20.GL_BLEND); } public Mesh createCircleMesh_V3(float cx, float cy, float r_out, float r_in, int num_segments, float segmentSizeDegrees){ float theta = (float) (2.0f * MathUtils.PI / (num_segments * (360.0f / segmentSizeDegrees))); float c = MathUtils.cos(theta);//precalculate the sine and cosine float s = MathUtils.sin(theta); float t,t2; float x = r_out;//we start at angle = 0 float y = 0; float x2 = r_in;//we start at angle = 0 float y2 = 0; float[] meshCoords = new float[num_segments *2 *3 *7]; int arrayIndex = 0; //array for triangles without indices for(int ii = 0; ii < num_segments; ii++) { meshCoords[arrayIndex] = x2+cx; meshCoords[arrayIndex +1] = y2+cy; meshCoords[arrayIndex +2] = 0.0f; meshCoords[arrayIndex +3] = 63.0f/255.0f; meshCoords[arrayIndex +4] = 139.0f/255.0f; meshCoords[arrayIndex +5] = 217.0f/255.0f; meshCoords[arrayIndex +6] = 0.7f; arrayIndex = arrayIndex + 7; meshCoords[arrayIndex] = x+cx; meshCoords[arrayIndex +1] = y+cy; meshCoords[arrayIndex +2] = 0.0f; meshCoords[arrayIndex +3] = 63.0f/255.0f; meshCoords[arrayIndex +4] = 139.0f/255.0f; meshCoords[arrayIndex +5] = 217.0f/255.0f; meshCoords[arrayIndex +6] = 0.7f; arrayIndex = arrayIndex + 7; t = x; x = c * x - s * y; y = s * t + c * y; meshCoords[arrayIndex] = x+cx; meshCoords[arrayIndex +1] = y+cy; meshCoords[arrayIndex +2] = 0.0f; meshCoords[arrayIndex +3] = 63.0f/255.0f; meshCoords[arrayIndex +4] = 139.0f/255.0f; meshCoords[arrayIndex +5] = 217.0f/255.0f; meshCoords[arrayIndex +6] = 0.7f; arrayIndex = arrayIndex + 7; meshCoords[arrayIndex] = x2+cx; meshCoords[arrayIndex +1] = y2+cy; meshCoords[arrayIndex +2] = 0.0f; meshCoords[arrayIndex +3] = 63.0f/255.0f; meshCoords[arrayIndex +4] = 139.0f/255.0f; meshCoords[arrayIndex +5] = 217.0f/255.0f; meshCoords[arrayIndex +6] = 0.7f; arrayIndex = arrayIndex + 7; meshCoords[arrayIndex] = x+cx; meshCoords[arrayIndex +1] = y+cy; meshCoords[arrayIndex +2] = 0.0f; meshCoords[arrayIndex +3] = 63.0f/255.0f; meshCoords[arrayIndex +4] = 139.0f/255.0f; meshCoords[arrayIndex +5] = 217.0f/255.0f; meshCoords[arrayIndex +6] = 0.7f; arrayIndex = arrayIndex + 7; t2 = x2; x2 = c * x2 - s * y2; y2 = s * t2 + c * y2; meshCoords[arrayIndex] = x2+cx; meshCoords[arrayIndex +1] = y2+cy; meshCoords[arrayIndex +2] = 0.0f; meshCoords[arrayIndex +3] = 63.0f/255.0f; meshCoords[arrayIndex +4] = 139.0f/255.0f; meshCoords[arrayIndex +5] = 217.0f/255.0f; meshCoords[arrayIndex +6] = 0.7f; arrayIndex = arrayIndex + 7; } Mesh myMesh = new Mesh(VertexDataType.VertexArray, false, meshCoords.length, 0, new VertexAttribute(VertexAttributes.Usage.Position, 3, "a_position"), new VertexAttribute(VertexAttributes.Usage.Color, 4, "a_color")); myMesh.setVertices(meshCoords); return myMesh; } }

    Read the article

< Previous Page | 1 2 3 4  | Next Page >