Search Results

Search found 37 results on 2 pages for 'maxx'.

Page 1/2 | 1 2  | Next Page >

  • Draw a Custom cell for tableview ( uitableview ) , with changed colors and separator color and width

    - by Madhup
    Hi, I want to draw the background of a UITableViewCell which has a grouped style. The problem with me is I am not able to call the -(void)drawRect:(CGRect)rect or I think it should be called programmatically... I have taken code from following link . http://stackoverflow.com/questions/400965/how-to-customize-the-background-border-colors-of-a-grouped-table-view/1031593#1031593 // // CustomCellBackgroundView.h // // Created by Mike Akers on 11/21/08. // Copyright 2008 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> typedef enum { CustomCellBackgroundViewPositionTop, CustomCellBackgroundViewPositionMiddle, CustomCellBackgroundViewPositionBottom, CustomCellBackgroundViewPositionSingle } CustomCellBackgroundViewPosition; @interface CustomCellBackgroundView : UIView { UIColor *borderColor; UIColor *fillColor; CustomCellBackgroundViewPosition position; } @property(nonatomic, retain) UIColor *borderColor, *fillColor; @property(nonatomic) CustomCellBackgroundViewPosition position; @end // // CustomCellBackgroundView.m // // Created by Mike Akers on 11/21/08. // Copyright 2008 __MyCompanyName__. All rights reserved. // #import "CustomCellBackgroundView.h" static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth,float ovalHeight); @implementation CustomCellBackgroundView @synthesize borderColor, fillColor, position; - (BOOL) isOpaque { return NO; } - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { // Initialization code } return self; } - (void)drawRect:(CGRect)rect { // Drawing code CGContextRef c = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(c, [fillColor CGColor]); CGContextSetStrokeColorWithColor(c, [borderColor CGColor]); CGContextSetLineWidth(c, 2.0); if (position == CustomCellBackgroundViewPositionTop) { CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ; CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ; minx = minx + 1; miny = miny + 1; maxx = maxx - 1; maxy = maxy ; CGContextMoveToPoint(c, minx, maxy); CGContextAddArcToPoint(c, minx, miny, midx, miny, ROUND_SIZE); CGContextAddArcToPoint(c, maxx, miny, maxx, maxy, ROUND_SIZE); CGContextAddLineToPoint(c, maxx, maxy); // Close the path CGContextClosePath(c); // Fill & stroke the path CGContextDrawPath(c, kCGPathFillStroke); return; } else if (position == CustomCellBackgroundViewPositionBottom) { CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ; CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ; minx = minx + 1; miny = miny ; maxx = maxx - 1; maxy = maxy - 1; CGContextMoveToPoint(c, minx, miny); CGContextAddArcToPoint(c, minx, maxy, midx, maxy, ROUND_SIZE); CGContextAddArcToPoint(c, maxx, maxy, maxx, miny, ROUND_SIZE); CGContextAddLineToPoint(c, maxx, miny); // Close the path CGContextClosePath(c); // Fill & stroke the path CGContextDrawPath(c, kCGPathFillStroke); return; } else if (position == CustomCellBackgroundViewPositionMiddle) { CGFloat minx = CGRectGetMinX(rect) , maxx = CGRectGetMaxX(rect) ; CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ; minx = minx + 1; miny = miny ; maxx = maxx - 1; maxy = maxy ; CGContextMoveToPoint(c, minx, miny); CGContextAddLineToPoint(c, maxx, miny); CGContextAddLineToPoint(c, maxx, maxy); CGContextAddLineToPoint(c, minx, maxy); CGContextClosePath(c); // Fill & stroke the path CGContextDrawPath(c, kCGPathFillStroke); return; } else if (position == CustomCellBackgroundViewPositionSingle) { CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ; CGFloat miny = CGRectGetMinY(rect) , midy = CGRectGetMidY(rect) , maxy = CGRectGetMaxY(rect) ; minx = minx + 1; miny = miny + 1; maxx = maxx - 1; maxy = maxy - 1; CGContextMoveToPoint(c, minx, midy); CGContextAddArcToPoint(c, minx, miny, midx, miny, ROUND_SIZE); CGContextAddArcToPoint(c, maxx, miny, maxx, midy, ROUND_SIZE); CGContextAddArcToPoint(c, maxx, maxy, midx, maxy, ROUND_SIZE); CGContextAddArcToPoint(c, minx, maxy, minx, midy, ROUND_SIZE); // Close the path CGContextClosePath(c); // Fill & stroke the path CGContextDrawPath(c, kCGPathFillStroke); return; } } - (void)dealloc { [borderColor release]; [fillColor release]; [super dealloc]; } @end static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth,float ovalHeight) { float fw, fh; if (ovalWidth == 0 || ovalHeight == 0) {// 1 CGContextAddRect(context, rect); return; } CGContextSaveGState(context);// 2 CGContextTranslateCTM (context, CGRectGetMinX(rect),// 3 CGRectGetMinY(rect)); CGContextScaleCTM (context, ovalWidth, ovalHeight);// 4 fw = CGRectGetWidth (rect) / ovalWidth;// 5 fh = CGRectGetHeight (rect) / ovalHeight;// 6 CGContextMoveToPoint(context, fw, fh/2); // 7 CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);// 8 CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);// 9 CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);// 10 CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // 11 CGContextClosePath(context);// 12 CGContextRestoreGState(context);// 13 } but the problem is my drawRect is not getting called automatically......... I am doing it like this. CustomCellBackgroundView *custView = [[CustomCellBackgroundView alloc] initWithFrame:CGRectMake(0,0,320,44)]; [cell setBackgroundView:custView]; [custView release]; and doing this gives me transparent cell. I tried and fought with code but could get any results. Please help me out. I am really having no idea how this code will run.

    Read the article

  • Can I get the Waves Maxx speaker effects to work in Ubuntu?

    - by Rafael
    I have a new machine that comes with JBL 2.1 Speakers with Waves Maxx Audio 3. On Windows it sounds perfect, though in Ubuntu 12.04 I get cheap/sound with simple mp3 files. I have tried a few things on different blogs but no luck so far. Any ideas? aplay -l **** List of PLAYBACK Hardware Devices **** card 0: PCH [HDA Intel PCH], device 0: ALC665 Analog [ALC665 Analog] Subdevices: 1/1 Subdevice #0: subdevice #0 card 0: PCH [HDA Intel PCH], device 1: ALC665 Digital [ALC665 Digital] Subdevices: 1/1 Subdevice #0: subdevice #0 card 0: PCH [HDA Intel PCH], device 3: HDMI 0 [HDMI 0] Subdevices: 1/1 Subdevice #0: subdevice #0 card 1: N700 [Logitech Speaker Lapdesk N700], device 0: USB Audio [USB Audio] Subdevices: 1/1 Subdevice #0: subdevice #0

    Read the article

  • onDraw() triggered but results don't show

    - by Don
    I have the following routine in a subclass of view: It calculates an array of points that make up a line, then erases the previous lines, then draws the new lines (impact refers to the width in pixels drawn with multiple lines). The line is your basic bell curve, squeezed or stretched by variance and x-factor. Unfortunately, nothing shows on the screen. A previous version with drawPoint() and no array worked, and I've verified the array contents are being loaded correctly, and I can see that my onDraw() is being triggered. Any ideas why it might not be drawn? Thanks in advance! protected void drawNewLine( int maxx, int maxy, Canvas canvas, int impact, double variance, double xFactor, int color) { // impact = 2 to 8; xFactor between 4 and 20; variance between 0.2 and 5 double x = 0; double y = 0; int cx = maxx / 2; int cy = maxy / 2; int mu = cx; int index = 0; points[maxx<<1][1] = points[maxx<<1][0]; for (x = 0; x < maxx; x++) { points[index][1] = points[index][0]; points[index][0] = (float) x; Log.i(DEBUG_TAG, "x: " + x); index++; double root = 1.0 / (Math.sqrt(2 * Math.PI * variance)); double exponent = -1.0 * (Math.pow(((x - mu)/maxx*xFactor), 2) / (2 * variance)); double ePow = Math.exp(exponent); y = Math.round(cy * root * ePow); points[index][1] = points[index][0]; points[index][0] = (float) (maxy - y - OFFSET); index++; } points[maxx<<1][0] = (float) impact; for (int line = 0; line < points[maxx<<1][1]; line++) { for (int pt = 0; pt < (maxx<<1); pt++) { pointsToPaint[pt] = points[pt][1]; } for (int skip = 1; skip < (maxx<<1); skip = skip + 2) pointsToPaint[skip] = pointsToPaint[skip] + line; myLinePaint.setColor(Color.BLACK); canvas.drawLines(pointsToPaint, bLinePaint); // draw over old lines w/blk } for (int line = 0; line < points[maxx<<1][0]; line++) { for (int pt = 0; pt < maxx<<1; pt++) { pointsToPaint[pt] = points[pt][0]; } for (int skip = 1; skip < maxx<<1; skip = skip + 2) pointsToPaint[skip] = pointsToPaint[skip] + line; myLinePaint.setColor(color); canvas.drawLines(pointsToPaint, myLinePaint); / new color } } update: Replaced the drawLines() with drawPoint() in loop, still no joy for (int p = 0; p<pointsToPaint.length; p = p + 2) { Log.i(DEBUG_TAG, "x " + pointsToPaint[p] + " y " + pointsToPaint[p+1]); canvas.drawPoint(pointsToPaint[p], pointsToPaint[p+1], myLinePaint); } /// canvas.drawLines(pointsToPaint, myLinePaint);

    Read the article

  • CSM shadow errors when models are split

    - by KaiserJohaan
    I'm getting closer to fixing CSM, but there seems to be one more issue at hand. At certain angles, the models will be caught/split between two shadow map cascades, like below. first depth split second depth split - here you can see the model is caught between the splits How does one fix this? Increase the overlapping boundaries between the splits? Or is the frustrum erronous? CameraFrustrum CalculateCameraFrustrum(const float fovDegrees, const float aspectRatio, const float minDist, const float maxDist, const Mat4& cameraViewMatrix, Mat4& outFrustrumMat) { CameraFrustrum ret = { Vec4(1.0f, -1.0f, 0.0f, 1.0f), Vec4(1.0f, 1.0f, 0.0f, 1.0f), Vec4(-1.0f, 1.0f, 0.0f, 1.0f), Vec4(-1.0f, -1.0f, 0.0f, 1.0f), Vec4(1.0f, -1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f), Vec4(-1.0f, 1.0f, 1.0f, 1.0f), Vec4(-1.0f, -1.0f, 1.0f, 1.0f), }; const Mat4 perspectiveMatrix = PerspectiveMatrixFov(fovDegrees, aspectRatio, minDist, maxDist); const Mat4 invMVP = glm::inverse(perspectiveMatrix * cameraViewMatrix); outFrustrumMat = invMVP; for (Vec4& corner : ret) { corner = invMVP * corner; corner /= corner.w; } return ret; } Mat4 CreateDirLightVPMatrix(const CameraFrustrum& cameraFrustrum, const Vec3& lightDir) { Mat4 lightViewMatrix = glm::lookAt(Vec3(0.0f), -glm::normalize(lightDir), Vec3(0.0f, -1.0f, 0.0f)); Vec4 transf = lightViewMatrix * cameraFrustrum[0]; float maxZ = transf.z, minZ = transf.z; float maxX = transf.x, minX = transf.x; float maxY = transf.y, minY = transf.y; for (uint32_t i = 1; i < 8; i++) { transf = lightViewMatrix * cameraFrustrum[i]; if (transf.z > maxZ) maxZ = transf.z; if (transf.z < minZ) minZ = transf.z; if (transf.x > maxX) maxX = transf.x; if (transf.x < minX) minX = transf.x; if (transf.y > maxY) maxY = transf.y; if (transf.y < minY) minY = transf.y; } Mat4 viewMatrix(lightViewMatrix); viewMatrix[3][0] = -(minX + maxX) * 0.5f; viewMatrix[3][1] = -(minY + maxY) * 0.5f; viewMatrix[3][2] = -(minZ + maxZ) * 0.5f; viewMatrix[0][3] = 0.0f; viewMatrix[1][3] = 0.0f; viewMatrix[2][3] = 0.0f; viewMatrix[3][3] = 1.0f; Vec3 halfExtents((maxX - minX) * 0.5, (maxY - minY) * 0.5, (maxZ - minZ) * 0.5); return OrthographicMatrix(-halfExtents.x, halfExtents.x, halfExtents.y, -halfExtents.y, halfExtents.z, -halfExtents.z) * viewMatrix; }

    Read the article

  • Where i set touch effect when a spawn Srite are comming on the screen?

    - by shihab_returns
    I just create a scene where create a spawn spirit that comes from above screen height in Landscape mode. Now i want to remove spirits when i touch on it. I tried but seems the code not works and crashed also after a while. here is my code: /** TimerHandler for collision detection and cleaning up */ IUpdateHandler detect = new IUpdateHandler() { @Override public void reset() { } @Override public void onUpdate(float pSecondsElapsed) { Iterator<AnimatedSprite> targets = targetLL.iterator(); AnimatedSprite _target; while (targets.hasNext()) { _target = targets.next(); if (_target.getY() >= cameraHeight) { // removeSprite(_target, targets); tPool.recyclePoolItem(_target); targets.remove(); Log.d("ok", "---------Looop Inside-----"); // fail(); break; } } targetLL.addAll(TargetsToBeAdded); TargetsToBeAdded.clear(); } }; /** adds a target at a random location and let it move along the y-axis */ public void addTarget() { Random rand = new Random(); int minX = mTargetTextureRegion.getWidth(); int maxX = (int) (mCamera.getWidth() - mTargetTextureRegion.getWidth()); int rangeX = maxX - minX; Log.d("----point----", "minX:" + minX + "maxX:" + maxX + "rangeX:" + rangeX); int rX = rand.nextInt(rangeX) + minX; int rY = (int) mCamera.getHeight() + mTargetTextureRegion.getHeight(); Log.d("---Random x----", "Random x" + rX + "Random y" + rY); target = tPool.obtainPoolItem(); target.setPosition(rX, rY); target.animate(100); mMainScene.attachChild(target, 1); mMainScene.registerTouchArea(target); int minDuration = 2; int maxDuration = 32; int rangeDuration = maxDuration - minDuration; int actualDuration = rand.nextInt(rangeDuration) + minDuration; // MoveXModifier mod = new MoveXModifier(actualDuration, target.getX(), // -target.getWidth()); MoveYModifier mody = new MoveYModifier(actualDuration, -target.getHeight(), cameraHeight + 10); target.registerEntityModifier(mody.deepCopy()); TargetsToBeAdded.add(target); } @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if (pTouchArea == target) { Toast.makeText(getApplicationContext(), "Yoooooooo", Toast.LENGTH_LONG).show(); } return true; } ** My question is where i implements IOnAreaTouchListener in My code. ? ** Thanks in Advance.

    Read the article

  • CSM DX11 issues

    - by KaiserJohaan
    I got CSM to work in OpenGL, and now Im trying to do the same in directx. I'm using the same math library and all and I'm pretty much using the alghorithm straight off. I am using right-handed, column major matrices from GLM. The light is looking (-1, -1, -1). The problem I have is twofolds; For some reason, the ground floor is causing alot of (false) shadow artifacts, like the vast shadowed area you see. I confirmed this when I disabled the ground for the depth pass, but thats a hack more than anything else The shadows are inverted compared to the shadowmap. If you squint you can see the chairs shadows should be mirrored instead. This is the first cascade shadow map, in range of the alien and the chair: I can't figure out why this is. This is the depth pass: for (uint32_t cascadeIndex = 0; cascadeIndex < NUM_SHADOWMAP_CASCADES; cascadeIndex++) { mShadowmap.BindDepthView(context, cascadeIndex); CameraFrustrum cameraFrustrum = CalculateCameraFrustrum(degreesFOV, aspectRatio, nearDistArr[cascadeIndex], farDistArr[cascadeIndex], cameraViewMatrix); lightVPMatrices[cascadeIndex] = CreateDirLightVPMatrix(cameraFrustrum, lightDir); mVertexTransformPass.RenderMeshes(context, renderQueue, meshes, lightVPMatrices[cascadeIndex]); lightVPMatrices[cascadeIndex] = gBiasMatrix * lightVPMatrices[cascadeIndex]; farDistArr[cascadeIndex] = -farDistArr[cascadeIndex]; } CameraFrustrum CalculateCameraFrustrum(const float fovDegrees, const float aspectRatio, const float minDist, const float maxDist, const Mat4& cameraViewMatrix) { CameraFrustrum ret = { Vec4(1.0f, 1.0f, -1.0f, 1.0f), Vec4(1.0f, -1.0f, -1.0f, 1.0f), Vec4(-1.0f, -1.0f, -1.0f, 1.0f), Vec4(-1.0f, 1.0f, -1.0f, 1.0f), Vec4(1.0f, -1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f), Vec4(-1.0f, 1.0f, 1.0f, 1.0f), Vec4(-1.0f, -1.0f, 1.0f, 1.0f), }; const Mat4 perspectiveMatrix = PerspectiveMatrixFov(fovDegrees, aspectRatio, minDist, maxDist); const Mat4 invMVP = glm::inverse(perspectiveMatrix * cameraViewMatrix); for (Vec4& corner : ret) { corner = invMVP * corner; corner /= corner.w; } return ret; } Mat4 CreateDirLightVPMatrix(const CameraFrustrum& cameraFrustrum, const Vec3& lightDir) { Mat4 lightViewMatrix = glm::lookAt(Vec3(0.0f), -glm::normalize(lightDir), Vec3(0.0f, -1.0f, 0.0f)); Vec4 transf = lightViewMatrix * cameraFrustrum[0]; float maxZ = transf.z, minZ = transf.z; float maxX = transf.x, minX = transf.x; float maxY = transf.y, minY = transf.y; for (uint32_t i = 1; i < 8; i++) { transf = lightViewMatrix * cameraFrustrum[i]; if (transf.z > maxZ) maxZ = transf.z; if (transf.z < minZ) minZ = transf.z; if (transf.x > maxX) maxX = transf.x; if (transf.x < minX) minX = transf.x; if (transf.y > maxY) maxY = transf.y; if (transf.y < minY) minY = transf.y; } Mat4 viewMatrix(lightViewMatrix); viewMatrix[3][0] = -(minX + maxX) * 0.5f; viewMatrix[3][1] = -(minY + maxY) * 0.5f; viewMatrix[3][2] = -(minZ + maxZ) * 0.5f; viewMatrix[0][3] = 0.0f; viewMatrix[1][3] = 0.0f; viewMatrix[2][3] = 0.0f; viewMatrix[3][3] = 1.0f; Vec3 halfExtents((maxX - minX) * 0.5, (maxY - minY) * 0.5, (maxZ - minZ) * 0.5); return OrthographicMatrix(-halfExtents.x, halfExtents.x, -halfExtents.y, halfExtents.y, halfExtents.z, -halfExtents.z) * viewMatrix; } And this is the pixel shader used for the lighting stage: #define DEPTH_BIAS 0.0005 #define NUM_CASCADES 4 cbuffer DirectionalLightConstants : register(CBUFFER_REGISTER_PIXEL) { float4x4 gSplitVPMatrices[NUM_CASCADES]; float4x4 gCameraViewMatrix; float4 gSplitDistances; float4 gLightColor; float4 gLightDirection; }; Texture2D gPositionTexture : register(TEXTURE_REGISTER_POSITION); Texture2D gDiffuseTexture : register(TEXTURE_REGISTER_DIFFUSE); Texture2D gNormalTexture : register(TEXTURE_REGISTER_NORMAL); Texture2DArray gShadowmap : register(TEXTURE_REGISTER_DEPTH); SamplerComparisonState gShadowmapSampler : register(SAMPLER_REGISTER_DEPTH); float4 ps_main(float4 position : SV_Position) : SV_Target0 { float4 worldPos = gPositionTexture[uint2(position.xy)]; float4 diffuse = gDiffuseTexture[uint2(position.xy)]; float4 normal = gNormalTexture[uint2(position.xy)]; float4 camPos = mul(gCameraViewMatrix, worldPos); uint index = 3; if (camPos.z > gSplitDistances.x) index = 0; else if (camPos.z > gSplitDistances.y) index = 1; else if (camPos.z > gSplitDistances.z) index = 2; float3 projCoords = (float3)mul(gSplitVPMatrices[index], worldPos); float viewDepth = projCoords.z - DEPTH_BIAS; projCoords.z = float(index); float visibilty = gShadowmap.SampleCmpLevelZero(gShadowmapSampler, projCoords, viewDepth); float angleNormal = clamp(dot(normal, gLightDirection), 0, 1); return visibilty * diffuse * angleNormal * gLightColor; } As you can see I am using depth bias and a bias matrix. Any hints on why this behaves so wierdly?

    Read the article

  • Best algorithm for recursive adjacent tiles?

    - by OhMrBigshot
    In my game I have a set of tiles placed in a 2D array marked by their Xs and Zs ([1,1],[1,2], etc). Now, I want a sort of "Paint Bucket" mechanism: Selecting a tile will destroy all adjacent tiles until a condition stops it, let's say, if it hits an object with hasFlag. Here's what I have so far, I'm sure it's pretty bad, it also freezes everything sometimes: void destroyAdjacentTiles(int x, int z) { int GridSize = Cubes.GetLength(0); int minX = x == 0 ? x : x-1; int maxX = x == GridSize - 1 ? x : x+1; int minZ = z == 0 ? z : z-1; int maxZ = z == GridSize - 1 ? z : z+1; Debug.Log(string.Format("Cube: {0}, {1}; X {2}-{3}; Z {4}-{5}", x, z, minX, maxX, minZ, maxZ)); for (int curX = minX; curX <= maxX; curX++) { for (int curZ = minZ; curZ <= maxZ; curZ++) { if (Cubes[curX, curZ] != Cubes[x, z]) { Debug.Log(string.Format(" Checking: {0}, {1}", curX, curZ)); if (Cubes[curX,curZ] && Cubes[curX,curZ].GetComponent<CubeBehavior>().hasFlag) { Destroy(Cubes[curX,curZ]); destroyAdjacentTiles(curX, curZ); } } } } }

    Read the article

  • XNA - Finding boundaries in isometric tilemap

    - by Yheeky
    I have an issue with my 2D isometric engine. I'm using my own 2D camera class which works with matrices and need to find the tilemaps boundaries so the user always sees the map. Currently my map size is 100x100 (with 128x128 tiles) so the calculation (e.g. for the right boundary) is: var maxX = (TileMap.MapWidth + 1) * (TileMap.TileWidth / 2) - ViewSize.X; var maxX = (100 + 1) * (128 / 2) - 1360; // = 5104 pixels. This works fine while having scale factor of 1.0f but not for any other zoom factor. When I zoom out to 0.9f the right border should be at approx. 4954. I´m using the following code for transformation but I always get a wrong value: var maxXVector = new Vector2(maxX, 0); var maxXTransformed = Vector2.Transform(maxXVector, tempTransform).X; The result is 4593. Does anyone of you have an idea what I´m during wrong? Thanks for your help! Yheeky

    Read the article

  • Add shadow to UIImage drawn in rounded path

    - by Tom Irving
    I'm drawing a rounded image in a UITableView cell like so: CGRect imageRect = CGRectMake(8, 8, 40, 40); CGFloat radius = 3; CGFloat minx = CGRectGetMinX(imageRect); CGFloat midx = CGRectGetMidX(imageRect); CGFloat maxx = CGRectGetMaxX(imageRect); CGFloat miny = CGRectGetMinY(imageRect); CGFloat midy = CGRectGetMidY(imageRect); CGFloat maxy = CGRectGetMaxY(imageRect); CGContextMoveToPoint(context, minx, midy); CGContextAddArcToPoint(context, minx, miny, midx, miny, radius); CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius); CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius); CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius); CGContextClosePath(context); CGContextClip(context); [self.theImage drawInRect:imageRect]; This looks great, but I'd like to add a shadow to it for added effect. I've tried using something along the lines of: CGContextSetShadowWithColor(context, CGSizeMake(2, 2), 2, [[UIColor grayColor] CGColor]); CGContextFillPath(context); But this only works when the image has transparent areas, if the image isn't transparent at all, it won't even draw a shadow around the border. I'm wondering if there is something I'm doing wrong?

    Read the article

  • Windows Screensaver Multi Monitor Problem

    - by Bryan
    I have a simple screensaver that I've written, which has been deployed to all of our company's client PCs. As most of our PCs have dual monitors, I took care to ensure that the screensaver ran on both displays. This works fine, however on some systems, where the primary screen has been swapped (to the left monitor), the screensaver only works on the left (primary) screen. The offending code is below. Can anyone see anything I've done wrong, or a better way of handling this? For info, the context of "this", is the screensaver form itself. // Make form full screen and on top of all other forms int minY = 0; int maxY = 0; int maxX = 0; int minX = 0; foreach (Screen screen in Screen.AllScreens) { // Find the bounds of all screens attached to the system if (screen.Bounds.Left < minX) minX = screen.Bounds.Left; if (screen.Bounds.Width > maxX) maxX = screen.Bounds.Width; if (screen.Bounds.Bottom < minY) minY = screen.Bounds.Bottom; if (screen.Bounds.Height > maxY) maxY = screen.Bounds.Height; } // Set the location and size of the form, so that it // fills the bounds of all screens attached to the system Location = new Point(minX, minY); Height = maxY - minY; Width = maxX - minX; Cursor.Hide(); TopMost = true;

    Read the article

  • Converting 2D Physics to 3D.

    - by static void main
    I'm new to game physics and I am trying to adapt a simple 2D ball simulation for a 3D simulation with the Java3D library. I have this problem: Two things: 1) I noted down the values generated by the engine: X/Y are too high and minX/minY/maxY/maxX values are causing trouble. Sometimes the balls are drawing but not moving Sometimes they are going out of the panel Sometimes they're moving on little area Sometimes they just stick at one place... 2) I'm unable to select/define/set the default correct/suitable values considering the 3D graphics scaling/resolution while they are set with respect to 2D screen coordinates, that is my only problem. Please help. This is the code: public class Ball extends GameObject { private float x, y; // Ball's center (x, y) private float speedX, speedY; // Ball's speed per step in x and y private float radius; // Ball's radius // Collision detected by collision detection and response algorithm? boolean collisionDetected = false; // If collision detected, the next state of the ball. // Otherwise, meaningless. private float nextX, nextY; private float nextSpeedX, nextSpeedY; private static final float BOX_WIDTH = 640; private static final float BOX_HEIGHT = 480; /** * Constructor The velocity is specified in polar coordinates of speed and * moveAngle (for user friendliness), in Graphics coordinates with an * inverted y-axis. */ public Ball(String name1,float x, float y, float radius, float speed, float angleInDegree, Color color) { this.x = x; this.y = y; // Convert velocity from polar to rectangular x and y. this.speedX = speed * (float) Math.cos(Math.toRadians(angleInDegree)); this.speedY = speed * (float) Math.sin(Math.toRadians(angleInDegree)); this.radius = radius; } public void move() { if (collisionDetected) { // Collision detected, use the values computed. x = nextX; y = nextY; speedX = nextSpeedX; speedY = nextSpeedY; } else { // No collision, move one step and no change in speed. x += speedX; y += speedY; } collisionDetected = false; // Clear the flag for the next step } public void collideWith() { // Get the ball's bounds, offset by the radius of the ball float minX = 0.0f + radius; float minY = 0.0f + radius; float maxX = 0.0f + BOX_WIDTH - 1.0f - radius; float maxY = 0.0f + BOX_HEIGHT - 1.0f - radius; double gravAmount = 0.9811111f; double gravDir = (90 / 57.2960285258); // Try moving one full step nextX = x + speedX; nextY = y + speedY; System.out.println("In serializedBall in collision."); // If collision detected. Reflect on the x or/and y axis // and place the ball at the point of impact. if (speedX != 0) { if (nextX > maxX) { // Check maximum-X bound collisionDetected = true; nextSpeedX = -speedX; // Reflect nextSpeedY = speedY; // Same nextX = maxX; nextY = (maxX - x) * speedY / speedX + y; // speedX non-zero } else if (nextX < minX) { // Check minimum-X bound collisionDetected = true; nextSpeedX = -speedX; // Reflect nextSpeedY = speedY; // Same nextX = minX; nextY = (minX - x) * speedY / speedX + y; // speedX non-zero } } // In case the ball runs over both the borders. if (speedY != 0) { if (nextY > maxY) { // Check maximum-Y bound collisionDetected = true; nextSpeedX = speedX; // Same nextSpeedY = -speedY; // Reflect nextY = maxY; nextX = (maxY - y) * speedX / speedY + x; // speedY non-zero } else if (nextY < minY) { // Check minimum-Y bound collisionDetected = true; nextSpeedX = speedX; // Same nextSpeedY = -speedY; // Reflect nextY = minY; nextX = (minY - y) * speedX / speedY + x; // speedY non-zero } } speedX += Math.cos(gravDir) * gravAmount; speedY += Math.sin(gravDir) * gravAmount; } public float getSpeed() { return (float) Math.sqrt(speedX * speedX + speedY * speedY); } public float getMoveAngle() { return (float) Math.toDegrees(Math.atan2(speedY, speedX)); } public float getRadius() { return radius; } public float getX() { return x; } public float getY() { return y; } public void setX(float f) { x = f; } public void setY(float f) { y = f; } } Here's how I'm drawing the balls: public class 3DMovingBodies extends Applet implements Runnable { private static final int BOX_WIDTH = 800; private static final int BOX_HEIGHT = 600; private int currentNumBalls = 1; // number currently active private volatile boolean playing; private long mFrameDelay; private JFrame frame; private int currentFrameRate; private Ball[] ball = new Ball[currentNumBalls]; private Random rand; private Sphere[] sphere = new Sphere[currentNumBalls]; private Transform3D[] trans = new Transform3D[currentNumBalls]; private TransformGroup[] objTrans = new TransformGroup[currentNumBalls]; public 3DMovingBodies() { rand = new Random(); float angleInDegree = rand.nextInt(360); setLayout(new BorderLayout()); GraphicsConfiguration config = SimpleUniverse .getPreferredConfiguration(); Canvas3D c = new Canvas3D(config); add("Center", c); ball[0] = new Ball(0.5f, 0.0f, 0.5f, 0.4f, angleInDegree, Color.yellow); // ball[1] = new Ball(1.0f, 0.0f, 0.25f, 0.8f, angleInDegree, // Color.yellow); // ball[2] = new Ball(0.0f, 1.0f, 0.15f, 0.11f, angleInDegree, // Color.yellow); trans[0] = new Transform3D(); // trans[1] = new Transform3D(); // trans[2] = new Transform3D(); sphere[0] = new Sphere(0.5f); // sphere[1] = new Sphere(0.25f); // sphere[2] = new Sphere(0.15f); // Create a simple scene and attach it to the virtual universe BranchGroup scene = createSceneGraph(); SimpleUniverse u = new SimpleUniverse(c); u.getViewingPlatform().setNominalViewingTransform(); u.addBranchGraph(scene); startSimulation(); } public BranchGroup createSceneGraph() { // Create the root of the branch graph BranchGroup objRoot = new BranchGroup(); for (int i = 0; i < currentNumBalls; i++) { // Create a simple shape leaf node, add it to the scene graph. objTrans[i] = new TransformGroup(); objTrans[i].setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); Transform3D pos1 = new Transform3D(); pos1.setTranslation(randomPos()); objTrans[i].setTransform(pos1); objTrans[i].addChild(sphere[i]); objRoot.addChild(objTrans[i]); } BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); Color3f light1Color = new Color3f(1.0f, 0.0f, 0.2f); Vector3f light1Direction = new Vector3f(4.0f, -7.0f, -12.0f); DirectionalLight light1 = new DirectionalLight(light1Color, light1Direction); light1.setInfluencingBounds(bounds); objRoot.addChild(light1); // Set up the ambient light Color3f ambientColor = new Color3f(1.0f, 1.0f, 1.0f); AmbientLight ambientLightNode = new AmbientLight(ambientColor); ambientLightNode.setInfluencingBounds(bounds); objRoot.addChild(ambientLightNode); return objRoot; } public void startSimulation() { playing = true; Thread t = new Thread(this); t.start(); } public void stop() { playing = false; } public void run() { long previousTime = System.currentTimeMillis(); long currentTime = previousTime; long elapsedTime; long totalElapsedTime = 0; int frameCount = 0; while (true) { currentTime = System.currentTimeMillis(); elapsedTime = (currentTime - previousTime); // elapsed time in // seconds totalElapsedTime += elapsedTime; if (totalElapsedTime > 1000) { currentFrameRate = frameCount; frameCount = 0; totalElapsedTime = 0; } for (int i = 0; i < currentNumBalls; i++) { ball[i].move(); ball[i].collideWith(); drawworld(); } try { Thread.sleep(88); } catch (Exception e) { e.printStackTrace(); } previousTime = currentTime; frameCount++; } } public void drawworld() { for (int i = 0; i < currentNumBalls; i++) { printTG(objTrans[i], "SteerTG"); trans[i].setTranslation(new Vector3f(ball[i].getX(), ball[i].getY(), 0.0f)); objTrans[i].setTransform(trans[i]); } } private Vector3f randomPos() /* * Return a random position vector. The numbers are hardwired to be within * the confines of the box. */ { Vector3f pos = new Vector3f(); pos.x = rand.nextFloat() * 5.0f - 2.5f; // -2.5 to 2.5 pos.y = rand.nextFloat() * 2.0f + 0.5f; // 0.5 to 2.5 pos.z = rand.nextFloat() * 5.0f - 2.5f; // -2.5 to 2.5 return pos; } // end of randomPos() public static void main(String[] args) { System.out.println("Program Started"); 3DMovingBodiesbb = new 3DMovingBodies(); bb.addKeyListener(bb); MainFrame mf = new MainFrame(bb, 600, 400); } }

    Read the article

  • Applications: The Mathematics of Movement, Part 3

    - by TechTwaddle
    Previously: Part 1, Part 2 As promised in the previous post, this post will cover two variations of the marble move program. The first one, Infinite Move, keeps the marble moving towards the click point, rebounding it off the screen edges and changing its direction when the user clicks again. The second version, Finite Move, is the same as first except that the marble does not move forever. It moves towards the click point, rebounds off the screen edges and slowly comes to rest. The amount of time that it moves depends on the distance between the click point and marble. Infinite Move This case is simple (actually both cases are simple). In this case all we need is the direction information which is exactly what the unit vector stores. So when the user clicks, you calculate the unit vector towards the click point and then keep updating the marbles position like crazy. And, of course, there is no stop condition. There’s a little more additional code in the bounds checking conditions. Whenever the marble goes off the screen boundaries, we need to reverse its direction.  Here is the code for mouse up event and UpdatePosition() method, //stores the unit vector double unitX = 0, unitY = 0; double speed = 6; //speed times the unit vector double incrX = 0, incrY = 0; private void Form1_MouseUp(object sender, MouseEventArgs e) {     double x = e.X - marble1.x;     double y = e.Y - marble1.y;     //calculate distance between click point and current marble position     double lenSqrd = x * x + y * y;     double len = Math.Sqrt(lenSqrd);     //unit vector along the same direction (from marble towards click point)     unitX = x / len;     unitY = y / len;     timer1.Enabled = true; } private void UpdatePosition() {     //amount by which to increment marble position     incrX = speed * unitX;     incrY = speed * unitY;     marble1.x += incrX;     marble1.y += incrY;     //check for bounds     if ((int)marble1.x < MinX + marbleWidth / 2)     {         marble1.x = MinX + marbleWidth / 2;         unitX *= -1;     }     else if ((int)marble1.x > (MaxX - marbleWidth / 2))     {         marble1.x = MaxX - marbleWidth / 2;         unitX *= -1;     }     if ((int)marble1.y < MinY + marbleHeight / 2)     {         marble1.y = MinY + marbleHeight / 2;         unitY *= -1;     }     else if ((int)marble1.y > (MaxY - marbleHeight / 2))     {         marble1.y = MaxY - marbleHeight / 2;         unitY *= -1;     } } So whenever the user clicks we calculate the unit vector along that direction and also the amount by which the marble position needs to be incremented. The speed in this case is fixed at 6. You can experiment with different values. And under bounds checking, whenever the marble position goes out of bounds along the x or y direction we reverse the direction of the unit vector along that direction. Here’s a video of it running;   Finite Move The code for finite move is almost exactly same as that of Infinite Move, except for the difference that the speed is not fixed and there is an end condition, so the marble comes to rest after a while. Code follows, //unit vector along the direction of click point double unitX = 0, unitY = 0; //speed of the marble double speed = 0; private void Form1_MouseUp(object sender, MouseEventArgs e) {     double x = 0, y = 0;     double lengthSqrd = 0, length = 0;     x = e.X - marble1.x;     y = e.Y - marble1.y;     lengthSqrd = x * x + y * y;     //length in pixels (between click point and current marble pos)     length = Math.Sqrt(lengthSqrd);     //unit vector along the same direction as vector(x, y)     unitX = x / length;     unitY = y / length;     speed = length / 12;     timer1.Enabled = true; } private void UpdatePosition() {     marble1.x += speed * unitX;     marble1.y += speed * unitY;     //check for bounds     if ((int)marble1.x < MinX + marbleWidth / 2)     {         marble1.x = MinX + marbleWidth / 2;         unitX *= -1;     }     else if ((int)marble1.x > (MaxX - marbleWidth / 2))     {         marble1.x = MaxX - marbleWidth / 2;         unitX *= -1;     }     if ((int)marble1.y < MinY + marbleHeight / 2)     {         marble1.y = MinY + marbleHeight / 2;         unitY *= -1;     }     else if ((int)marble1.y > (MaxY - marbleHeight / 2))     {         marble1.y = MaxY - marbleHeight / 2;         unitY *= -1;     }     //reduce speed by 3% in every loop     speed = speed * 0.97f;     if ((int)speed <= 0)     {         timer1.Enabled = false;     } } So the only difference is that the speed is calculated as a function of length when the mouse up event occurs. Again, this can be experimented with. Bounds checking is same as before. In the update and draw cycle, we reduce the speed by 3% in every cycle. Since speed is calculated as a function of length, speed = length/12, the amount of time it takes speed to reach zero is directly proportional to length. Note that the speed is in ‘pixels per 40ms’ because the timeout value of the timer is 40ms.  The readability can be improved by representing speed in ‘pixels per second’. This would require you to add some more calculations to the code, which I leave out as an exercise. Here’s a video of this second version,

    Read the article

  • UITableViewCell rounded corners and clip subviews

    - by Brenden
    I can't find anything anywhere(search engines, docs, here, etc) that shows how to create rounded corners (esp. in a grouped table view) on an element that also clips the subviews. I have code that properly creates a rounded rectangle out of a path with 4 arcs(the rounded corners) that has been tested in the drawRect: method in my subclassed uitableviewcell. The issue is that the subviews, which happen to be uibuttons with their internal uiimageviews, do no obey the CGContextClip() that the uitableviewcell obeys. Here is the code: - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGFloat radius = 12; CGFloat width = CGRectGetWidth(rect); CGFloat height = CGRectGetHeight(rect); // Make sure corner radius isn't larger than half the shorter side if (radius > width/2.0) radius = width/2.0; if (radius > height/2.0) radius = height/2.0; CGFloat minx = CGRectGetMinX(rect) + 10; CGFloat midx = CGRectGetMidX(rect); CGFloat maxx = CGRectGetMaxX(rect) - 10; CGFloat miny = CGRectGetMinY(rect); CGFloat midy = CGRectGetMidY(rect); CGFloat maxy = CGRectGetMaxY(rect); [[UIColor greenColor] set]; CGContextBeginPath(context); CGContextMoveToPoint(context, minx, midy); CGContextAddArcToPoint(context, minx, miny, midx, miny, radius); CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius); CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius); CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius); CGContextClip(context); CGContextFillRect(context, rect); [super drawRect:rect]; } Because this specific case is static(only shows in 1 specific row of buttons), I can edit the images being used for the buttons to get the desired effect. HOWEVER, I have another case that is dynamic. Specifically, a grouped table with lots of database-driven results that will show photos that may be in the first or last row with rounded corners and thus needs to be clipped). So, is it possible to create a CGContextClip() that also clips the subviews? If so, how?

    Read the article

  • [C++ / NCURSES] Can't convert from 'int' to 'int *'

    - by flarn2006
    So I have these lines of code: int maxY, maxX; getmaxyx(stdscr, &maxY, &maxX); It gives me the following error: error C2440: '=' : cannot convert from 'int' to 'int *' Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast twice for each time I use it. I'm not even using the = operator! The curses.h file is included. What am I doing wrong?

    Read the article

  • How to push further as a programmer?

    - by MaXX
    For the last, hmm, 6 months I've been reading into Programming in C, I got myself K&Rv2, BEEJ's socket guide, Expert C programming, Linux Systems Programming, the ISO/IEC 9899:1999 specification (real, and not draft). After receiving them from Amazon, I got Linux installed, and got to it. I'm done with K&R, about halfway through Expert C Programming, but still feel weak as a programmer, I'm sure it takes much more than 6 months of reading to become truly skilled, but my question is this: I've done all the exercises in K&Rv2 (in chapter 1) and some in other chapters, most of which are generally really boring. How do I lift my skills, and become truly great? I've invested money, time and a general lifestyle for something I truly desire, but I'm not sure how exactly to achieve it. Could someone explain to me, perhaps if I need to continuously code, what exactly I'm to code? I'm pretty sure, coding up hello world programs isn't going to teach me any more than I already know about anything. A friend of mine said "read" (with emphasis on read) a man page a day, but reading is all I do, I want to do, but I'm not sure what! I'm interested in security, but I'm not sure as a novice what to code that would be considered enough. Ah, I hope you don't delete this paste :) Thanks

    Read the article

  • Beginning PHP for someone interested in Security

    - by MaXX
    I'd like to learn PHP specifically for dealing with security vulnerabilities/exploits. Could someone recommend a book? I don't know if I need to learn HTML/CSS/XML/XHTML etc, do I have to learn those too? I don't really plan on designing websites, could anyone help me with this? :P

    Read the article

  • 3D picking lwjgl

    - by Wirde
    I have written some code to preform 3D picking that for some reason dosn't work entirely correct! (Im using LWJGL just so you know.) I posted this at stackoverflow at first but after researching some more in to my problem i found this neat site and tought that you guys might be more qualified to answer this question. This is how the code looks like: if(Mouse.getEventButton() == 1) { if (!Mouse.getEventButtonState()) { Camera.get().generateViewMatrix(); float screenSpaceX = ((Mouse.getX()/800f/2f)-1.0f)*Camera.get().getAspectRatio(); float screenSpaceY = 1.0f-(2*((600-Mouse.getY())/600f)); float displacementRate = (float)Math.tan(Camera.get().getFovy()/2); screenSpaceX *= displacementRate; screenSpaceY *= displacementRate; Vector4f cameraSpaceNear = new Vector4f((float) (screenSpaceX * Camera.get().getNear()), (float) (screenSpaceY * Camera.get().getNear()), (float) (-Camera.get().getNear()), 1); Vector4f cameraSpaceFar = new Vector4f((float) (screenSpaceX * Camera.get().getFar()), (float) (screenSpaceY * Camera.get().getFar()), (float) (-Camera.get().getFar()), 1); Matrix4f tmpView = new Matrix4f(); Camera.get().getViewMatrix().transpose(tmpView); Matrix4f invertedViewMatrix = (Matrix4f)tmpView.invert(); Vector4f worldSpaceNear = new Vector4f(); Matrix4f.transform(invertedViewMatrix, cameraSpaceNear, worldSpaceNear); Vector4f worldSpaceFar = new Vector4f(); Matrix4f.transform(invertedViewMatrix, cameraSpaceFar, worldSpaceFar); Vector3f rayPosition = new Vector3f(worldSpaceNear.x, worldSpaceNear.y, worldSpaceNear.z); Vector3f rayDirection = new Vector3f(worldSpaceFar.x - worldSpaceNear.x, worldSpaceFar.y - worldSpaceNear.y, worldSpaceFar.z - worldSpaceNear.z); rayDirection.normalise(); Ray clickRay = new Ray(rayPosition, rayDirection); Vector tMin = new Vector(), tMax = new Vector(), tempPoint; float largestEnteringValue, smallestExitingValue, temp, closestEnteringValue = Camera.get().getFar()+0.1f; Drawable closestDrawableHit = null; for(Drawable d : this.worldModel.getDrawableThings()) { // Calcualte AABB for each object... needs to be moved later... firstVertex = true; for(Surface surface : d.getSurfaces()) { for(Vertex v : surface.getVertices()) { worldPosition.x = (v.x+d.getPosition().x)*d.getScale().x; worldPosition.y = (v.y+d.getPosition().y)*d.getScale().y; worldPosition.z = (v.z+d.getPosition().z)*d.getScale().z; worldPosition = worldPosition.rotate(d.getRotation()); if (firstVertex) { maxX = worldPosition.x; maxY = worldPosition.y; maxZ = worldPosition.z; minX = worldPosition.x; minY = worldPosition.y; minZ = worldPosition.z; firstVertex = false; } else { if (worldPosition.x > maxX) { maxX = worldPosition.x; } if (worldPosition.x < minX) { minX = worldPosition.x; } if (worldPosition.y > maxY) { maxY = worldPosition.y; } if (worldPosition.y < minY) { minY = worldPosition.y; } if (worldPosition.z > maxZ) { maxZ = worldPosition.z; } if (worldPosition.z < minZ) { minZ = worldPosition.z; } } } } // ray/slabs intersection test... // clickRay.getOrigin().x + clickRay.getDirection().x * f = minX // clickRay.getOrigin().x - minX = -clickRay.getDirection().x * f // clickRay.getOrigin().x/-clickRay.getDirection().x - minX/-clickRay.getDirection().x = f // -clickRay.getOrigin().x/clickRay.getDirection().x + minX/clickRay.getDirection().x = f largestEnteringValue = -clickRay.getOrigin().x/clickRay.getDirection().x + minX/clickRay.getDirection().x; temp = -clickRay.getOrigin().y/clickRay.getDirection().y + minY/clickRay.getDirection().y; if(largestEnteringValue < temp) { largestEnteringValue = temp; } temp = -clickRay.getOrigin().z/clickRay.getDirection().z + minZ/clickRay.getDirection().z; if(largestEnteringValue < temp) { largestEnteringValue = temp; } smallestExitingValue = -clickRay.getOrigin().x/clickRay.getDirection().x + maxX/clickRay.getDirection().x; temp = -clickRay.getOrigin().y/clickRay.getDirection().y + maxY/clickRay.getDirection().y; if(smallestExitingValue > temp) { smallestExitingValue = temp; } temp = -clickRay.getOrigin().z/clickRay.getDirection().z + maxZ/clickRay.getDirection().z; if(smallestExitingValue < temp) { smallestExitingValue = temp; } if(largestEnteringValue > smallestExitingValue) { //System.out.println("Miss!"); } else { if (largestEnteringValue < closestEnteringValue) { closestEnteringValue = largestEnteringValue; closestDrawableHit = d; } } } if(closestDrawableHit != null) { System.out.println("Hit at: (" + clickRay.setDistance(closestEnteringValue).x + ", " + clickRay.getCurrentPosition().y + ", " + clickRay.getCurrentPosition().z); this.worldModel.removeDrawableThing(closestDrawableHit); } } } I just don't understand what's wrong, the ray are shooting and i do hit stuff that gets removed but the result of the ray are verry strange it sometimes removes the thing im clicking at, sometimes it removes things thats not even close to what im clicking at, and sometimes it removes nothing at all. Edit: Okay so i have continued searching for errors and by debugging the ray (by painting smal dots where it travles) i can now se that there is something oviously wrong with the ray that im sending out... it has its origin near the world center (nearer or further away depending on where on the screen im clicking) and always shots to the same position no matter where I direct my camera... My initial toughts is that there might be some error in the way i calculate my viewMatrix (since it's not possible to get the viewmatrix from the gluLookAt method in lwjgl; I have to build it my self and I guess thats where the problem is at)... Edit2: This is how i calculate it currently: private double[][] viewMatrixDouble = {{0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,1}}; public Vector getCameraDirectionVector() { Vector actualEye = this.getActualEyePosition(); return new Vector(lookAt.x-actualEye.x, lookAt.y-actualEye.y, lookAt.z-actualEye.z); } public Vector getActualEyePosition() { return eye.rotate(this.getRotation()); } public void generateViewMatrix() { Vector cameraDirectionVector = getCameraDirectionVector().normalize(); Vector side = Vector.cross(cameraDirectionVector, this.upVector).normalize(); Vector up = Vector.cross(side, cameraDirectionVector); viewMatrixDouble[0][0] = side.x; viewMatrixDouble[0][1] = up.x; viewMatrixDouble[0][2] = -cameraDirectionVector.x; viewMatrixDouble[1][0] = side.y; viewMatrixDouble[1][1] = up.y; viewMatrixDouble[1][2] = -cameraDirectionVector.y; viewMatrixDouble[2][0] = side.z; viewMatrixDouble[2][1] = up.z; viewMatrixDouble[2][2] = -cameraDirectionVector.z; /* Vector actualEyePosition = this.getActualEyePosition(); Vector zaxis = new Vector(this.lookAt.x - actualEyePosition.x, this.lookAt.y - actualEyePosition.y, this.lookAt.z - actualEyePosition.z).normalize(); Vector xaxis = Vector.cross(upVector, zaxis).normalize(); Vector yaxis = Vector.cross(zaxis, xaxis); viewMatrixDouble[0][0] = xaxis.x; viewMatrixDouble[0][1] = yaxis.x; viewMatrixDouble[0][2] = zaxis.x; viewMatrixDouble[1][0] = xaxis.y; viewMatrixDouble[1][1] = yaxis.y; viewMatrixDouble[1][2] = zaxis.y; viewMatrixDouble[2][0] = xaxis.z; viewMatrixDouble[2][1] = yaxis.z; viewMatrixDouble[2][2] = zaxis.z; viewMatrixDouble[3][0] = -Vector.dot(xaxis, actualEyePosition); viewMatrixDouble[3][1] =-Vector.dot(yaxis, actualEyePosition); viewMatrixDouble[3][2] = -Vector.dot(zaxis, actualEyePosition); */ viewMatrix = new Matrix4f(); viewMatrix.load(getViewMatrixAsFloatBuffer()); } Would be verry greatfull if anyone could verify if this is wrong or right, and if it's wrong; supply me with the right way of doing it... I have read alot of threads and documentations about this but i can't seam to wrapp my head around it... Edit3: Okay with the help of Byte56 (thanks alot for the help) i have now concluded that it's not the viewMatrix that is the problem... I still get the same messedup result; anyone that think that they can find the error in my code, i certenly can't, have bean working on this for 3 days now :(

    Read the article

  • What's wrong with my code? (pdcurses/getmaxyx)

    - by flarn2006
    It gives me an access violation on the getmaxyx line (second line in the main function) and also gives me these two warnings: LINK : warning LNK4049: locally defined symbol "_stdscr" imported LINK : warning LNK4049: locally defined symbol "_SP" imported Yes, it's the same code as in another question I asked, it's just that I'm making it more clear. And yes, I have written programs with pdcurses before with no problems. #include <time.h> #include <curses.h> #include "Ball.h" #include "Paddle.h" #include "config.h" int main(int argc, char *argv[]) { int maxY, maxX; getmaxyx(stdscr, maxY, maxX); Paddle *paddleLeft = new Paddle(0, KEY_L_UP, KEY_L_DOWN); Paddle *paddleRight = new Paddle(maxX, KEY_R_UP, KEY_R_DOWN); Ball *ball = new Ball(paddleLeft, paddleRight); int key = 0; initscr(); cbreak(); noecho(); curs_set(0); while (key != KEY_QUIT) { key = getch(); paddleLeft->OnKeyPress(key); paddleRight->OnKeyPress(key); } endwin(); return 0; }

    Read the article

  • Problems Allocating Objects of Derived Class Where Base Class has Abstract Virtual Functions

    - by user1743901
    I am trying to get this Zombie/Human agent based simulation running, but I am having problems with these derived classes (Human and Zombie) who have parent class "Creature". I have 3 virtual functions declared in "Creature" and all three of these are re-declared AND DEFINED in both "Human" and "Zombie". But for some reason when I have my program call "new" to allocate memory for objects of type Human or Zombie, it complains about the virtual functions being abstract. Here's the code: definitions.h #ifndef definitions_h #define definitions_h class Creature; class Item; class Coords; class Grid { public: Creature*** cboard; Item*** iboard; int WIDTH; int HEIGHT; Grid(int WIDTHVALUE, int HEIGHTVALUE); void FillGrid(); //initializes grid object with humans and zombies void Refresh(); //calls Creature::Die(),Move(),Attack(),Breed() on every square void UpdateBuffer(char** buffer); bool isEmpty(int startx, int starty, int dir); char CreatureType(int xcoord, int ycoord); char CreatureType(int startx, int starty, int dir); }; class Random { public: int* rptr; void Print(); Random(int MIN, int MAX, int LEN); ~Random(); private: bool alreadyused(int checkthis, int len, int* rptr); bool isClean(); int len; }; class Coords { public: int x; int y; int MaxX; int MaxY; Coords() {x=0; y=0; MaxX=0; MaxY=0;} Coords(int X, int Y, int WIDTH, int HEIGHT) {x=X; y=Y; MaxX=WIDTH; MaxY=HEIGHT; } void MoveRight(); void MoveLeft(); void MoveUp(); void MoveDown(); void MoveUpRight(); void MoveUpLeft(); void MoveDownRight(); void MoveDownLeft(); void MoveDir(int dir); void setx(int X) {x=X;} void sety(int Y) {y=Y;} }; class Creature { public: bool alive; Coords Location; char displayletter; Creature() {Location.x=0; Location.y=0;} Creature(int i, int j) {Location.setx(i); Location.sety(j);} virtual void Attack() =0; virtual void AttackCreature(Grid G, int attackdirection) =0; virtual void Breed() =0; void Die(); void Move(Grid G); int DecideSquare(Grid G); void MoveTo(Grid G, int dir); }; class Human : public Creature { public: bool armed; //if armed, chances of winning fight increased for next fight bool vaccinated; //if vaccinated, no chance of getting infected int bitecount; //if a human is bitten, bite count is set to a random number int breedcount; //if a human goes x steps without combat, will breed if next to a human int starvecount; //if a human does not eat in x steps, will die Human() {displayletter='H';} Human(int i, int j) {displayletter='H';} void Attack(Grid G); void AttackCreature(Grid G, int attackdirection); void Breed(Grid G); //will breed after x steps and next to human int DecideAttack(Grid G); }; class Zombie : public Creature { public: Zombie() {displayletter='Z';} Zombie(int i, int j) {displayletter='Z';} void Attack(Grid G); void AttackCreature(Grid G, int attackdirection); void Breed() {} //does nothing int DecideAttack(Grid G); void AttackCreature(Grid G, int attackdirection); }; class Item { }; #endif definitions.cpp #include <cstdlib> #include "definitions.h" Random::Random(int MIN, int MAX, int LEN) //constructor { len=LEN; rptr=new int[LEN]; //allocate array of given length for (int i=0; i<LEN; i++) { int random; do { random = rand() % (MAX-MIN+1) + MIN; } while (alreadyused(random,LEN,rptr)); rptr[i]=random; } } bool Random::alreadyused(int checkthis, int len, int* rptr) { for (int i=0; i<len; i++) { if (rptr[i]==checkthis) return 1; } return 0; } Random::~Random() { delete rptr; } Grid::Grid(int WIDTHVALUE, int HEIGHTVALUE) { WIDTH = WIDTHVALUE; HEIGHT = HEIGHTVALUE; //builds 2d array of creature pointers cboard = new Creature**[WIDTH]; for(int i=0; i<WIDTH; i++) { cboard[i] = new Creature*[HEIGHT]; } //builds 2d array of item pointers iboard = new Item**[WIDTH]; for (int i=0; i<WIDTH; i++) { iboard[i] = new Item*[HEIGHT]; } } void Grid::FillGrid() { /* For each creature pointer in grid, randomly selects whether to initalize as zombie, human, or empty square. This methodology can be changed to initialize different creature types with different probabilities */ int random; for (int i=0; i<WIDTH; i++) { for (int j=0; j<HEIGHT; j++) { Random X(1,100,1); //create a single random integer from [1,100] at X.rptr random=*(X.rptr); if (random < 20) cboard[i][j] = new Human(i,j); else if (random < 40) cboard[i][j] = new Zombie(i,j); else cboard[i][j] = NULL; } } //at this point every creature pointer should be pointing to either //a zombie, human, or NULL with varying probabilities } void Grid::UpdateBuffer(char** buffer) { for (int i=0; i<WIDTH; i++) { for (int j=0; j<HEIGHT; j++) { if (cboard[i][j]) buffer[i][j]=cboard[i][j]->displayletter; else buffer[i][j]=' '; } } } bool Grid::isEmpty(int startx, int starty, int dir) { Coords StartLocation(startx,starty,WIDTH,HEIGHT); switch(dir) { case 1: StartLocation.MoveUp(); if (cboard[StartLocation.x][StartLocation.y]) return 0; case 2: StartLocation.MoveUpRight(); if (cboard[StartLocation.x][StartLocation.y]) return 0; case 3: StartLocation.MoveRight(); if (cboard[StartLocation.x][StartLocation.y]) return 0; case 4: StartLocation.MoveDownRight(); if (cboard[StartLocation.x][StartLocation.y]) return 0; case 5: StartLocation.MoveDown(); if (cboard[StartLocation.x][StartLocation.y]) return 0; case 6: StartLocation.MoveDownLeft(); if (cboard[StartLocation.x][StartLocation.y]) return 0; case 7: StartLocation.MoveLeft(); if (cboard[StartLocation.x][StartLocation.y]) return 0; case 8: StartLocation.MoveUpLeft(); if (cboard[StartLocation.x][StartLocation.y]) return 0; } return 1; } char Grid::CreatureType(int xcoord, int ycoord) { if (cboard[xcoord][ycoord]) //if there is a creature at location xcoord,ycoord return (cboard[xcoord][ycoord]->displayletter); else //if pointer at location xcoord,ycoord is null, return null char return '\0'; } char Grid::CreatureType(int startx, int starty, int dir) { Coords StartLocation(startx,starty,WIDTH,HEIGHT); switch(dir) { case 1: StartLocation.MoveUp(); if (cboard[StartLocation.x][StartLocation.y]) return (cboard[StartLocation.x][StartLocation.y]->displayletter); case 2: StartLocation.MoveUpRight(); if (cboard[StartLocation.x][StartLocation.y]) return (cboard[StartLocation.x][StartLocation.y]->displayletter); case 3: StartLocation.MoveRight(); if (cboard[StartLocation.x][StartLocation.y]) return (cboard[StartLocation.x][StartLocation.y]->displayletter); case 4: StartLocation.MoveDownRight(); if (cboard[StartLocation.x][StartLocation.y]) return (cboard[StartLocation.x][StartLocation.y]->displayletter); case 5: StartLocation.MoveDown(); if (cboard[StartLocation.x][StartLocation.y]) return (cboard[StartLocation.x][StartLocation.y]->displayletter); case 6: StartLocation.MoveDownLeft(); if (cboard[StartLocation.x][StartLocation.y]) return (cboard[StartLocation.x][StartLocation.y]->displayletter); case 7: StartLocation.MoveLeft(); if (cboard[StartLocation.x][StartLocation.y]) return (cboard[StartLocation.x][StartLocation.y]->displayletter); case 8: StartLocation.MoveUpLeft(); if (cboard[StartLocation.x][StartLocation.y]) return (cboard[StartLocation.x][StartLocation.y]->displayletter); } //if function hasn't returned by now, square being looked at is pointer to null return '\0'; //return null char } void Coords::MoveRight() {(x==MaxX)? (x=0):(x++);} void Coords::MoveLeft() {(x==0)? (x=MaxX):(x--);} void Coords::MoveUp() {(y==0)? (y=MaxY):(y--);} void Coords::MoveDown() {(y==MaxY)? (y=0):(y++);} void Coords::MoveUpRight() {MoveUp(); MoveRight();} void Coords::MoveUpLeft() {MoveUp(); MoveLeft();} void Coords::MoveDownRight() {MoveDown(); MoveRight();} void Coords::MoveDownLeft() {MoveDown(); MoveLeft();} void Coords::MoveDir(int dir) { switch(dir) { case 1: MoveUp(); break; case 2: MoveUpRight(); break; case 3: MoveRight(); break; case 4: MoveDownRight(); break; case 5: MoveDown(); break; case 6: MoveDownLeft(); break; case 7: MoveLeft(); break; case 8: MoveUpLeft(); break; case 0: break; } } void Creature::Move(Grid G) { int movedir=DecideSquare(G); MoveTo(G,movedir); } int Creature::DecideSquare(Grid G) { Random X(1,8,8); //X.rptr now points to 8 unique random integers from [1,8] for (int i=0; i<8; i++) { int dir=X.rptr[i]; if (G.isEmpty(Location.x,Location.y,dir)) return dir; } return 0; } void Creature::MoveTo(Grid G, int dir) { Coords OldLocation=Location; Location.MoveDir(dir); G.cboard[Location.x][Location.y]=this; //point new location to this creature G.cboard[OldLocation.x][OldLocation.y]=NULL; //point old location to NULL } void Creature::Die() { if (!alive) { delete this; this=NULL; } } void Human::Breed(Grid G) { if (!breedcount) { Coords BreedLocation=Location; Random X(1,8,8); for (int i=0; i<8; i++) { BreedLocation.MoveDir(X.rptr[i]); if (!G.cboard[BreedLocation.x][BreedLocation.y]) { G.cboard[BreedLocation.x][BreedLocation.y])=new Human(BreedLocation.x,BreedLocation.y); return; } } } } int Human::DecideAttack(Grid G) { Coords AttackLocation=Location; Random X(1,8,8); int attackdir; for (int i=0; i<8; i++) { attackdir=X.rptr[i]; switch(G.CreatureType(Location.x,Location.y,attackdir)) { case 'H': break; case 'Z': return attackdir; case '\0': break; default: break; } } return 0; //no zombies! } int AttackRoll(int para1, int para2) { //outcome 1: Zombie wins, human dies //outcome 2: Human wins, zombie dies //outcome 3: Human wins, zombie dies, but human is bitten Random X(1,100,1); int roll= *(X.rptr); if (roll < para1) return 1; else if (roll < para2) return 2; else return 3; } void Human::AttackCreature(Grid G, int attackdirection) { Coords AttackLocation=Location; AttackLocation.MoveDir(attackdirection); int para1=33; int para2=33; if (vaccinated) para2=101; //makes attackroll > para 2 impossible, never gets infected if (armed) para1-=16; //reduces chance of zombie winning fight int roll=AttackRoll(para1,para2); //outcome 1: Zombie wins, human dies //outcome 2: Human wins, zombie dies //outcome 3: Human wins, zombie dies, but human is bitten switch(roll) { case 1: alive=0; //human (this) dies return; case 2: G.cboard[AttackLocation.x][AttackLocation.y]->alive=0; return; //zombie dies case 3: G.cboard[AttackLocation.x][AttackLocation.y]->alive=0; //zombie dies Random X(3,7,1); //human is bitten bitecount=*(X.rptr); return; } } int Zombie::DecideAttack(Grid G) { Coords AttackLocation=Location; Random X(1,8,8); int attackdir; for (int i=0; i<8; i++) { attackdir=X.rptr[i]; switch(G.CreatureType(Location.x,Location.y,attackdir)) { case 'H': return attackdir; case 'Z': break; case '\0': break; default: break; } } return 0; //no zombies! } void Zombie::AttackCreature(Grid G, int attackdirection) { int reversedirection; if (attackdirection < 9 && attackdirection>0) { (attackdirection<5)? (reversedirection=attackdirection+4):(reversedirection=attackdirection-4); } else reversedirection=0; //this should never happen //when a zombie attacks a human, the Human::AttackZombie() function is called //in the "reverse" direction, utilizing that function that has already been written Coords ZombieLocation=Location; Coords HumanLocation=Location; HumanLocation.MoveDir(attackdirection); if (G.cboard[HumanLocation.x][HumanLocation.y]) //if there is a human there, which there should be G.cboard[HumanLocation.x][HumanLocation.y]->AttackCreature(G,reversedirection); } void Zombie::Attack(Grid G) { int attackdirection=DecideAttack(G); AttackCreature(G,attackdirection); } main.cpp #include <cstdlib> #include <iostream> #include "definitions.h" using namespace std; int main(int argc, char *argv[]) { Grid G(500,500); system("PAUSE"); return EXIT_SUCCESS; }

    Read the article

  • rotating bitmaps. In code.

    - by Marco van de Voort
    Is there a faster way to rotate a large bitmap by 90 or 270 degrees than simply doing a nested loop with inverted coordinates? The bitmaps are 8bpp and typically 2048*2400*8bpp Currently I do this by simply copying with argument inversion, roughly (pseudo code: for x = 0 to 2048-1 for y = 0 to 2048-1 dest[x][y]=src[y][x]; (In reality I do it with pointers, for a bit more speed, but that is roughly the same magnitude) GDI is quite slow with large images, and GPU load/store times for textures (GF7 cards) are in the same magnitude as the current CPU time. Any tips, pointers? An in-place algorithm would even be better, but speed is more important than being in-place. Target is Delphi, but it is more an algorithmic question. SSE(2) vectorization no problem, it is a big enough problem for me to code it in assembler Duplicates How do you rotate a two dimensional array?. Follow up to Nils' answer Image 2048x2700 - 2700x2048 Compiler Turbo Explorer 2006 with optimization on. Windows: Power scheme set to "Always on". (important!!!!) Machine: Core2 6600 (2.4 GHz) time with old routine: 32ms (step 1) time with stepsize 8 : 12ms time with stepsize 16 : 10ms time with stepsize 32+ : 9ms Meanwhile I also tested on a Athlon 64 X2 (5200+ iirc), and the speed up there was slightly more than a factor four (80 to 19 ms). The speed up is well worth it, thanks. Maybe that during the summer months I'll torture myself with a SSE(2) version. However I already thought about how to tackle that, and I think I'll run out of SSE2 registers for an straight implementation: for n:=0 to 7 do begin load r0, <source+n*rowsize> shift byte from r0 into r1 shift byte from r0 into r2 .. shift byte from r0 into r8 end; store r1, <target> store r2, <target+1*<rowsize> .. store r8, <target+7*<rowsize> So 8x8 needs 9 registers, but 32-bits SSE only has 8. Anyway that is something for the summer months :-) Note that the pointer thing is something that I do out of instinct, but it could be there is actually something to it, if your dimensions are not hardcoded, the compiler can't turn the mul into a shift. While muls an sich are cheap nowadays, they also generate more register pressure afaik. The code (validated by subtracting result from the "naieve" rotate1 implementation): const stepsize = 32; procedure rotatealign(Source: tbw8image; Target:tbw8image); var stepsx,stepsy,restx,resty : Integer; RowPitchSource, RowPitchTarget : Integer; pSource, pTarget,ps1,ps2 : pchar; x,y,i,j: integer; rpstep : integer; begin RowPitchSource := source.RowPitch; // bytes to jump to next line. Can be negative (includes alignment) RowPitchTarget := target.RowPitch; rpstep:=RowPitchTarget*stepsize; stepsx:=source.ImageWidth div stepsize; stepsy:=source.ImageHeight div stepsize; // check if mod 16=0 here for both dimensions, if so -> SSE2. for y := 0 to stepsy - 1 do begin psource:=source.GetImagePointer(0,y*stepsize); // gets pointer to pixel x,y ptarget:=Target.GetImagePointer(target.imagewidth-(y+1)*stepsize,0); for x := 0 to stepsx - 1 do begin for i := 0 to stepsize - 1 do begin ps1:=@psource[rowpitchsource*i]; // ( 0,i) ps2:=@ptarget[stepsize-1-i]; // (maxx-i,0); for j := 0 to stepsize - 1 do begin ps2[0]:=ps1[j]; inc(ps2,RowPitchTarget); end; end; inc(psource,stepsize); inc(ptarget,rpstep); end; end; // 3 more areas to do, with dimensions // - stepsy*stepsize * restx // right most column of restx width // - stepsx*stepsize * resty // bottom row with resty height // - restx*resty // bottom-right rectangle. restx:=source.ImageWidth mod stepsize; // typically zero because width is // typically 1024 or 2048 resty:=source.Imageheight mod stepsize; if restx>0 then begin // one loop less, since we know this fits in one line of "blocks" psource:=source.GetImagePointer(source.ImageWidth-restx,0); // gets pointer to pixel x,y ptarget:=Target.GetImagePointer(Target.imagewidth-stepsize,Target.imageheight-restx); for y := 0 to stepsy - 1 do begin for i := 0 to stepsize - 1 do begin ps1:=@psource[rowpitchsource*i]; // ( 0,i) ps2:=@ptarget[stepsize-1-i]; // (maxx-i,0); for j := 0 to restx - 1 do begin ps2[0]:=ps1[j]; inc(ps2,RowPitchTarget); end; end; inc(psource,stepsize*RowPitchSource); dec(ptarget,stepsize); end; end; if resty>0 then begin // one loop less, since we know this fits in one line of "blocks" psource:=source.GetImagePointer(0,source.ImageHeight-resty); // gets pointer to pixel x,y ptarget:=Target.GetImagePointer(0,0); for x := 0 to stepsx - 1 do begin for i := 0 to resty- 1 do begin ps1:=@psource[rowpitchsource*i]; // ( 0,i) ps2:=@ptarget[resty-1-i]; // (maxx-i,0); for j := 0 to stepsize - 1 do begin ps2[0]:=ps1[j]; inc(ps2,RowPitchTarget); end; end; inc(psource,stepsize); inc(ptarget,rpstep); end; end; if (resty>0) and (restx>0) then begin // another loop less, since only one block psource:=source.GetImagePointer(source.ImageWidth-restx,source.ImageHeight-resty); // gets pointer to pixel x,y ptarget:=Target.GetImagePointer(0,target.ImageHeight-restx); for i := 0 to resty- 1 do begin ps1:=@psource[rowpitchsource*i]; // ( 0,i) ps2:=@ptarget[resty-1-i]; // (maxx-i,0); for j := 0 to restx - 1 do begin ps2[0]:=ps1[j]; inc(ps2,RowPitchTarget); end; end; end; end;

    Read the article

  • redrawing on ncurses

    - by John C
    I'm trying to redraw the content of a simple loop. So far it prints out to the stdscr 100 lines, and then by using scrl to scroll n lines I get n blank rows. What I want is to keep with the sequence. However, I'm not sure how to redraw the stdscr with the n extra lines. Any ideas will be appreciate it! #include <ncurses.h> int main(void) { initscr(); int maxy,maxx,y; getmaxyx(stdscr,maxy,maxx); scrollok(stdscr,TRUE); for(y=0;y<=100;y++) mvprintw(y,0,"This is some text written to line %d.",y); refresh(); getch(); scrl(5); refresh(); getch(); endwin(); return(0); }

    Read the article

  • Panoramio API access using AJAX - error "Origin hxxp://foo.bar is not allowed by Access-Control-Allow-Origin."

    - by Marko
    Hello there! I am currently experiencing this issue, and am wondering why...? The error message is: "XMLHttpRequest cannot load http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&minx=-30&miny=0&maxx=0&maxy=150&callback=?. Origin hxxp://foo.bar is not allowed by Access-Control-Allow-Origin. test_panoramio.html:59Uncaught SyntaxError: Unexpected token )" "hxxp://foo.bar" refers to the site I am running the script from. The "test_panoramio.html" on the site contains e.g. the following : var url = "http://www.panoramio.com/wapi/data/get_photos? v=1&key=dummykey&tag=test&offset=0&length=20&minx=- 30&miny=0&maxx=0&maxy=150&callback=?"; function myScriptFn() { if (window.XMLHttpRequest) { myAjax = new XMLHttpRequest(); if ( typeof myAjax.overrideMimeType != 'undefined') { myAjax.overrideMimeType('text/xml'); } } else if (window.ActiveXObject) { myAjax = new ActiveXObject("Microsoft.XMLHTTP"); } else { alert('The browser does not support the AJAX XMLHttpRequest!!!'); } myAjax.onreadystatechange = function() { handleResponse(); } myAjax.open('GET', url, true); myAjax.send(null); } function handleResponse() { if (myAjax.readyState == 4){ // Response is COMPLETE if ((myAjax.status == 200) || (myAjax.status = 304)) { // do something with the responseText or responseXML processResults(); }else{ alert("[handleResponse]: An error has occurred."); } } } function processResults() { myObj = eval( '(' + myAjax.responseText + ')' ); ... doSomething() ... } The Panoramio URL works if typed directly to the browser. Please could you help me with this, I am running out of hope...:( Thank you in advance, Yours Marko

    Read the article

  • Cheap sound on speakers - Dell XPS L502X

    - by Rafael
    I have a new machine that comes with JBL 2.1 Speakers with Waves Maxx Audio 3. On Windows it sounds perfect, though in Ubuntu 12.04 I get cheap/sound with simple mp3 files. I have tried a few things on different blogs but no luck so far. Any ideas? aplay -l **** List of PLAYBACK Hardware Devices **** card 0: PCH [HDA Intel PCH], device 0: ALC665 Analog [ALC665 Analog] Subdevices: 1/1 Subdevice #0: subdevice #0 card 0: PCH [HDA Intel PCH], device 1: ALC665 Digital [ALC665 Digital] Subdevices: 1/1 Subdevice #0: subdevice #0 card 0: PCH [HDA Intel PCH], device 3: HDMI 0 [HDMI 0] Subdevices: 1/1 Subdevice #0: subdevice #0 card 1: N700 [Logitech Speaker Lapdesk N700], device 0: USB Audio [USB Audio] Subdevices: 1/1 Subdevice #0: subdevice #0

    Read the article

  • Applications: The Mathematics of Movement, Part 2

    - by TechTwaddle
    In part 1 of this series we saw how we can make the marble move towards the click point, with a fixed speed. In this post we’ll see, first, how to get rid of Atan2(), sine() and cosine() in our calculations, and, second, reducing the speed of the marble as it approaches the destination, so it looks like the marble is easing into it’s final position. As I mentioned in one of the previous posts, this is achieved by making the speed of the marble a function of the distance between the marble and the destination point. Getting rid of Atan2(), sine() and cosine() Ok, to be fair we are not exactly getting rid of these trigonometric functions, rather, replacing one form with another. So instead of writing sin(?), we write y/length. You see the point. So instead of using the trig functions as below, double x = destX - marble1.x; double y = destY - marble1.y; //distance between destination and current position, before updating marble position distanceSqrd = x * x + y * y; double angle = Math.Atan2(y, x); //Cos and Sin give us the unit vector, 6 is the value we use to magnify the unit vector along the same direction incrX = speed * Math.Cos(angle); incrY = speed * Math.Sin(angle); marble1.x += incrX; marble1.y += incrY; we use the following, double x = destX - marble1.x; double y = destY - marble1.y; //distance between destination and marble (before updating marble position) lengthSqrd = x * x + y * y; length = Math.Sqrt(lengthSqrd); //unit vector along the same direction as vector(x, y) unitX = x / length; unitY = y / length; //update marble position incrX = speed * unitX; incrY = speed * unitY; marble1.x += incrX; marble1.y += incrY; so we replaced cos(?) with x/length and sin(?) with y/length. The result is the same.   Adding oomph to the way it moves In the last post we had the speed of the marble fixed at 6, double speed = 6; to make the marble decelerate as it moves, we have to keep updating the speed of the marble in every frame such that the speed is calculated as a function of the length. So we may have, speed = length/12; ‘length’ keeps decreasing as the marble moves and so does speed. The Form1_MouseUp() function remains the same as before, here is the UpdatePosition() method, private void UpdatePosition() {     double incrX = 0, incrY = 0;     double lengthSqrd = 0, length = 0, lengthSqrdNew = 0;     double unitX = 0, unitY = 0;     double speed = 0;     double x = destX - marble1.x;     double y = destY - marble1.y;     //distance between destination and marble (before updating marble position)     lengthSqrd = x * x + y * y;     length = Math.Sqrt(lengthSqrd);     //unit vector along the same direction as vector(x, y)     unitX = x / length;     unitY = y / length;     //speed as a function of length     speed = length / 12;     //update marble position     incrX = speed * unitX;     incrY = speed * unitY;     marble1.x += incrX;     marble1.y += incrY;     //check for bounds     if ((int)marble1.x < MinX + marbleWidth / 2)     {         marble1.x = MinX + marbleWidth / 2;     }     else if ((int)marble1.x > (MaxX - marbleWidth / 2))     {         marble1.x = MaxX - marbleWidth / 2;     }     if ((int)marble1.y < MinY + marbleHeight / 2)     {         marble1.y = MinY + marbleHeight / 2;     }     else if ((int)marble1.y > (MaxY - marbleHeight / 2))     {         marble1.y = MaxY - marbleHeight / 2;     }     //distance between destination and marble (after updating marble position)     x = destX - (marble1.x);     y = destY - (marble1.y);     lengthSqrdNew = x * x + y * y;     /*      * End Condition:      * 1. If there is not much difference between lengthSqrd and lengthSqrdNew      * 2. If the marble has moved more than or equal to a distance of totLenToTravel (see Form1_MouseUp)      */     x = startPosX - marble1.x;     y = startPosY - marble1.y;     double totLenTraveledSqrd = x * x + y * y;     if ((int)totLenTraveledSqrd >= (int)totLenToTravelSqrd)     {         System.Console.WriteLine("Stopping because Total Len has been traveled");         timer1.Enabled = false;     }     else if (Math.Abs((int)lengthSqrd - (int)lengthSqrdNew) < 4)     {         System.Console.WriteLine("Stopping because no change in Old and New");         timer1.Enabled = false;     } } A point to note here is that, in this implementation, the marble never stops because it travelled a distance of totLenToTravelSqrd (first if condition). This happens because speed is a function of the length. During the final few frames length becomes very small and so does speed; and so the amount by which the marble shifts is quite small, and the second if condition always hits true first. I’ll end this series with a third post. In part 3 we will cover two things, one, when the user clicks, the marble keeps moving in that direction, rebounding off the screen edges and keeps moving forever. Two, when the user clicks on the screen, the marble moves towards it, with it’s speed reducing by every frame. It doesn’t come to a halt when the destination point is reached, instead, it continues to move, rebounds off the screen edges and slowly comes to halt. The amount of time that the marble keeps moving depends on how far the user clicks from the marble. I had mentioned this second situation here. Finally, here’s a video of this program running,

    Read the article

  • I am making a maze type of game using javascript and HTML and need some questions answered [on hold]

    - by Timothy Bilodeau
    First off, i am a noob to JavaScript but am willing to learn. :) I found a simple JavaScript moment engine created by another member on this site. Using that i made it so my character can walk around within a rectangle/square shaped room. I want to make it so the character can walk through a "doorway" within a wall to the next room. Either that or make it so if the character moves over a certain image within the room it will take the player to another webpage in which the character "spawns" into the room and so on and so fourth. Here is a link to what i have made so far as to get an idea. http://bit.ly/1fSMesA Any help would be much appreciated. Here is the javascript code for the character movement and boundaries. <script type='text/javascript'> // movement vars var xpos = 100; var ypos = 100; var xspeed = 1; var yspeed = 0; var maxSpeed = 5; // boundary var minx = 37; var miny = 41; var maxx = 187; // 10 pixels for character's width var maxy = 178; // 10 pixels for character's width // controller vars var upPressed = 0; var downPressed = 0; var leftPressed = 0; var rightPressed = 0; function slowDownX() { if (xspeed > 0) xspeed = xspeed - 1; if (xspeed < 0) xspeed = xspeed + 1; } function slowDownY() { if (yspeed > 0) yspeed = yspeed - 1; if (yspeed < 0) yspeed = yspeed + 1; } function gameLoop() { // change position based on speed xpos = Math.min(Math.max(xpos + xspeed,minx),maxx); ypos = Math.min(Math.max(ypos + yspeed,miny),maxy); // or, without boundaries: // xpos = xpos + xspeed; // ypos = ypos + yspeed; // change actual position document.getElementById('character').style.left = xpos; document.getElementById('character').style.top = ypos; // change speed based on keyboard events if (upPressed == 1) yspeed = Math.max(yspeed - 1,-1*maxSpeed); if (downPressed == 1) yspeed = Math.min(yspeed + 1,1*maxSpeed) if (rightPressed == 1) xspeed = Math.min(xspeed + 1,1*maxSpeed); if (leftPressed == 1) xspeed = Math.max(xspeed - 1,-1*maxSpeed); // deceleration if (upPressed == 0 && downPressed == 0) slowDownY(); if (leftPressed == 0 && rightPressed == 0) slowDownX(); // loop setTimeout("gameLoop()",10); } function keyDown(e) { var code = e.keyCode ? e.keyCode : e.which; if (code == 38) upPressed = 1; if (code == 40) downPressed = 1; if (code == 37) leftPressed = 1; if (code == 39) rightPressed = 1; } function keyUp(e) { var code = e.keyCode ? e.keyCode : e.which; if (code == 38) upPressed = 0; if (code == 40) downPressed = 0; if (code == 37) leftPressed = 0; if (code == 39) rightPressed = 0; } </script> here is the HTML code to follow <!-- The Level --> <img src="room1.png" /> <!-- The Character --> <img id='character' src='../texture packs/characters/snazgel.png' style='position:absolute;left:100;top:100;height:40;width:26;'/>

    Read the article

1 2  | Next Page >