Search Results

Search found 35 results on 2 pages for 'xmax'.

Page 1/2 | 1 2  | Next Page >

  • G++, compiler warnings, c++ templates

    - by Ian
    During the compilatiion of the C++ program those warnings appeared: c:/MinGW/bin/../lib/gcc/mingw32/3.4.5/../../../../include/c++/3.4.5/bc:/MinGW/bin/../lib/gcc/mingw32/3.4.5/../../../../include/c++/3.4.5/bits/stl_algo.h:2317: instantiated from `void std::partial_sort(_RandomAccessIterator, _RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Object<double>**, std::vector<Object<double>*, std::allocator<Object<double>*> > >, _Compare = sortObjects<double>]' c:/MinGW/bin/../lib/gcc/mingw32/3.4.5/../../../../include/c++/3.4.5/bits/stl_algo.h:2506: instantiated from `void std::__introsort_loop(_RandomAccessIterator, _RandomAccessIterator, _Size, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Object<double>**, std::vector<Object<double>*, std::allocator<Object<double>*> > >, _Size = int, _Compare = sortObjects<double>]' c:/MinGW/bin/../lib/gcc/mingw32/3.4.5/../../../../include/c++/3.4.5/bits/stl_algo.h:2589: instantiated from `void std::sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Object<double>**, std::vector<Object<double>*, std::allocator<Object<double>*> > >, _Compare = sortObjects<double>]' io/../structures/objects/../../algorithm/analysis/../../structures/list/ObjectsList.hpp:141: instantiated from `void ObjectsList <T>::sortObjects(unsigned int, T, T, T, T, unsigned int) [with T = double]' I do not why, because all objects have only template parameter T, their local variables are also T. The only place, where I am using double is main. There are objects of type double creating and adding into the ObjectsList... Object <double> o1; ObjectsList <double> olist; olist.push_back(o1); .... T xmin = ..., ymin = ..., xmax = ..., ymax = ...; unsigned int n = ...; olist.sortAllObjects(xmin, ymin, xmax, ymax, n); and comparator template <class T> class sortObjects { private: unsigned int n; T xmin, ymin, xmax, ymax; public: sortObjects ( const T xmin_, const T ymin_, const T xmax_, const T ymax_, const int n_ ) : xmin ( xmin_ ), ymin ( ymin_ ), xmax ( xmax_ ), ymax ( ymax_ ), n ( n_ ) {} bool operator() ( const Object <T> *o1, const Object <T> *o2 ) const { T dmax = (std::max) ( xmax - xmin, ymax - ymin ); T x_max = ( xmax - xmin ) / dmax; T y_max = ( ymax - ymin ) / dmax; ... return ....; } representing ObjectsList method: template <class T> void ObjectsList <T> ::sortAllObjects ( const T xmin, const T ymin, const T xmax, const T ymax, const unsigned int n ) { std::sort ( objects.begin(), objects.end(), sortObjects <T> ( xmin, ymin, xmax, ymax, n ) ); }

    Read the article

  • F# and ArcObjects, Part 3

    - by Marko Apfel
    Today i played a little bit with IFeature-sequences and piping data. The result was a calculator of the bounding box around all features in a feature class. Maybe a little bit dirty, but for learning was it OK. ;-) open System;; #I "C:\Program Files\ArcGIS\DotNet";; #r "ESRI.ArcGIS.System.dll";; #r "ESRI.ArcGIS.DataSourcesGDB.dll";; #r "ESRI.ArcGIS.Geodatabase.dll";; #r "ESRI.ArcGIS.Geometry.dll";; open ESRI.ArcGIS.esriSystem;; open ESRI.ArcGIS.DataSourcesGDB;; open ESRI.ArcGIS.Geodatabase;; open ESRI.ArcGIS.Geometry; let aoInitialize = new AoInitializeClass();; let status = aoInitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcEditor);; let workspacefactory = new SdeWorkspaceFactoryClass();; let connection = "SERVER=okul;DATABASE=p;VERSION=sde.default;INSTANCE=sde:sqlserver:okul;USER=s;PASSWORD=g";; let workspace = workspacefactory.OpenFromString(connection, 0);; let featureWorkspace = (box workspace) :?> IFeatureWorkspace;; let featureClass = featureWorkspace.OpenFeatureClass("Praxair.SFG.BP_L_ROHR");; let queryFilter = new QueryFilterClass();; let featureCursor = featureClass.Search(queryFilter, true);; let featureCursorSeq (featureCursor : IFeatureCursor) = let actualFeature = ref (featureCursor.NextFeature()) seq { while (!actualFeature) <> null do yield actualFeature do actualFeature := featureCursor.NextFeature() };; let min x y = if x < y then x else y;; let max x y = if x > y then x else y;; let info s (x : IEnvelope) = printfn "%s xMin:{%f} xMax: {%f} yMin:{%f} yMax: {%f}" s x.XMin x.XMax x.YMin x.YMax;; let con (env1 : IEnvelope) (env2 : IEnvelope) = let env = (new EnvelopeClass()) :> IEnvelope env.XMin <- min env1.XMin env2.XMin env.XMax <- max env1.XMax env2.XMax env.YMin <- min env1.YMin env2.YMin env.YMax <- max env1.YMax env2.YMax info "Intermediate" env env;; let feature = featureClass.GetFeature(100);; let ext = feature.Extent;; let BoundingBox featureClassName = let featureClass = featureWorkspace.OpenFeatureClass(featureClassName) let queryFilter = new QueryFilterClass() let featureCursor = featureClass.Search(queryFilter, true) let featureCursorSeq (featureCursor : IFeatureCursor) = let actualFeature = ref (featureCursor.NextFeature()) seq { while (!actualFeature) <> null do yield actualFeature do actualFeature := featureCursor.NextFeature() } featureCursorSeq featureCursor |> Seq.map (fun feature -> (!feature).Extent) |> Seq.fold (fun (acc : IEnvelope) a -> info "Intermediate" acc (con acc a)) ext ;; let boundingBox = BoundingBox "Praxair.SFG.BP_L_ROHR";; info "Ende-Info:" boundingBox;;

    Read the article

  • Qwt setAxisScale() locks up application when given numbers less than 2e-07 and greater than 0

    - by Dane Larsen
    I'm using Qwt for some scientific graphing, and I'm working with some fairly small numbers, the smallest being around 1.0e-22. I'm trying to call setAxisScale(xaxis, xmin, xmax) //xmin = 0, xmax = 2.0e-10 But when I do, the application locks up. I haven't found anything in the documentation that refers to a minimum value. Xmin and xmax are both doubles, so that shouldn't be a problem. Is this a bug in Qwt, or am I doing something wrong? Thanks in advance

    Read the article

  • Qwt setAxisScale() seems to lock up application when given numbers with greater precision than 2e-07

    - by Dane Larsen
    I'm using Qwt for some scientific graphing, and I'm working with some fairly small numbers, the smallest being around 1.0e-22. I'm trying to call setAxisScale(xaxis, xmin, xmax) //xmin = 0, xmax = 2.0e-10 But when I do, the application locks up. I haven't found anything in the documentation that refers to a minimum value. Xmin and xmax are both doubles, so that shouldn't be a problem. Is this a bug in Qwt, or am I doing something wrong? Thanks in advance

    Read the article

  • vector::erase with pointer member

    - by matt
    I am manipulating vectors of objects defined as follow: class Hyp{ public: int x; int y; double wFactor; double hFactor; char shapeNum; double* visibleShape; int xmin, xmax, ymin, ymax; Hyp(int xx, int yy, double ww, double hh, char s): x(xx), y(yy), wFactor(ww), hFactor(hh), shapeNum(s) {visibleShape=0;shapeNum=-1;}; //Copy constructor necessary for support of vector::push_back() with visibleShape Hyp(const Hyp &other) { x = other.x; y = other.y; wFactor = other.wFactor; hFactor = other.hFactor; shapeNum = other.shapeNum; xmin = other.xmin; xmax = other.xmax; ymin = other.ymin; ymax = other.ymax; int visShapeSize = (xmax-xmin+1)*(ymax-ymin+1); visibleShape = new double[visShapeSize]; for (int ind=0; ind<visShapeSize; ind++) { visibleShape[ind] = other.visibleShape[ind]; } }; ~Hyp(){delete[] visibleShape;}; }; When I create a Hyp object, allocate/write memory to visibleShape and add the object to a vector with vector::push_back, everything works as expected: the data pointed by visibleShape is copied using the copy-constructor. But when I use vector::erase to remove a Hyp from the vector, the other elements are moved correctly EXCEPT the pointer members visibleShape that are now pointing to wrong addresses! How to avoid this problem? Am I missing something?

    Read the article

  • Incorrect output on changing sequence of declarations

    - by max
    Writing C++ code to implement Sutherland-Hodgeman polygon clipping. This order of declaration of these 2 statements gives correct output, reverse does not. int numberOfVertices = 5; Point pointList[] = { {50,50}, {200,300}, {310,110}, {130,90}, {70,40} }; I am passing the polygon vertex set to clippers in order - LEFT, RIGHT, TOP, BOTTOM. The exact error which comes when the declarations are reversed is that the bottom clipper, produces an empty set of vertices so no polygon is displayed after clipping. Correct: Incorrent: Confirmed by outputting the number of vertices produced after each pass: Correct: Incorrect: What is the reason for this error? Code: #include <iostream> #include <GL/glut.h> #define MAXVERTICES 10 #define LEFT 0 #define RIGHT 1 #define TOP 2 #define BOTTOM 3 using namespace std; /* Clipping window */ struct Window { double xmin; double xmax; double ymin; double ymax; }; struct Point { double x; double y; }; /* If I interchange these two lines, the code doesn't work. */ /**************/ int numberOfVertices = 5; Point pointList[] = { {50,50}, {200,300}, {310,110}, {130,90}, {70,40} }; /**************/ const Window w = { 100, 400, 60, 200 }; /* Checks whether a point is inside or outside a window side */ int isInside(Point p, int side) { switch(side) { case LEFT: return p.x >= w.xmin; case RIGHT: return p.x <= w.xmax; case TOP: return p.y <= w.ymax; case BOTTOM: return p.y >= w.ymin; } } /* Calculates intersection of a segment and a window side */ Point intersection(Point p1, Point p2, int side) { Point temp; double slope, intercept; bool infinite; /* Find slope and intercept of segment, taking care of inf slope */ if(p2.x - p1.x != 0) { slope = (p2.y - p1.y) / (p2.x - p1.x); infinite = false; } else { infinite = true; } intercept = p1.y - p1.x * slope; /* Calculate intersections */ switch(side) { case LEFT: temp.x = w.xmin; temp.y = temp.x * slope + intercept; break; case RIGHT: temp.x = w.xmax; temp.y = temp.x * slope + intercept; break; case TOP: temp.y = w.ymax; temp.x = infinite ? p1.x : (temp.y - intercept) / slope; break; case BOTTOM: temp.y = w.ymin; temp.x = infinite ? p1.x : (temp.y - intercept) / slope; break; } return temp; } /* Clips polygon against a side, updating the point list (called once for each side) */ void clipAgainstSide(int sideToClip) { int i, j=0; Point s,p; Point outputList[MAXVERTICES]; /* Main algorithm */ s = pointList[numberOfVertices-1]; for(i=0 ; i<numberOfVertices ; i++) { p = pointList[i]; if(isInside(p, sideToClip)) { /* p inside */ if(!isInside(s, sideToClip)) { /* p inside, s outside */ outputList[j] = intersection(p, s, sideToClip); j++; } outputList[j] = p; j++; } else if(isInside(s, sideToClip)) { /* s inside, p outside */ outputList[j] = intersection(s, p, sideToClip); j++; } s = p; } /* Updating number of points and point list */ numberOfVertices = j; /* ERROR: In last call with BOTTOM argument, numberOfVertices becomes 0 */ /* all earlier 3 calls have correct output */ cout<<numberOfVertices<<endl; for(i=0 ; i<numberOfVertices ; i++) { pointList[i] = outputList[i]; } } void SutherlandHodgemanPolygonClip() { clipAgainstSide(LEFT); clipAgainstSide(RIGHT); clipAgainstSide(TOP); clipAgainstSide(BOTTOM); } void init() { glClearColor(1,1,1,0); glMatrixMode(GL_PROJECTION); gluOrtho2D(0,1000,0,500); } void display() { glClear(GL_COLOR_BUFFER_BIT); /* Displaying ORIGINAL box and polygon */ glColor3f(0,0,1); glBegin(GL_LINE_LOOP); glVertex2i(w.xmin, w.ymin); glVertex2i(w.xmin, w.ymax); glVertex2i(w.xmax, w.ymax); glVertex2i(w.xmax, w.ymin); glEnd(); glColor3f(1,0,0); glBegin(GL_LINE_LOOP); for(int i=0 ; i<numberOfVertices ; i++) { glVertex2i(pointList[i].x, pointList[i].y); } glEnd(); /* Clipping */ SutherlandHodgemanPolygonClip(); /* Displaying CLIPPED box and polygon, 500px right */ glColor3f(0,0,1); glBegin(GL_LINE_LOOP); glVertex2i(w.xmin+500, w.ymin); glVertex2i(w.xmin+500, w.ymax); glVertex2i(w.xmax+500, w.ymax); glVertex2i(w.xmax+500, w.ymin); glEnd(); glColor3f(1,0,0); glBegin(GL_LINE_LOOP); for(int i=0 ; i<numberOfVertices ; i++) { glVertex2i(pointList[i].x+500, pointList[i].y); } glEnd(); glFlush(); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(1000,500); glutCreateWindow("Sutherland-Hodgeman polygon clipping"); init(); glutDisplayFunc(display); glutMainLoop(); return 0; }

    Read the article

  • Dynamically udpate canvasOverlay property of jQuery jqPlot

    - by You Kuper
    I want to dynamically udpate canvasOverlay property of jQuery jqPlot. This will provide the effect of a timeline in my jqPlot. This effect should be similar to the one shown in this jFiddle. However, instead of drawing points, I want to update canvasOverlay property every second: canvasOverlay: { show: true, objects: [ { rectangle: { xmax: new Date(), xminOffset: "0px", xmaxOffset: "0px", yminOffset: "0px", ymaxOffset: "0px", color: "rgba(0, 0, 0, 0.1)", showTooltip: true } }, ] } How can I do this? What are the functions I should use? UPDATE: My idea is to do something like this: canvasOverlay: { name: 'current', show: true, objects: [ { rectangle: { xmax: new Date(), xminOffset: "0px", xmaxOffset: "0px", yminOffset: "0px", ymaxOffset: "0px", color: "rgba(0, 0, 0, 0.1)", showTooltip: true } }, ] } /... var co = plot.plugins.canvasOverlay; var current = co.get('current'); current.options.objects.rectangle.xmax = new Date(); co.draw(plot);

    Read the article

  • Using core plot for iPhone, drawing date on x axis

    - by xmax
    I have available an array of dictionary that contains NSDate and NSNumber values. I wanted to plot date on X axis. for plotting I need to supply xRanges to plot with some decimal values.I don't understand how can i supply NSdate values to xRange (low and length). And what should be there in this method: -(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index I mean how my date value will be returned as NSNumber..? I think i should use some interval over there.but what should be the exact conversion..? can any one explain me what are the exact requirement to plot the date on xAxis..? I am plotting my plot in half of the view.

    Read the article

  • Pythonic reading from config files

    - by Adam Matan
    Hi, I have a python class which reads a config file using ConfigParser: Config file: [geography] Xmin=6.6 Xmax=18.6 Ymin=36.6 YMax=47.1 Python code: class Slicer: def __init__(self, config_file_name): config = ConfigParser.ConfigParser() config.read(config_file_name) # Rad the lines from the file self.x_min = config.getfloat('geography', 'xmin') self.x_max = config.getfloat('geography', 'xmax') self.y_min = config.getfloat('geography', 'ymin') self.y_max = config.getfloat('geography', 'ymax') I feel that the last four lines are repetitive, and should somehow be compressed to one Pythonic line that would create a self.item variable for each item in the section. Any ideas? Adam

    Read the article

  • Fortran 90 How to call a function in a subroutine in a module?

    - by Feynman
    I have a module that "contains" a subroutine that "contains" a function. I say "use themodule" in my main program and I can "call thesubroutine", but how to I get the function that is "contained" in the subroutine? The code looks like this: module useful integer, parameter :: N=2 double precision, parameter :: xmin=1, xmax=10, pi=3.1415926535898 double complex :: green(N,N), solution(N), k=(2.0,0.0) contains subroutine y(n1) contains function x(n1) real :: n1, x x=n1*(xmax-xmin)/N end function x end subroutine y end module useful

    Read the article

  • Optimizing spacing of mesh containing a given set of points

    - by Feynman
    I tried to summarize the this as best as possible in the title. I am writing an initial value problem solver in the most general way possible. I start with an arbitrary number of initial values at arbitrary locations (inside a boundary.) The first part of my program creates a mesh/grid (I am not sure which is the correct nuance), with N points total, that contains all the initial values. My goal is to optimize the mesh such that the spacing is as uniform as possible. My solver seems to work half decently (it needs some more obscure debugging that is not relevant here.) I am starting with one dimension. I intend to generalize the algorithm to an arbitrary number of dimensions once I get it working consistently. I am writing my code in fortran, but feel free to reply with pseudocode or the language of your choice. Allow me to elaborate with an example: Say I am working on a closed interval [1,10] xmin=1 xmax=10 Say I have 3 initial points: xmin, 5 and xmax num_ivc=3 known(num_ivc)=[xmin,5,xmax] //my arrays start at 1. Assume "known" starts sorted I store my mesh/grid points in an array called coord. Say I want 10 points total in my mesh/grid. N=10 coord(10) Remember, all this is arbitrary--except the variable names of course. The algorithm should set coord to {1,2,3,4,5,6,7,8,9,10} Now for a less trivial example: num_ivc=3 known(num_ivc)=[xmin,5.5,xmax or just num_ivc=1 known(num_ivc)=[5.5] Now, would you have 5 evenly spaced points on the interval [1, 5.5] and 5 evenly spaced points on the interval (5.5, 10]? But there is more space between 1 and 5.5 than between 5.5 and 10. So would you have 6 points on [1, 5.5] followed by 4 on (5.5 to 10]. The key is to minimize the difference in spacing. I have been working on this for 2 days straight and I can assure you it is a lot trickier than it sounds. I have written code that only works if N is large only works if N is small only works if it the known points are close together only works if it the known points are far apart only works if at least one of the known points is near a boundary only works if none of the known points are near a boundary So as you can see, I have coded the gamut of almost-solutions. I cannot figure out a way to get it to perform equally well in all possible scenarios (that is, create the optimum spacing.)

    Read the article

  • How do I classify using GLCM and SVM Classifier in Matlab?

    - by Gomathi
    I'm on a project of liver tumor segmentation and classification. I used Region Growing and FCM for liver and tumor segmentation respectively. Then, I used Gray Level Co-occurence matrix for texture feature extraction. I have to use Support Vector Machine for Classification. But I don't know how to normalize the feature vectors. Can anyone tell how to program it in Matlab? To the GLCM program, I gave the tumor segmented image as input. Was I correct? If so, I think, then, my output will also be correct. My glcm coding, as far as I have tried is, I = imread('fzliver3.jpg'); GLCM = graycomatrix(I,'Offset',[2 0;0 2]); stats = graycoprops(GLCM,'all') t1= struct2array(stats) I2 = imread('fzliver4.jpg'); GLCM2 = graycomatrix(I2,'Offset',[2 0;0 2]); stats2 = graycoprops(GLCM2,'all') t2= struct2array(stats2) I3 = imread('fzliver5.jpg'); GLCM3 = graycomatrix(I3,'Offset',[2 0;0 2]); stats3 = graycoprops(GLCM3,'all') t3= struct2array(stats3) t=[t1;t2;t3] xmin = min(t); xmax = max(t); scale = xmax-xmin; tf=(x-xmin)/scale Was this a correct implementation? Also, I get an error at the last line. My output is: stats = Contrast: [0.0510 0.0503] Correlation: [0.9513 0.9519] Energy: [0.8988 0.8988] Homogeneity: [0.9930 0.9935] t1 = Columns 1 through 6 0.0510 0.0503 0.9513 0.9519 0.8988 0.8988 Columns 7 through 8 0.9930 0.9935 stats2 = Contrast: [0.0345 0.0339] Correlation: [0.8223 0.8255] Energy: [0.9616 0.9617] Homogeneity: [0.9957 0.9957] t2 = Columns 1 through 6 0.0345 0.0339 0.8223 0.8255 0.9616 0.9617 Columns 7 through 8 0.9957 0.9957 stats3 = Contrast: [0.0230 0.0246] Correlation: [0.7450 0.7270] Energy: [0.9815 0.9813] Homogeneity: [0.9971 0.9970] t3 = Columns 1 through 6 0.0230 0.0246 0.7450 0.7270 0.9815 0.9813 Columns 7 through 8 0.9971 0.9970 t = Columns 1 through 6 0.0510 0.0503 0.9513 0.9519 0.8988 0.8988 0.0345 0.0339 0.8223 0.8255 0.9616 0.9617 0.0230 0.0246 0.7450 0.7270 0.9815 0.9813 Columns 7 through 8 0.9930 0.9935 0.9957 0.9957 0.9971 0.9970 ??? Error using ==> minus Matrix dimensions must agree. The images are:

    Read the article

  • Black Screen: How to set Projection/View Matrix

    - by Lisa
    I have a Windows Phone 8 C#/XAML with DirectX component project. I'm rendering some particles, but each particle is a rectangle versus a square (as I've set the vertices to be positions equally offset from each other). I used an Identity matrix in the view and projection matrix. I decided to add the windows aspect ratio to prevent the rectangles. But now I get a black screen. None of the particles are rendered now. I don't know what's wrong with my matrices. Can anyone see the problem? These are the default matrices in Microsoft's project example. View Matrix: XMVECTOR eye = XMVectorSet(0.0f, 0.7f, 1.5f, 0.0f); XMVECTOR at = XMVectorSet(0.0f, -0.1f, 0.0f, 0.0f); XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); XMStoreFloat4x4(&m_constantBufferData.view, XMMatrixTranspose(XMMatrixLookAtRH(eye, at, up))); Projection Matrix: void CubeRenderer::CreateWindowSizeDependentResources() { Direct3DBase::CreateWindowSizeDependentResources(); float aspectRatio = m_windowBounds.Width / m_windowBounds.Height; float fovAngleY = 70.0f * XM_PI / 180.0f; if (aspectRatio < 1.0f) { fovAngleY /= aspectRatio; } XMStoreFloat4x4(&m_constantBufferData.projection, XMMatrixTranspose(XMMatrixPerspectiveFovRH(fovAngleY, aspectRatio, 0.01f, 100.0f))); } I've tried modifying them to use cocos2dx's WP8 example. XMMATRIX identityMatrix = XMMatrixIdentity(); float fovy = 60.0f; float aspect = m_windowBounds.Width / m_windowBounds.Height; float zNear = 0.1f; float zFar = 100.0f; float xmin, xmax, ymin, ymax; ymax = zNear * tanf(fovy * XM_PI / 360); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; XMMATRIX tmpMatrix = XMMatrixPerspectiveOffCenterRH(xmin, xmax, ymin, ymax, zNear, zFar); XMMATRIX projectionMatrix = XMMatrixMultiply(tmpMatrix, identityMatrix); // View Matrix float fEyeX = m_windowBounds.Width * 0.5f; float fEyeY = m_windowBounds.Height * 0.5f; float fEyeZ = m_windowBounds.Height / 1.1566f; float fLookAtX = m_windowBounds.Width * 0.5f; float fLookAtY = m_windowBounds.Height * 0.5f; float fLookAtZ = 0.0f; float fUpX = 0.0f; float fUpY = 1.0f; float fUpZ = 0.0f; XMMATRIX tmpMatrix2 = XMMatrixLookAtRH(XMVectorSet(fEyeX,fEyeY,fEyeZ,0.f), XMVectorSet(fLookAtX,fLookAtY,fLookAtZ,0.f), XMVectorSet(fUpX,fUpY,fUpZ,0.f)); XMMATRIX viewMatrix = XMMatrixMultiply(tmpMatrix2, identityMatrix); XMStoreFloat4x4(&m_constantBufferData.view, viewMatrix); Vertex Shader cbuffer ModelViewProjectionConstantBuffer : register(b0) { //matrix model; matrix view; matrix projection; }; struct VertexInputType { float4 position : POSITION; float2 tex : TEXCOORD0; float4 color : COLOR; }; struct PixelInputType { float4 position : SV_POSITION; float2 tex : TEXCOORD0; float4 color : COLOR; }; PixelInputType main(VertexInputType input) { PixelInputType output; // Change the position vector to be 4 units for proper matrix calculations. input.position.w = 1.0f; //===================================== // TODO: ADDED for testing input.position.z = 0.0f; //===================================== // Calculate the position of the vertex against the world, view, and projection matrices. //output.position = mul(input.position, model); output.position = mul(input.position, view); output.position = mul(output.position, projection); // Store the texture coordinates for the pixel shader. output.tex = input.tex; // Store the particle color for the pixel shader. output.color = input.color; return output; } Before I render the shader, I set the view/projection matrices into the constant buffer void ParticleRenderer::SetShaderParameters() { ViewProjectionConstantBuffer* dataPtr; D3D11_MAPPED_SUBRESOURCE mappedResource; DX::ThrowIfFailed(m_d3dContext->Map(m_constantBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource)); dataPtr = (ViewProjectionConstantBuffer*)mappedResource.pData; dataPtr->view = m_constantBufferData.view; dataPtr->projection = m_constantBufferData.projection; m_d3dContext->Unmap(m_constantBuffer.Get(), 0); // Now set the constant buffer in the vertex shader with the updated values. m_d3dContext->VSSetConstantBuffers(0, 1, m_constantBuffer.GetAddressOf() ); // Set shader texture resource in the pixel shader. m_d3dContext->PSSetShaderResources(0, 1, &m_textureView); } Nothing, black screen... I tried so many different look at, eye, and up vectors. I tried transposing the matrices. I've set the particle center position to always be (0, 0, 0), I tried different positions too, just to make sure they're not being rendered offscreen.

    Read the article

  • geom_rect and NULL

    - by csgillespie
    I've been looking at the geom_rect example in section 5.10 of the ggplot2 book and don't understand the purpose of the NULL's in the aes function. For example, using the mpg data: g = ggplot(data=mpg, aes(x=displ, y=hwy)) + geom_point() #Produces a plot with a transparent filled region g + geom_rect(aes(NULL, NULL), alpha=0.1,xmin=5, xmax=7, ymin=10, ymax=45, fill="blue") #Solid filled region (v0.9) or nothing in v0.8 g + geom_rect(alpha=0.1,xmin=5, xmax=7, ymin=10, ymax=45, fill="blue") My understanding is that the NULL's are resetting the x & y mapping, but I don't see why this should affect the transparency.

    Read the article

  • OpenGL flickerinng near the edges

    - by Daniel
    I am trying to simulate particles moving around the scene with OpenCL for computation and OpenGL for rendering with GLUT. There is no OpenCL-OpenGL interop yet, so the drawing is done in the older fixed pipeline way. Whenever circles get close to the edges, they start to flicker. The drawing should draw a part of the circle on the top of the scene and a part on the bottom. The effect is the following: The balls you see on the bottom should be one part on the bottom and one part on the top. Wrapping around the scene, so to say, but they constantly flicker. The code for drawing them is: void Scene::drawCircle(GLuint index){ glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(pos.at(2*index),pos.at(2*index+1), 0.0f); glBegin(GL_TRIANGLE_FAN); GLfloat incr = (2.0 * M_PI) / (GLfloat) slices; glColor3f(0.8f, 0.255f, 0.26f); glVertex2f(0.0f, 0.0f); glColor3f(1.0f, 0.0f, 0.0f); for(GLint i = 0; i <=slices; ++i){ GLfloat x = radius * sin((GLfloat) i * incr); GLfloat y = radius * cos((GLfloat) i * incr); glVertex2f(x, y); } glEnd(); } If it helps, this is the reshape method: void Scene::reshape(GLint width, GLint height){ if(0 == height) height = 1; //Prevent division by zero glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(xmin, xmax, ymin, ymax); std::cout << xmin << " " << xmax << " " << ymin << " " << ymax << std::endl; }

    Read the article

  • Multiple data series in real time plot

    - by Gr3n
    Hi, I'm kind of new to Python and trying to create a plotting app for values read via RS232 from a sensor. I've managed (after some reading and copying examples online) to get a plot working that updates on a timer which is great. My only trouble is that I can't manage to get multiple data series into the same plot. Does anyone have a solution to this? This is the code that I've worked out this far: import os import pprint import random import sys import wx # The recommended way to use wx with mpl is with the WXAgg backend import matplotlib matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas, NavigationToolbar2WxAgg as NavigationToolbar import numpy as np import pylab DATA_LENGTH = 100 REDRAW_TIMER_MS = 20 def getData(): return int(random.uniform(1000, 1020)) class GraphFrame(wx.Frame): # the main frame of the application def __init__(self): wx.Frame.__init__(self, None, -1, "Usart plotter", size=(800,600)) self.Centre() self.data = [] self.paused = False self.create_menu() self.create_status_bar() self.create_main_panel() self.redraw_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer) self.redraw_timer.Start(REDRAW_TIMER_MS) def create_menu(self): self.menubar = wx.MenuBar() menu_file = wx.Menu() m_expt = menu_file.Append(-1, "&Save plot\tCtrl-S", "Save plot to file") self.Bind(wx.EVT_MENU, self.on_save_plot, m_expt) menu_file.AppendSeparator() m_exit = menu_file.Append(-1, "E&xit\tCtrl-X", "Exit") self.Bind(wx.EVT_MENU, self.on_exit, m_exit) self.menubar.Append(menu_file, "&File") self.SetMenuBar(self.menubar) def create_main_panel(self): self.panel = wx.Panel(self) self.init_plot() self.canvas = FigCanvas(self.panel, -1, self.fig) # pause button self.pause_button = wx.Button(self.panel, -1, "Pause") self.Bind(wx.EVT_BUTTON, self.on_pause_button, self.pause_button) self.Bind(wx.EVT_UPDATE_UI, self.on_update_pause_button, self.pause_button) self.hbox1 = wx.BoxSizer(wx.HORIZONTAL) self.hbox1.Add(self.pause_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.canvas, 1, flag=wx.LEFT | wx.TOP | wx.GROW) self.vbox.Add(self.hbox1, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.panel.SetSizer(self.vbox) #self.vbox.Fit(self) def create_status_bar(self): self.statusbar = self.CreateStatusBar() def init_plot(self): self.dpi = 100 self.fig = Figure((3.0, 3.0), dpi=self.dpi) self.axes = self.fig.add_subplot(111) self.axes.set_axis_bgcolor('white') self.axes.set_title('Usart data', size=12) pylab.setp(self.axes.get_xticklabels(), fontsize=8) pylab.setp(self.axes.get_yticklabels(), fontsize=8) # plot the data as a line series, and save the reference # to the plotted line series # self.plot_data = self.axes.plot( self.data, linewidth=1, color="blue", )[0] def draw_plot(self): # redraws the plot xmax = len(self.data) if len(self.data) > DATA_LENGTH else DATA_LENGTH xmin = xmax - DATA_LENGTH ymin = 0 ymax = 4096 self.axes.set_xbound(lower=xmin, upper=xmax) self.axes.set_ybound(lower=ymin, upper=ymax) # enable grid #self.axes.grid(True, color='gray') # Using setp here is convenient, because get_xticklabels # returns a list over which one needs to explicitly # iterate, and setp already handles this. # pylab.setp(self.axes.get_xticklabels(), visible=True) self.plot_data.set_xdata(np.arange(len(self.data))) self.plot_data.set_ydata(np.array(self.data)) self.canvas.draw() def on_pause_button(self, event): self.paused = not self.paused def on_update_pause_button(self, event): label = "Resume" if self.paused else "Pause" self.pause_button.SetLabel(label) def on_save_plot(self, event): file_choices = "PNG (*.png)|*.png" dlg = wx.FileDialog( self, message="Save plot as...", defaultDir=os.getcwd(), defaultFile="plot.png", wildcard=file_choices, style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() self.canvas.print_figure(path, dpi=self.dpi) self.flash_status_message("Saved to %s" % path) def on_redraw_timer(self, event): if not self.paused: newData = getData() self.data.append(newData) self.draw_plot() def on_exit(self, event): self.Destroy() def flash_status_message(self, msg, flash_len_ms=1500): self.statusbar.SetStatusText(msg) self.timeroff = wx.Timer(self) self.Bind( wx.EVT_TIMER, self.on_flash_status_off, self.timeroff) self.timeroff.Start(flash_len_ms, oneShot=True) def on_flash_status_off(self, event): self.statusbar.SetStatusText('') if __name__ == '__main__': app = wx.PySimpleApp() app.frame = GraphFrame() app.frame.Show() app.MainLoop()

    Read the article

  • How can I marshall a vector<int> from a C++ dll to a C# application?

    - by mmr
    I have a C++ function that produces a list of rectangles that are interesting. I want to be able to get that list out of the C++ library and back into the C# application that is calling it. So far, I'm encoding the rectangles like so: struct ImagePatch{ int xmin, xmax, ymin, ymax; } and then encoding some vectors: void MyFunc(..., std::vector<int>& rectanglePoints){ std::vector<ImagePatch> patches; //this is filled with rectangles for(i = 0; i < patches.size(); i++){ rectanglePoints.push_back(patches[i].xmin); rectanglePoints.push_back(patches[i].xmax); rectanglePoints.push_back(patches[i].ymin); rectanglePoints.push_back(patches[i].ymax); } } The header for interacting with C# looks like (and works for a bunch of other functions): extern "C" { __declspec(dllexport) void __cdecl MyFunc(..., std::vector<int>& rectanglePoints); } Are there some keywords or other things I can do to get that set of rectangles out? I found this article for marshalling objects in C#, but it seems way too complicated and way too underexplained. Is a vector of integers the right way to do this, or is there some other trick or approach?

    Read the article

  • pylab.savefig() and pylab.show() image difference

    - by Jack1990
    I'm making an script to automatically create plots from .xvg files, but there's a problem when I'm trying to use pylab's savefig() method. Using pylab.show() and saving from there, everything's fine. Using pylab.show() Using pylab.savefig() def producePlot(timestep, energy_values,type_line = 'r', jump = 1,finish = 100): fc = sp.interp1d(timestep[::jump], energy_values[::jump],kind='cubic') xnew = numpy.linspace(0, finish, finish*2) pylab.plot(xnew, fc(xnew),type_line) pylab.xlabel('Time in ps ') pylab.ylabel('kJ/mol') pylab.xlim(xmin=0, xmax=finish) def produceSimplePlot(timestep, energy_values,type_line = 'r', jump = 1,finish = 100): pylab.plot(timestep, energy_values,type_line) pylab.xlabel('Time in ps ') pylab.ylabel('kJ/mol') pylab.xlim(xmin=0, xmax=finish) def linearRegression(timestep, energy_values, type_line = 'g'): #, jump = 1,finish = 100): from scipy import stats import numpy #print 'fuck' timestep = numpy.asarray(timestep) slope, intercept, r_value, p_value, std_err = stats.linregress(timestep,energy_values) line = slope*timestep+intercept pylab.plot(timestep, line, type_line) def plottingTime(Title,file_name, timestep, energy_values ,loc, jump , finish): pylab.title(Title) producePlot(timestep,energy_values, 'b',jump, finish) linearRegression(timestep,energy_values) import numpy Average = numpy.average(energy_values) #print Average pylab.legend(("Average = %.2f" %(Average),'Linear Reg'),loc) #pylab.show() pylab.savefig('%s.jpg' %file_name[:-4], bbox_inches= None, pad_inches=0) #if __name__ == '__main__': #plottingTime(Title,timestep1, energy_values, jump =10, finish = 4800) def specialCase(Title,file_name, timestep, energy_values,loc, jump, finish): #print 'Working here ...?' pylab.title(Title) producePlot(timestep,energy_values, 'b',jump, finish) import numpy from pylab import * Average = numpy.average(energy_values) #print Average pylab.legend(("Average = %.2g" %(Average), Title),loc) locs,labels = yticks() yticks(locs, map(lambda x: "%.3g" % x, locs)) #pylab.show() pylab.savefig('%s.jpg' %file_name[:-4] , bbox_inches= None, pad_inches=0) Thanks in advance, John

    Read the article

  • Scrolling a canvas as a shape you're moving approaches its edges

    - by Steven Sproat
    Hi, I develop a Python-based drawing program, Whyteboard. I have tools that the user can create new shapes on the canvas, such as text/images/rectangles/circles/polygons. I also have a Select tool that allows the users to modify these shapes - for example, moving a shape's position, resizing, or editing polygon's points' positions. I'm adding in a new feature where moving or resizing a point near the canvas edge will automatically scroll the canvas. I think it's a good idea in terms of program usability, and annoys me when other program's don't have this feature. I've made some good progress on coding this; below is some Python code to demonstrate what I'm doing. These functions demonstrate how some shapes calculate their "edges": def find_edges(self): """A line.""" self.edges = {EDGE_TOP: min(self.y, self.y2), EDGE_RIGHT: max(self.x, self.x2), EDGE_BOTTOM: max(self.y, self.y2), EDGE_LEFT: min(self. x, self.x2)} def find_edges(self): """An image""" self.edges = {EDGE_TOP: self.y, EDGE_RIGHT: self.x + self.image.GetWidth(), EDGE_BOTTOM: self.y + self.image.GetWidth(), EDGE_LEFT: self.x} def find_edges(self): """Get the bounding rectangle for the polygon""" xmin = min(x for x, y in self.points) ymin = min(y for x, y in self.points) xmax = max(x for x, y in self.points) ymax = max(y for x, y in self.points) self.edges = {EDGE_TOP: ymin, EDGE_RIGHT: xmax, EDGE_BOTTOM: ymax, EDGE_LEFT: xmin} And here's the code I have so far to implement the scrolling when a shape nears the edge: def check_canvas_scroll(self, x, y, moving=False): """ We check that the x/y coords are within 50px from the edge of the canvas and scroll the canvas accordingly. If the shape is being moved, we need to check specific edges of the shape (e.g. left/right side of rectangle) """ size = self.board.GetClientSizeTuple() # visible area of the canvas if not self.board.area > size: # canvas is too small to need to scroll return start = self.board.GetViewStart() # user's starting "viewport" scroll = (-1, -1) # -1 means no change if moving: if self.shape.edges[EDGE_RIGHT] > start[0] + size[0] - 50: scroll = (start[0] + 5, -1) if self.shape.edges[EDGE_BOTTOM] > start[1] + size[1] - 50: scroll = (-1, start[1] + 5) # snip others else: if x > start[0] + size[0] - 50: scroll = (start[0] + 5, -1) if y > start[1] + size[1] - 50: scroll = (-1, start[1] + 5) # snip others self.board.Scroll(*scroll) This code actually works pretty well. If we're moving a shape, then we need to know its edges to calculate when they're coming close to the canvas edge. If we're resizing just a single point, then we just use the x/y coords of that point to see if it's close to the edge. The problem I'm having is a little tricky to describe - basically, if you move a shape to the left, and stop moving it, if you positioned the shape within the 50px from the canvas, then the next time you go to move the shape, the code that says "ok, is this shape close to the end?" gets triggered, and the canvas scrolls to the left, even if you're moving the shape to the right. Can anyone think on how to stop this? I created a youtube video to demonstrate the issue. At about 0:54, I move a polygon to the left of the canvas and position it there. The next time I move it, the canvas scrolls to the left even though I'm moving it right Another thing I'd like to add, but I'm stuck on is the scroll gaining momentum the longer a shape is scrolling? So, with a large canvas, you're not moving a shape for ages, moving 5px at a time, when you need to cover a 2000px distance. Any suggestions there? Thanks all - sorry for the super long question!

    Read the article

  • Need help with a possible memory management problem(leak) regarding NSMutableArray

    - by user309030
    Hi, I'm a beginner level programmer trying to make a game app for the iphone and I've encountered a possible issue with the memory management (exc_bad_access) of my program so far. I've searched and read dozens of articles regarding memory management (including apple's docs) but I still can't figure out what exactly is wrong with my codes. So I would really appreciate it if someone can help clear up the mess I made for myself. - (void)viewDidLoad { [super viewDidLoad]; self.gameState = gameStatePaused; fencePoleArray = [[NSMutableArray alloc] init]; fencePoleImageArray = [[NSMutableArray alloc] init]; fenceImageArray = [[NSMutableArray alloc] init]; mainField = CGRectMake(10, 35, 310, 340); .......... [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(gameLoop) userInfo:nil repeats:YES]; } So basically, the player touches the screen to set up the fences/poles -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if(.......) { ....... } else { UITouch *touch = [[event allTouches] anyObject]; currentTapLoc = [touch locationInView:touch.view]; NSLog(@"%i, %i", (int)currentTapLoc.x, (int)currentTapLoc.y); if(CGRectContainsPoint(mainField, currentTapLoc)) { if([self checkFence]) { onFencePole++; //this 3 set functions adds their respective objects into the 3 NSMutableArrays using addObject: [self setFencePole]; [self setFenceImage]; [self setFencePoleImage]; ....... } } else { ....... } } } } The setFence function (setFenceImage and setFencePoleImage is similar to this) -(void)setFencePole { Fence *fencePole; if (!elecFence) { fencePole = [[Fence alloc] initFence:onFencePole fenceType:1 fencePos:currentTapLoc]; } else { fencePole = [[Fence alloc] initFence:onFencePole fenceType:2 fencePos:currentTapLoc]; } [fencePoleArray addObject:fencePole]; [fencePole release]; and whenever I press a button in the game, endOpenState is called to clear away all the extra images(fence/poles) on the screen and also to remove all existing objects in the 3 NSMutableArray -(void)endOpenState { ........ int xMax = [fencePoleArray count]; int yMax = [fenceImageArray count]; for (int x = 0; x < xMax; x++) { [[fencePoleImageArray objectAtIndex:x] removeFromSuperview]; } for (int y = 0; y < yMax; y++) { [[fenceImageArray objectAtIndex:y] removeFromSuperview]; } [fencePoleArray removeAllObjects]; [fencePoleImageArray removeAllObjects]; [fenceImageArray removeAllObjects]; ........ } The crash happens here at the checkFence function. -(BOOL)checkFence { if (onFencePole == 0) { return YES; } else if (onFencePole >= 1 && onFencePole < currentMaxFencePole - 1) { CGPoint tempPoint1 = currentTapLoc; CGPoint tempPoint2 = [[fencePoleArray objectAtIndex:onFencePole-1] returnPos]; // the crash happens at this line if ([self checkDistance:tempPoint1 point2:tempPoint2]) { return YES; } else { return NO; } } else if (onFencePole == currentMaxFencePole - 1) { ...... } else { return NO; } } What I'm thinking of is that fencePoleArray got messed up when I used [fencePoleArray removeAllObjects] because it doesn't crash when I comment it out. It would really be great if someone can explain to me what went wrong. And thanks in advance.

    Read the article

  • Need help with a memory management problem in my game model

    - by user309030
    Hi, I'm a beginner level programmer trying to make a game app for the iphone and I've encountered a possible issue with the memory management (exc_bad_access) of my program so far. I've searched and read dozens of articles regarding memory management (including apple's docs) but I still can't figure out what exactly is wrong with my codes. So I would really appreciate it if someone can help clear up the mess I made for myself. //in the .h file @property(nonatomic,retain) NSMutableArray *fencePoleArray; @property(nonatomic,retain) NSMutableArray *fencePoleImageArray; @property(nonatomic,retain) NSMutableArray *fenceImageArray; //in the .m file - (void)viewDidLoad { [super viewDidLoad]; self.gameState = gameStatePaused; fencePoleArray = [[NSMutableArray alloc] init]; fencePoleImageArray = [[NSMutableArray alloc] init]; fenceImageArray = [[NSMutableArray alloc] init]; mainField = CGRectMake(10, 35, 310, 340); .......... [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(gameLoop) userInfo:nil repeats:YES]; } So basically, the player touches the screen to set up the fences/poles -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if(.......) { ....... } else { UITouch *touch = [[event allTouches] anyObject]; currentTapLoc = [touch locationInView:touch.view]; NSLog(@"%i, %i", (int)currentTapLoc.x, (int)currentTapLoc.y); if(CGRectContainsPoint(mainField, currentTapLoc)) { if([self checkFence]) { onFencePole++; //this 3 set functions adds their respective objects into the 3 NSMutableArrays using addObject: [self setFencePole]; [self setFenceImage]; [self setFencePoleImage]; ....... } } else { ....... } } } } The setFence function (setFenceImage and setFencePoleImage is similar to this) -(void)setFencePole { Fence *fencePole; if (!elecFence) { fencePole = [[Fence alloc] initFence:onFencePole fenceType:1 fencePos:currentTapLoc]; } else { fencePole = [[Fence alloc] initFence:onFencePole fenceType:2 fencePos:currentTapLoc]; } [fencePoleArray addObject:fencePole]; [fencePole release]; and whenever I press a button in the game, endOpenState is called to clear away all the extra images(fence/poles) on the screen and also to remove all existing objects in the 3 NSMutableArray. Point is to remove all the objects in the NSMutableArrays but keep the array itself so it can be reused later. -(void)endOpenState { ........ int xMax = [fencePoleArray count]; int yMax = [fenceImageArray count]; for (int x = 0; x < xMax; x++) { [[fencePoleImageArray objectAtIndex:x] removeFromSuperview]; } for (int y = 0; y < yMax; y++) { [[fenceImageArray objectAtIndex:y] removeFromSuperview]; } [fencePoleArray removeAllObjects]; [fencePoleImageArray removeAllObjects]; [fenceImageArray removeAllObjects]; ........ } The crash happens here at the checkFence function. -(BOOL)checkFence { if (onFencePole == 0) { return YES; } else if (onFencePole >= 1 && onFencePole < currentMaxFencePole - 1) { CGPoint tempPoint1 = currentTapLoc; CGPoint tempPoint2 = [[fencePoleArray objectAtIndex:onFencePole-1] returnPos]; // the crash happens at this line if ([self checkDistance:tempPoint1 point2:tempPoint2]) { return YES; } else { return NO; } } else if (onFencePole == currentMaxFencePole - 1) { ...... } else { return NO; } } So the problem here is, everything works fine until checkFence is called the 2nd time after endOpenState is called. So its like tap_screen - tap_screen - press_button_to_call_endOpenState - tap screen - tap_screen - crash What I'm thinking of is that fencePoleArray got messed up when I used [fencePoleArray removeAllObjects] because it doesn't crash when I comment it out. It would really be great if someone can explain to me what went wrong. And thanks in advance.

    Read the article

  • Android Bitmap: Collision Detecting

    - by Aekasitt Guruvanich
    I am writing an Android game right now and I would need some help in the collision of the Pawns on screen. I figured I could run a for loop on the Player class with all Pawn objects on the screen checking whether or not Width*Height intersects with each other, but is there a more efficient way to do this? And if you do it this way, many of the transparent pixel inside the rectangular area will also be considered as collision as well. Is there a way to check for collision between Bitmap on a Canvas that disregard transparent pixels? The class for player is below and the Pawn class uses the same method of display. Class Player { private Resources res; // Used for referencing Bitmap from predefined location private Bounds bounds; // Class that holds the boundary of the screen private Bitmap image; private float x, y; private Matrix position; private int width, height; private float velocity_x, velocity_y; public Player (Resources resources, Bounds boundary) { res = resources; bounds = boundary; image = BitmapFactory.decodeResource(res, R.drawable.player); width = image.getWidth(); height = image.getHeight(); position = new Matrix(); x = bounds.xMax / 2; // Initially puts the Player in the middle of screen y = bounds.yMax / 2; position.preTranslate(x,y); } public void draw(Canvas canvas) { canvas.drawBitmap(image, position, null); } }

    Read the article

  • Elusive race condition in Java

    - by nasufara
    I am creating a graphing calculator. In an attempt to squeeze some more performance out of it, I added some multithreaded to the line calculator. Essentially what my current implementation does is construct a thread-safe Queue of X values, then start however many threads it needs, each one calculating a point on the line using the queue to get its values, and then ordering the points using a HashMap when the calculations are done. This implementation works great, and that's not where my race condition is (merely some background info). In examining the performance results from this, I found that the HashMap is a performance bottleneck, since I do that synchronously on one thread. So I figured that ordering each point as its calculated would work best. I tried a PriorityQueue, but that was slower than the HashMap. I ended up creating an algorithm that essentially works like this: I construct a list of X values to calculate, like in my current algorithm. I then copy that list of values into another class, unimaginatively and temporarily named BlockingList, which is responsible for ordering the points as they are calculated. BlockingList contains a put() method, which takes in two BigDecimals as parameters, the first the X value, the second the calculated Y value. put() will only accept a value if the X value is the next one on the list to be accepted in the list of X values, and will block until another thread gives it the next excepted value. For example, since that can be confusing, say I have two threads, Thread-1 and Thread-2. Thread-2 gets the X value 10.0 from the values queue, and Thread-1 gets 9.0. However, Thread-1 completes its calculations first, and calls put() before Thread-2 does. Because BlockingList is expecting to get 10.0 first, and not 9.0, it will block on Thread-1 until Thread-2 finishes and calls put(). Once Thread-2 gives BlockingList 10.0, it notify()s all waiting threads, and expects 9.0 next. This continues until BlockingList gets all of its expected values. (I apologise if that was hard to follow, if you need more clarification, just ask.) As expected by the question title, there is a race condition in here. If I run it without any System.out.printlns, it will sometimes lock because of conflicting wait() and notifyAll()s, but if I put a println in, it will run great. A small implementation of this is included below, and exhibits the same behavior: import java.math.BigDecimal; import java.util.concurrent.ConcurrentLinkedQueue; public class Example { public static void main(String[] args) throws InterruptedException { // Various scaling values, determined based on the graph size // in the real implementation BigDecimal xMax = new BigDecimal(10); BigDecimal xStep = new BigDecimal(0.05); // Construct the values list, from -10 to 10 final ConcurrentLinkedQueue<BigDecimal> values = new ConcurrentLinkedQueue<BigDecimal>(); for (BigDecimal i = new BigDecimal(-10); i.compareTo(xMax) <= 0; i = i.add(xStep)) { values.add(i); } // Contains the calculated values final BlockingList list = new BlockingList(values); for (int i = 0; i < 4; i++) { new Thread() { public void run() { BigDecimal x; // Keep looping until there are no more values while ((x = values.poll()) != null) { PointPair pair = new PointPair(); pair.realX = x; try { list.put(pair); } catch (Exception ex) { ex.printStackTrace(); } } } }.start(); } } private static class PointPair { public BigDecimal realX; } private static class BlockingList { private final ConcurrentLinkedQueue<BigDecimal> _values; private final ConcurrentLinkedQueue<PointPair> _list = new ConcurrentLinkedQueue<PointPair>(); public BlockingList(ConcurrentLinkedQueue<BigDecimal> expectedValues) throws InterruptedException { // Copy the values into a new queue BigDecimal[] arr = expectedValues.toArray(new BigDecimal[0]); _values = new ConcurrentLinkedQueue<BigDecimal>(); for (BigDecimal dec : arr) { _values.add(dec); } } public void put(PointPair item) throws InterruptedException { while (item.realX.compareTo(_values.peek()) != 0) { synchronized (this) { // Block until someone enters the next desired value wait(); } } _list.add(item); _values.poll(); synchronized (this) { notifyAll(); } } } } My question is can anybody help me find the threading error? Thanks!

    Read the article

  • Scala n00b: Critique my code

    - by Peter
    G'day everyone, I'm a Scala n00b (but am experienced with other languages) and am learning the language as I find time - very much enjoying it so far! Usually when learning a new language the first thing I do is implement Conway's Game of Life, since it's just complex enough to give a good sense of the language, but small enough in scope to be able to whip up in a couple of hours (most of which is spent wrestling with syntax). Anyhoo, having gone through this exercise with Scala I was hoping the Scala gurus out there might take a look at the code I've ended up with and provide feedback on it. I'm after anything - algorithmic improvements (particularly concurrent solutions!), stylistic improvements, alternative APIs or language constructs, disgust at the length of my function names - whatever feedback you've got, I'm keen to hear it! You should be able to run the following script via "scala GameOfLife.scala" - by default it will run a 20x20 board with a single glider on it - please feel free to experiment. // CONWAY'S GAME OF LIFE (SCALA) abstract class GameOfLifeBoard(val aliveCells : Set[Tuple2[Int, Int]]) { // Executes a "time tick" - returns a new board containing the next generation def tick : GameOfLifeBoard // Is the board empty? def empty : Boolean = aliveCells.size == 0 // Is the given cell alive? protected def alive(cell : Tuple2[Int, Int]) : Boolean = aliveCells contains cell // Is the given cell dead? protected def dead(cell : Tuple2[Int, Int]) : Boolean = !alive(cell) } class InfiniteGameOfLifeBoard(aliveCells : Set[Tuple2[Int, Int]]) extends GameOfLifeBoard(aliveCells) { // Executes a "time tick" - returns a new board containing the next generation override def tick : GameOfLifeBoard = new InfiniteGameOfLifeBoard(nextGeneration) // The next generation of this board protected def nextGeneration : Set[Tuple2[Int, Int]] = aliveCells flatMap neighbours filter shouldCellLiveInNextGeneration // Should the given cell should live in the next generation? protected def shouldCellLiveInNextGeneration(cell : Tuple2[Int, Int]) : Boolean = (alive(cell) && (numberOfAliveNeighbours(cell) == 2 || numberOfAliveNeighbours(cell) == 3)) || (dead(cell) && numberOfAliveNeighbours(cell) == 3) // The number of alive neighbours for the given cell protected def numberOfAliveNeighbours(cell : Tuple2[Int, Int]) : Int = aliveNeighbours(cell) size // Returns the alive neighbours for the given cell protected def aliveNeighbours(cell : Tuple2[Int, Int]) : Set[Tuple2[Int, Int]] = aliveCells intersect neighbours(cell) // Returns all neighbours (whether dead or alive) for the given cell protected def neighbours(cell : Tuple2[Int, Int]) : Set[Tuple2[Int, Int]] = Set((cell._1-1, cell._2-1), (cell._1, cell._2-1), (cell._1+1, cell._2-1), (cell._1-1, cell._2), (cell._1+1, cell._2), (cell._1-1, cell._2+1), (cell._1, cell._2+1), (cell._1+1, cell._2+1)) // Information on where the currently live cells are protected def xVals = aliveCells map { cell => cell._1 } protected def xMin = (xVals reduceLeft (_ min _)) - 1 protected def xMax = (xVals reduceLeft (_ max _)) + 1 protected def xRange = xMin until xMax + 1 protected def yVals = aliveCells map { cell => cell._2 } protected def yMin = (yVals reduceLeft (_ min _)) - 1 protected def yMax = (yVals reduceLeft (_ max _)) + 1 protected def yRange = yMin until yMax + 1 // Returns a simple graphical representation of this board override def toString : String = { var result = "" for (y <- yRange) { for (x <- xRange) { if (alive (x,y)) result += "# " else result += ". " } result += "\n" } result } // Equality stuff override def equals(other : Any) : Boolean = { other match { case that : InfiniteGameOfLifeBoard => (that canEqual this) && that.aliveCells == this.aliveCells case _ => false } } def canEqual(other : Any) : Boolean = other.isInstanceOf[InfiniteGameOfLifeBoard] override def hashCode = aliveCells.hashCode } class FiniteGameOfLifeBoard(val boardWidth : Int, val boardHeight : Int, aliveCells : Set[Tuple2[Int, Int]]) extends InfiniteGameOfLifeBoard(aliveCells) { override def tick : GameOfLifeBoard = new FiniteGameOfLifeBoard(boardWidth, boardHeight, nextGeneration) // Determines the coordinates of all of the neighbours of the given cell override protected def neighbours(cell : Tuple2[Int, Int]) : Set[Tuple2[Int, Int]] = super.neighbours(cell) filter { cell => cell._1 >= 0 && cell._1 < boardWidth && cell._2 >= 0 && cell._2 < boardHeight } // Information on where the currently live cells are override protected def xRange = 0 until boardWidth override protected def yRange = 0 until boardHeight // Equality stuff override def equals(other : Any) : Boolean = { other match { case that : FiniteGameOfLifeBoard => (that canEqual this) && that.boardWidth == this.boardWidth && that.boardHeight == this.boardHeight && that.aliveCells == this.aliveCells case _ => false } } override def canEqual(other : Any) : Boolean = other.isInstanceOf[FiniteGameOfLifeBoard] override def hashCode : Int = { 41 * ( 41 * ( 41 + super.hashCode ) + boardHeight.hashCode ) + boardWidth.hashCode } } class GameOfLife(initialBoard: GameOfLifeBoard) { // Run the game of life until the board is empty or the exact same board is seen twice // Important note: this method does NOT necessarily terminate!! def go : Unit = { var currentBoard = initialBoard var previousBoards = List[GameOfLifeBoard]() while (!currentBoard.empty && !(previousBoards contains currentBoard)) { print(27.toChar + "[2J") // ANSI: clear screen print(27.toChar + "[;H") // ANSI: move cursor to top left corner of screen println(currentBoard.toString) Thread.sleep(75) // Warning: unbounded list concatenation can result in OutOfMemoryExceptions ####TODO: replace with LRU bounded list previousBoards = List(currentBoard) ::: previousBoards currentBoard = currentBoard tick } // Print the final board print(27.toChar + "[2J") // ANSI: clear screen print(27.toChar + "[;H") // ANSI: move cursor to top left corner of screen println(currentBoard.toString) } } // Script starts here val simple = Set((1,1)) val square = Set((4,4), (4,5), (5,4), (5,5)) val glider = Set((2,1), (3,2), (1,3), (2,3), (3,3)) val initialBoard = glider (new GameOfLife(new FiniteGameOfLifeBoard(20, 20, initialBoard))).go //(new GameOfLife(new InfiniteGameOfLifeBoard(initialBoard))).go // COPYRIGHT PETER MONKS 2010 Thanks! Peter

    Read the article

  • Video Synthesis - Making waves, patterns, gradients...

    - by Nathan
    I'm writing a program to generate some wild visuals. So far I can paint each pixel with a random blue value: for (y = 0; y < YMAX; y++) { for (x = 0; x < XMAX; x++) { b = rand() % 255; setPixelColor(x,y,r,g,b); } } I'd like to do more than just make blue noise, but I'm not sure where to start (Google isn't helping me much today), so it would be great if you could share anything you know on the subject or some links to related resources.

    Read the article

1 2  | Next Page >