Search Results

Search found 452 results on 19 pages for 'delta'.

Page 4/19 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Variable-step update() in game loop is falling behind, how can I get around this?

    - by ThatsGobbles
    I'm working on a minimal game engine for my next game. I'm using the delta update method like shown: void update(double delta) { // Update code that uses `delta` goes here } I have a deep hierarchy of updatable objects, with a root updatable that contains several updatables, each of which contains more updatables, etc. Normally I'd just iterate through each of the root's children and update each one, which would then do the same for its children, and so on. However, passing a fixed value of delta to the root means that by the time the leaf updatables are reached, it's been longer since delta seconds that have elapsed. This is causing noticable desyncing in my game, and time synchronization is very important in my case (I'm working on a rhythm game). Any ideas on how I should tackle this? I've considered using StopWatches and a global readable timer, but any advice would be helpful. I'm also open to moving to fixed timesteps as opposed to variable.

    Read the article

  • Stopping the animation after you let go of a key

    - by Michael Zeuner
    What I have right now is an animation that starts when I press space: if(input.isKeyDown(Input.KEY_SPACE)) player = movingRightSwingingSword; However when I stop clicking space my animation continues. until I move my player, how do I make it so it stops the animation right when you let go of space? A few lines Animation player, movingUp, movingDown, movingLeft, movingRight, movingRightSwingingSword; int[] duration = {200,200}; public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { Image[] attackRight = {new Image("res/buckysRightSword1.png"), new Image("res/buckysRightSword2.png")}; movingRightSwingingSword = new Animation(attackRight, duration, true); } public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException { if(input.isKeyDown(Input.KEY_SPACE)) player = movingRightSwingingSword; } Full Code package javagame; import org.newdawn.slick.*; import org.newdawn.slick.state.*; public class Play extends BasicGameState { Animation player, movingUp, movingDown, movingLeft, movingRight, movingRightSwingingSword; Image worldMap; boolean quit = false; int[] duration = {200,200}; float playerPositionX = 0; float playerPositionY = 0; float shiftX = playerPositionX + 320; float shiftY = playerPositionY + 160; public Play(int state) { } public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { worldMap = new Image("res/world.png"); Image[] walkUp = {new Image("res/buckysBack.png"), new Image("res/buckysBack.png")}; Image[] walkDown = {new Image("res/buckysFront.png"), new Image("res/buckysFront.png")}; Image[] walkLeft = {new Image("res/buckysLeft.png"), new Image("res/buckysLeft.png")}; Image[] walkRight = {new Image("res/buckysRight.png"), new Image("res/buckysRight.png")}; Image[] attackRight = {new Image("res/buckysRightSword1.png"), new Image("res/buckysRightSword2.png")}; movingUp = new Animation(walkUp, duration, false); movingDown = new Animation(walkDown, duration, false); movingLeft = new Animation(walkLeft, duration, false); movingRight = new Animation(walkRight, duration, false); //doesnt work! vvv movingRightSwingingSword = new Animation(attackRight, duration, true); player = movingDown; } public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException { worldMap.draw(playerPositionX, playerPositionY); player.draw(shiftX, shiftY); g.drawString("Player X: " + playerPositionX + "\nPlayer Y: " + playerPositionY, 400, 20); if (quit == true) { g.drawString("Resume (R)", 250, 100); g.drawString("MainMenu (M)", 250, 150); g.drawString("Quit Game (Q)", 250, 200); if (quit==false) { g.clear(); } } } public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException { Input input = gc.getInput(); if(input.isKeyDown(Input.KEY_UP)) { player = movingUp; playerPositionY += delta * .1f; if(playerPositionY>162) playerPositionY -= delta * .1f; } if(input.isKeyDown(Input.KEY_DOWN)) { player = movingDown; playerPositionY -= delta * .1f; if(playerPositionY<-600) playerPositionY += delta * .1f; } if(input.isKeyDown(Input.KEY_RIGHT)) { player = movingRight; playerPositionX -= delta * .1f; if(playerPositionX<-840) playerPositionX += delta * .1f; } if(input.isKeyDown(Input.KEY_LEFT)) { player = movingLeft; playerPositionX += delta * .1f; if(playerPositionX>318) playerPositionX -= delta * .1f; } if(input.isKeyDown(Input.KEY_SPACE)) player = movingRightSwingingSword; if(input.isKeyDown(Input.KEY_ESCAPE)) quit = true; if(input.isKeyDown(Input.KEY_R)) if (quit == true) quit = false; if(input.isKeyDown(Input.KEY_M)) if (quit == true) {sbg.enterState(0); quit = false;} if(input.isKeyDown(Input.KEY_Q)) if (quit == true) System.exit(0); } public int getID() { return 1; } }

    Read the article

  • Need help limiting a join in Transact-sql

    - by MsLis
    I'm somewhat new to SQL and need help with query syntax. My issue involves 2 tables within a larger multi-table join under Transact-SQL (MS SQL Server 2000 Query Analyzer) I have ACCOUNTS and LOGINS, which are joined on 2 fields: Site & Subset. Both tables may have multiple rows for each Site/Subset combination. ACCOUNTS: | LOGINS: SITE SUBSET FIELD FIELD FIELD | SITE SUBSET USERID PASSWD alpha bravo blah blah blah | alpha bravo foo bar alpha charlie blah blah blah | alpha bravo bar foo alpha charlie bleh bleh blue | alpha charlie id ego delta bravo blah blah blah | delta bravo john welcome delta foxtrot blah blah blah | delta bravo jane welcome | delta bravo ken welcome | delta bravo barbara welcome I want to select all rows in ACCOUNTS which have LOGIN entries, but only 1 login per account. DESIRED RESULT: SITE SUBSET FIELD FIELD FIELD USERID PASSWD alpha bravo blah blah blah foo bar alpha charlie blah blah blah id ego alpha charlie bleh bleh blue id ego delta bravo blah blah blah jane welcome I don't really care which row from the login table I get, but the UserID and Password have to correspond. [Don't return invalid combinations like foo/foo or bar/bar] MS Access has a handy FIRST function, which can do this, but I haven't found an equivalent in TSQL. Also, if it makes a difference, other tables are joined to ACCOUNTS, but this is the only use of LOGINS in the structure. Thank you very much for any assistance.

    Read the article

  • collision with moving objects

    - by blacksheep
    tried to write a collision with the moving "floats" but did not succeed. maybe wrong place of the "collision" code? thanx 4 help! // // FruitsView.m // import "FruitsView.h" import "Constants.h" import "Utilities.h" define kFloat1Speed 0.15 define kFloat2Speed 0.3 define kFloat3Speed 0.2 @interface FruitsView (Private) - (void) stopTimer; @end @implementation FruitsView @synthesize apple, float1, float2, float3, posFloat1, posFloat2, posFloat3; -(void)onTimer { float1.center = CGPointMake(float1.center.x+posFloat1.x,float1.cen ter.y+posFloat1.y); if(float1.center.x 380 || float1.center.x < -60) posFloat1.x = -posFloat1.x; if(float1.center.y 100 || float1.center.y < -40) posFloat1.y = -posFloat1.y; float2.center = CGPointMake(float2.center.x+posFloat2.x,float2.cen ter.y+posFloat2.y); if(float2.center.x 380 || float2.center.x < -50) posFloat2.x = -posFloat2.x; if(float2.center.y 150 || float2.center.y < -30) posFloat2.y = -posFloat2.y; float3.center = CGPointMake(float3.center.x+posFloat3.x,float3.cen ter.y+posFloat3.y); if(float3.center.x 380 || float3.center.x < -70) posFloat3.x = -posFloat3.x; if(float3.center.y 100 || float3.center.y < -20) posFloat3.y = -posFloat3.y; if(CGRectIntersectsRect(apple.frame,float1.frame)) { if(apple.center.y float1.center.y) { posApple.y = -posApple.y; } } if(CGRectIntersectsRect(apple.frame,float2.frame)) { if(apple.center.y float2.center.y) { posFloat2.y = -posFloat2.y; } } if(CGRectIntersectsRect(apple.frame,float3.frame)) { if(apple.center.y float3.center.y) { posFloat3.y = -posFloat3.y; } } } pragma mark Initialisation/destruction (void)awakeFromNib { [NSTimer scheduledTimerWithTimeInterval:0.0001 target:self selector:@selector(onTimer) userInfo:nil repeats:YES]; posFloat1 = CGPointMake(kFloat1Speed, 0); posFloat2 = CGPointMake(kFloat2Speed, 0); posFloat3 = CGPointMake(kFloat3Speed, 0); timer = nil; modeLock = lockNotYetChosen; defaultSize = self.bounds.size.width; modal = self.tag; [[UIAccelerometer sharedAccelerometer] setDelegate:self]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationRepeatCount:1]; eadbea.transform = CGAffineTransformMakeScale(0.5,0.5); [UIView commitAnimations]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationRepeatCount:1]; apple.transform = CGAffineTransformMakeScale(0.5,0.5); [UIView commitAnimations]; } pragma mark Background animation processing (void) startTimer { if (!timer) { timer = [[NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES] retain]; } } (void) stopTimer { [timer invalidate]; [timer release]; timer = nil; } (void) check:(CGPoint*)position delta:(CGSize*)delta halfSize:(CGSize)halfSize forBouncingAgainst:(CGSize)containerSize { if ((position-x - halfSize.width)<0) { delta-width = fabsf(delta-width)*BOUNCE_DAMPING; position-x = halfSize.width; } if ((position-x + halfSize.width)containerSize.width) { delta-width = fabsf(delta-width)*-BOUNCE_DAMPING; position-x = containerSize.width - halfSize.width; } if ((position-y - halfSize.height)<0) { delta-height = fabsf(delta-height)*BOUNCE_DAMPING; position-y = halfSize.height; } if ((position-y + halfSize.height)containerSize.height) { delta-height = fabsf(delta-height)*-BOUNCE_DAMPING; position-y = containerSize.height - halfSize.height; } } (void) timerTick: (NSTimer*)timer { dragDelta = CGSizeScale(dragDelta, INERTIAL_DAMPING); if ((fabsf(dragDelta.width)DELTA_ZERO_THRESHOLD) || (fabsf(dragDelta.height)DELTA_ZERO_THRESHOLD)) { CGPoint ctr = CGPointApplyDelta(self.center, dragDelta); CGSize halfSize = CGSizeMake(self.bounds.size.width/4, self.bounds.size.height/4); [self check:&ctr delta:&dragDelta halfSize:halfSize forBouncingAgainst:self.superview.bounds.size]; self.center = ctr; } else { [self stopTimer]; } } pragma mark Input Handling (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent )event { NSSet allTouches = [event touchesForView:self]; if ([allTouches count]==1) { if (modeLocklockNotYetChosen) return; UITouch* anyTouch = [touches anyObject]; lastMove = anyTouch.timestamp; CGPoint now = [anyTouch locationInView: self.superview]; CGPoint then = [anyTouch previousLocationInView: self.superview]; dragDelta = CGPointDelta(now, then); self.center = CGPointApplyDelta(self.center, dragDelta); [self stopTimer]; } } (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { NSSet* allTouches = [event touchesForView:self]; if ([touches count]==[allTouches count]) { modeLock = lockNotYetChosen; if ((event.timestamp - lastMove) MOVEMENT_PAUSE_THRESHOLD) return; if ((fabsf(dragDelta.width)INERTIA_THRESHOLD) || (fabsf(dragDelta.height)INERTIA_THRESHOLD)) { [self startTimer]; } } } (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { modeLock = lockNotYetChosen; [self stopTimer]; } (void)dealloc { [float1 release]; [float2 release]; [float3 release]; [apple release]; [bear_head release]; [self stopTimer]; [super dealloc]; } @end

    Read the article

  • Mass Ball-to-Ball Collision Handling (as in, lots of balls)

    - by BlueThen
    Update: Found out that I was using the radius as the diameter, which was why the mtd was overcompensating. Hi, StackOverflow. I've written a Processing program awhile back simulating ball physics. Basically, I have a large number of balls (1000), with gravity turned on. Detection works great, but my issue is that they start acting weird when they're bouncing against other balls in all directions. I'm pretty confident this involves the handling. For the most part, I'm using Jay Conrod's code. One part that's different is if (distance > 1.0) return; which I've changed to if (distance < 1.0) return; because the collision wasn't even being performed with the first bit of code, I'm guessing that's a typo. The balls overlap when I use his code, which isn't what I was looking for. My attempt to fix it was to move the balls to the edge of each other: float angle = atan2(y - collider.y, x - collider.x); float distance = dist(x,y, balls[ID2].x,balls[ID2].y); x = collider.x + radius * cos(angle); y = collider.y + radius * sin(angle); This isn't correct, I'm pretty sure of that. I tried the correction algorithm in the previous ball-to-ball topic: // get the mtd Vector2d delta = (position.subtract(ball.position)); float d = delta.getLength(); // minimum translation distance to push balls apart after intersecting Vector2d mtd = delta.multiply(((getRadius() + ball.getRadius())-d)/d); // resolve intersection -- // inverse mass quantities float im1 = 1 / getMass(); float im2 = 1 / ball.getMass(); // push-pull them apart based off their mass position = position.add(mtd.multiply(im1 / (im1 + im2))); ball.position = ball.position.subtract(mtd.multiply(im2 / (im1 + im2))); except my version doesn't use vectors, and every ball's weight is 1. The resulting code I get is this: PVector delta = new PVector(collider.x - x, collider.y - y); float d = delta.mag(); PVector mtd = new PVector(delta.x * ((radius + collider.radius - d) / d), delta.y * ((radius + collider.radius - d) / d)); // push-pull apart based on mass x -= mtd.x * 0.5; y -= mtd.y * 0.5; collider.x += mtd.x * 0.5; collider.y += mtd.y * 0.5; This code seems to over-correct collisions. Which doesn't make sense to me because in no other way do I modify the x and y values of each ball, other than this. Some other part of my code could be wrong, but I don't know. Here's the snippet of the entire ball-to-ball collision handling I'm using: if (alreadyCollided.contains(new Integer(ID2))) // if the ball has already collided with this, then we don't need to reperform the collision algorithm return; Ball collider = (Ball) objects.get(ID2); PVector collision = new PVector(x - collider.x, y - collider.y); float distance = collision.mag(); if (distance == 0) { collision = new PVector(1,0); distance = 1; } if (distance < 1) return; PVector velocity = new PVector(vx,vy); PVector velocity2 = new PVector(collider.vx, collider.vy); collision.div(distance); // normalize the distance float aci = velocity.dot(collision); float bci = velocity2.dot(collision); float acf = bci; float bcf = aci; vx += (acf - aci) * collision.x; vy += (acf - aci) * collision.y; collider.vx += (bcf - bci) * collision.x; collider.vy += (bcf - bci) * collision.y; alreadyCollided.add(new Integer(ID2)); collider.alreadyCollided.add(new Integer(ID)); PVector delta = new PVector(collider.x - x, collider.y - y); float d = delta.mag(); PVector mtd = new PVector(delta.x * ((radius + collider.radius - d) / d), delta.y * ((radius + collider.radius - d) / d)); // push-pull apart based on mass x -= mtd.x * 0.2; y -= mtd.y * 0.2; collider.x += mtd.x * 0.2; collider.y += mtd.y * 0.2; Thanks. (Apologies for lack of sources, stackoverflow thinks I'm a spammer)

    Read the article

  • Convolving two signals

    - by John Elway
    Calculate the convolution of the following signals (your answer will be in the form of an equation): h[n] = delta[n-1] + delta[n+1], x[n] = delta[n-a] + delta[n+b] I'm lost as to what I do with h and x. Do I simply multiply them? h[n]*x[n]? I programmed convolution with several types of blurs and edge detectors, but I don't see how to translate that knowledge to this problem. please help!

    Read the article

  • LibGDX onTouch() method Array and flip method

    - by johnny-b
    How can I add this on my application. i want to use the onTouch() method from the implementation of the InputProcessor to kill the enemies on screen. how do i do that? do i have to do anything to the enemy class? also i am trying to add a Array of enemies and it keeps throwing exceptions or the bullet now is facing LEFT <--- again after I used the flip method in the bullet class. All the code is below so please anyone feel free to have a look thanks. please help Thank you M // This is the bullet class. public class Bullet extends Sprite { public static final float BULLET_HOMING = 6000; public static final float BULLET_SPEED = 300; private Vector2 velocity; private float lifetime; private Rectangle bul; public Bullet(float x, float y) { velocity = new Vector2(0, 0); setPosition(x, y); AssetLoader.bullet1.flip(true, false); AssetLoader.bullet2.flip(true, false); setSize(AssetLoader.bullet1.getWidth(), AssetLoader.bullet1.getHeight()); bul = new Rectangle(); } public void update(float delta) { float targetX = GameWorld.getBall().getX(); float targetY = GameWorld.getBall().getY(); float dx = targetX - getX(); float dy = targetY - getY(); float distToTarget = (float) Math.sqrt(dx * dx + dy * dy); dx /= distToTarget; dy /= distToTarget; dx *= BULLET_HOMING; dy *= BULLET_HOMING; velocity.x += dx * delta; velocity.y += dy * delta; float vMag = (float) Math.sqrt(velocity.x * velocity.x + velocity.y * velocity.y); velocity.x /= vMag; velocity.y /= vMag; velocity.x *= BULLET_SPEED; velocity.y *= BULLET_SPEED; bul.set(getX(), getY(), getOriginX(), getOriginY()); Vector2 v = velocity.cpy().scl(delta); setPosition(getX() + v.x, getY() + v.y); setOriginCenter(); setRotation(velocity.angle()); } public Rectangle getBounds() { return bul; } public Rectangle getBounds1() { return this.getBoundingRectangle(); } } // This is the class where i load all the images from public class AssetLoader { public static Texture texture; public static TextureRegion bg, ball1, ball2; public static Animation bulletAnimation, ballAnimation; public static Sprite bullet1, bullet2; public static void load() { texture = new Texture(Gdx.files.internal("SpriteN1.png")); texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest); bg = new TextureRegion(texture, 80, 421, 395, 30); bg.flip(false, true); ball1 = new TextureRegion(texture, 0, 321, 32, 32); ball1.flip(false, true); ball2 = new TextureRegion(texture, 32, 321, 32, 32); ball2.flip(false, true); bullet1 = new Sprite(texture, 380, 350, 45, 20); bullet1.flip(false, true); bullet2 = new Sprite(texture, 425, 350, 45, 20); bullet2.flip(false, true); TextureRegion[] balls = { ball1, ball2 }; ballAnimation = new Animation(0.16f, balls); ballAnimation.setPlayMode(Animation.PlayMode.LOOP); } Sprite[] bullets = { bullet1, bullet2 }; bulletAnimation = new Animation(0.06f, aims); bulletAnimation.setPlayMode(Animation.PlayMode.LOOP); } public static void dispose() { texture.dispose(); } // This is for the rendering or drawing onto the screen/canvas. public class GameRenderer { private Bullet bullet; private Ball ball; public GameRenderer(GameWorld world) { myWorld = world; cam = new OrthographicCamera(); cam.setToOrtho(true, 480, 320); batcher = new SpriteBatch(); // Attach batcher to camera batcher.setProjectionMatrix(cam.combined); shapeRenderer = new ShapeRenderer(); shapeRenderer.setProjectionMatrix(cam.combined); // Call helper methods to initialize instance variables initGameObjects(); initAssets(); } private void initGameObjects() { ball = GameWorld.getBall(); bullet = myWorld.getBullet(); scroller = myWorld.getScroller(); } private void initAssets() { ballAnimation = AssetLoader.ballAnimation; bulletAnimation = AssetLoader.bulletAnimation; } public void render(float runTime) { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT); batcher.begin(); batcher.disableBlending(); batcher.enableBlending(); batcher.draw(AssetLoader.ballAnimation.getKeyFrame(runTime), ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight()); batcher.draw(AssetLoader.bulletAnimation.getKeyFrame(runTime), bullet.getX(), bullet.getY(), bullet.getOriginX(), bullet.getOriginY(), bullet.getWidth(), bullet.getHeight(), 1.0f, 1.0f, bullet.getRotation()); // End SpriteBatch batcher.end(); } } // this is to load the image etc on the screen i guess public class GameWorld { public static Ball ball; private Bullet bullet; private ScrollHandler scroller; public GameWorld() { ball = new Ball(480, 273, 32, 32); bullet = new Bullet(10, 10); scroller = new ScrollHandler(0); } public void update(float delta) { ball.update(delta); bullet.update(delta); scroller.update(delta); } public static Ball getBall() { return ball; } public ScrollHandler getScroller() { return scroller; } public Bullet getBullet() { return bullet; } } //This is the input handler class public class InputHandler implements InputProcessor { private Ball myBall; private Bullet bullet; private GameRenderer aims; // Ask for a reference to the Soldier when InputHandler is created. public InputHandler(Ball ball) { myBall = ball; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { return false; } @Override public boolean keyDown(int keycode) { return false; } @Override public boolean keyUp(int keycode) { return false; } @Override public boolean keyTyped(char character) { return false; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return false; } @Override public boolean mouseMoved(int screenX, int screenY) { return false; } @Override public boolean scrolled(int amount) { return false; } } i am rendering all graphics in a GameRender class and a gameworld class if you need more info please let me know I am trying to make the array work but keep finding that when an array is initialized then the bullet fips back to the original and ends up being backwards???? and if I create an array I keep getting Exceptions throw??? Thank you for any help given.

    Read the article

  • Hue, saturation, brightness, contrast effect in hlsl

    - by Vibhore Tanwer
    I am new to pixel shader, and I am trying to write a simple brightness, contrast, hue, saturation effect. I have written a shader for it but I doubt that my shader is not providing me correct result, Brightness, contrast, saturation is working fine, problem is with hue. if I apply hue between -1 to 1, it seems to be working fine, but to make things more sharp, I need to apply hue value between -180 and 180, like we can apply hue in Paint.NET. Here is my code. // Amount to shift the Hue, range 0 to 6 float Hue; float Brightness; float Contrast; float Saturation; float Alpha; sampler Samp : register(S0); // Converts the rgb value to hsv, where H's range is -1 to 5 float3 rgb_to_hsv(float3 RGB) { float r = RGB.x; float g = RGB.y; float b = RGB.z; float minChannel = min(r, min(g, b)); float maxChannel = max(r, max(g, b)); float h = 0; float s = 0; float v = maxChannel; float delta = maxChannel - minChannel; if (delta != 0) { s = delta / v; if (r == v) h = (g - b) / delta; else if (g == v) h = 2 + (b - r) / delta; else if (b == v) h = 4 + (r - g) / delta; } return float3(h, s, v); } float3 hsv_to_rgb(float3 HSV) { float3 RGB = HSV.z; float h = HSV.x; float s = HSV.y; float v = HSV.z; float i = floor(h); float f = h - i; float p = (1.0 - s); float q = (1.0 - s * f); float t = (1.0 - s * (1 - f)); if (i == 0) { RGB = float3(1, t, p); } else if (i == 1) { RGB = float3(q, 1, p); } else if (i == 2) { RGB = float3(p, 1, t); } else if (i == 3) { RGB = float3(p, q, 1); } else if (i == 4) { RGB = float3(t, p, 1); } else /* i == -1 */ { RGB = float3(1, p, q); } RGB *= v; return RGB; } float4 mainPS(float2 uv : TEXCOORD) : COLOR { float4 col = tex2D(Samp, uv); float3 hsv = rgb_to_hsv(col.xyz); hsv.x += Hue; // Put the hue back to the -1 to 5 range //if (hsv.x > 5) { hsv.x -= 6.0; } hsv = hsv_to_rgb(hsv); float4 newColor = float4(hsv,col.w); float4 colorWithBrightnessAndContrast = newColor; colorWithBrightnessAndContrast.rgb /= colorWithBrightnessAndContrast.a; colorWithBrightnessAndContrast.rgb = colorWithBrightnessAndContrast.rgb + Brightness; colorWithBrightnessAndContrast.rgb = ((colorWithBrightnessAndContrast.rgb - 0.5f) * max(Contrast + 1.0, 0)) + 0.5f; colorWithBrightnessAndContrast.rgb *= colorWithBrightnessAndContrast.a; float greyscale = dot(colorWithBrightnessAndContrast.rgb, float3(0.3, 0.59, 0.11)); colorWithBrightnessAndContrast.rgb = lerp(greyscale, colorWithBrightnessAndContrast.rgb, col.a * (Saturation + 1.0)); return colorWithBrightnessAndContrast; } technique TransformTexture { pass p0 { PixelShader = compile ps_2_0 mainPS(); } } Please If anyone can help me learning what am I doing wrong or any suggestions? Any help will be of great value. EDIT: Images of the effect at hue 180: On the left hand side, the effect I got with @teodron answer. On the right hand side, The effect Paint.NET gives and I'm trying to reproduce.

    Read the article

  • what does calling ´this´ outside of a jquery plugin refer to

    - by Richard
    Hi, I am using the liveTwitter plugin The problem is that I need to stop the plugin from hitting the Twitter api. According to the documentation I need to do this $("#tab1 .container_twitter_status").each(function(){ this.twitter.stop(); }); Already, the each does not make sense on an id and what does this refer to? Anyway, I get an undefined error. I will paste the plugin code and hope it makes sense to somebody MY only problem thusfar with this plugin is that I need to be able to stop it. thanks in advance, Richard /* * jQuery LiveTwitter 1.5.0 * - Live updating Twitter plugin for jQuery * * Copyright (c) 2009-2010 Inge Jørgensen (elektronaut.no) * Licensed under the MIT license (MIT-LICENSE.txt) * * $Date: 2010/05/30$ */ /* * Usage example: * $("#twitterSearch").liveTwitter('bacon', {limit: 10, rate: 15000}); */ (function($){ if(!$.fn.reverse){ $.fn.reverse = function() { return this.pushStack(this.get().reverse(), arguments); }; } $.fn.liveTwitter = function(query, options, callback){ var domNode = this; $(this).each(function(){ var settings = {}; // Handle changing of options if(this.twitter) { settings = jQuery.extend(this.twitter.settings, options); this.twitter.settings = settings; if(query) { this.twitter.query = query; } this.twitter.limit = settings.limit; this.twitter.mode = settings.mode; if(this.twitter.interval){ this.twitter.refresh(); } if(callback){ this.twitter.callback = callback; } // ..or create a new twitter object } else { // Extend settings with the defaults settings = jQuery.extend({ mode: 'search', // Mode, valid options are: 'search', 'user_timeline' rate: 15000, // Refresh rate in ms limit: 10, // Limit number of results refresh: true }, options); // Default setting for showAuthor if not provided if(typeof settings.showAuthor == "undefined"){ settings.showAuthor = (settings.mode == 'user_timeline') ? false : true; } // Set up a dummy function for the Twitter API callback if(!window.twitter_callback){ window.twitter_callback = function(){return true;}; } this.twitter = { settings: settings, query: query, limit: settings.limit, mode: settings.mode, interval: false, container: this, lastTimeStamp: 0, callback: callback, // Convert the time stamp to a more human readable format relativeTime: function(timeString){ var parsedDate = Date.parse(timeString); var delta = (Date.parse(Date()) - parsedDate) / 1000; var r = ''; if (delta < 60) { r = delta + ' seconds ago'; } else if(delta < 120) { r = 'a minute ago'; } else if(delta < (45*60)) { r = (parseInt(delta / 60, 10)).toString() + ' minutes ago'; } else if(delta < (90*60)) { r = 'an hour ago'; } else if(delta < (24*60*60)) { r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago'; } else if(delta < (48*60*60)) { r = 'a day ago'; } else { r = (parseInt(delta / 86400, 10)).toString() + ' days ago'; } return r; }, // Update the timestamps in realtime refreshTime: function() { var twitter = this; $(twitter.container).find('span.time').each(function(){ $(this).html(twitter.relativeTime(this.timeStamp)); }); }, // Handle reloading refresh: function(initialize){ var twitter = this; if(this.settings.refresh || initialize) { var url = ''; var params = {}; if(twitter.mode == 'search'){ params.q = this.query; if(this.settings.geocode){ params.geocode = this.settings.geocode; } if(this.settings.lang){ params.lang = this.settings.lang; } if(this.settings.rpp){ params.rpp = this.settings.rpp; } else { params.rpp = this.settings.limit; } // Convert params to string var paramsString = []; for(var param in params){ if(params.hasOwnProperty(param)){ paramsString[paramsString.length] = param + '=' + encodeURIComponent(params[param]); } } paramsString = paramsString.join("&"); url = "http://search.twitter.com/search.json?"+paramsString+"&callback=?"; } else if(twitter.mode == 'user_timeline') { url = "http://api.twitter.com/1/statuses/user_timeline/"+encodeURIComponent(this.query)+".json?count="+twitter.limit+"&callback=?"; } else if(twitter.mode == 'list') { var username = encodeURIComponent(this.query.user); var listname = encodeURIComponent(this.query.list); url = "http://api.twitter.com/1/"+username+"/lists/"+listname+"/statuses.json?per_page="+twitter.limit+"&callback=?"; } $.getJSON(url, function(json) { var results = null; if(twitter.mode == 'search'){ results = json.results; } else { results = json; } var newTweets = 0; $(results).reverse().each(function(){ var screen_name = ''; var profile_image_url = ''; if(twitter.mode == 'search') { screen_name = this.from_user; profile_image_url = this.profile_image_url; created_at_date = this.created_at; } else { screen_name = this.user.screen_name; profile_image_url = this.user.profile_image_url; // Fix for IE created_at_date = this.created_at.replace(/^(\w+)\s(\w+)\s(\d+)(.*)(\s\d+)$/, "$1, $3 $2$5$4"); } var userInfo = this.user; var linkified_text = this.text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) { return m.link(m); }); linkified_text = linkified_text.replace(/@[A-Za-z0-9_]+/g, function(u){return u.link('http://twitter.com/'+u.replace(/^@/,''));}); linkified_text = linkified_text.replace(/#[A-Za-z0-9_\-]+/g, function(u){return u.link('http://search.twitter.com/search?q='+u.replace(/^#/,'%23'));}); if(!twitter.settings.filter || twitter.settings.filter(this)) { if(Date.parse(created_at_date) > twitter.lastTimeStamp) { newTweets += 1; var tweetHTML = '<div class="tweet tweet-'+this.id+'">'; if(twitter.settings.showAuthor) { tweetHTML += '<img width="24" height="24" src="'+profile_image_url+'" />' + '<p class="text"><span class="username"><a href="http://twitter.com/'+screen_name+'">'+screen_name+'</a>:</span> '; } else { tweetHTML += '<p class="text"> '; } tweetHTML += linkified_text + ' <span class="time">'+twitter.relativeTime(created_at_date)+'</span>' + '</p>' + '</div>'; $(twitter.container).prepend(tweetHTML); var timeStamp = created_at_date; $(twitter.container).find('span.time:first').each(function(){ this.timeStamp = timeStamp; }); if(!initialize) { $(twitter.container).find('.tweet-'+this.id).hide().fadeIn(); } twitter.lastTimeStamp = Date.parse(created_at_date); } } }); if(newTweets > 0) { // Limit number of entries $(twitter.container).find('div.tweet:gt('+(twitter.limit-1)+')').remove(); // Run callback if(twitter.callback){ twitter.callback(domNode, newTweets); } // Trigger event $(domNode).trigger('tweets'); } }); } }, start: function(){ var twitter = this; if(!this.interval){ this.interval = setInterval(function(){twitter.refresh();}, twitter.settings.rate); this.refresh(true); } }, stop: function(){ if(this.interval){ clearInterval(this.interval); this.interval = false; } } }; var twitter = this.twitter; this.timeInterval = setInterval(function(){twitter.refreshTime();}, 5000); this.twitter.start(); } }); return this; }; })(jQuery);

    Read the article

  • Compatibility between DirectX 9 and DirectX 10 shaders

    - by Delta
    I am a beginner to game development and as I am used to programming in C# I decided to go for XNA. I've been playing around with it for a while and now I am learning the basics of HLSL shaders, I have noticed in the MSDN documentation that there have been some syntax changes in HLSL between DirectX 9 and DirectX 10, for example, the Sampler type Since I am having some troubles with my desktop pc, I am using my laptop which video card only supports DirectX 9.0c. Then I'm gonna have to write my shaders using the DirectX 9 syntax, right? So I am wondering, will my HLSL shaders written using the DirectX 9 syntax work on a system running DirectX 10 (or higher)?

    Read the article

  • 3Ds Max is exporting model with more normals than vertices

    - by Delta
    I made a simple teapot with the "Create Standard Primitives" option and exported it as a collada file, ended up with this: < float_array id="Teapot001-POSITION-array" count="1590" < float_array id="Teapot001-Normal0-array" count="9216" For what I know there should be only one normal per vertex, am I wrong? What am I supposed to do with that much normals? Just put them on the normal buffer all at once normally?

    Read the article

  • What is UVIndex and how do I use it on OpenGL?

    - by Delta
    I am a noob in OpenGL ES 2.0 (for WebGL) and I'm trying to draw a simple model I've made with a 3D tool and exported to .fbx format. I've been able to draw some models that only have: A vertex buffer, a index buffer for the vertices, a normal buffer and a texture coordinate buffer, but this model now has a "UVIndex" and I'm not sure where am I supposed to put this UVIndex. My code looks like this: GL.bindBuffer(GL.ARRAY_BUFFER, this.Model.House.VertexBuffer); GL.vertexAttribPointer(this.Shader.TextureAndLighting.Attribute["vPosition"],3,GL.FLOAT, false, 0, 0); GL.bindBuffer(GL.ARRAY_BUFFER, this.Model.House.NormalBuffer); GL.vertexAttribPointer(this.Shader.TextureAndLighting.Attribute["vNormal"], 3, GL.FLOAT, false, 0, 0); GL.bindBuffer(GL.ARRAY_BUFFER, this.Model.House.TexCoordBuffer); GL.vertexAttribPointer(this.Shader.TextureAndLighting.Attribute["TexCoord"], 2, GL.FLOAT, false, 0, 0); GL.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, this.Model.House.IndexBuffer); GL.bindTexture(GL.TEXTURE_2D, this.Texture.HTex1); GL.activeTexture(GL.TEXTURE0); GL.drawElements(GL.TRIANGLES, this.Model.House.IndexBuffer.Length, GL.UNSIGNED_SHORT, 0); But my model renders totally incorrect and I think it has to do with the fact that I am ignoring this "UVIndex" in the .fbx file, since I've never drawn any model that uses this UVIndex I really have no clue on what to do with it. This is the json file containing the model's data: http://pastebin.com/raw.php?i=G294TVmz

    Read the article

  • Convert RGB value to HSV

    - by marionmaiden
    I've found a method on the Internet to convert RGB values to HSV values. Unfortunately, when the values are R=G=B, I'm getting a NaN, because of the 0/0 operation. Do you know if there is an implemented method for this conversion in Java, or what do I have to do when I get the 0/0 division to get the right value of the HSV? Here comes my method, adapted from some code on the Internet: public static double[] RGBtoHSV(double r, double g, double b){ double h, s, v; double min, max, delta; min = Math.min(Math.min(r, g), b); max = Math.max(Math.max(r, g), b); // V v = max; delta = max - min; // S if( max != 0 ) s = delta / max; else { s = 0; h = -1; return new double[]{h,s,v}; } // H if( r == max ) h = ( g - b ) / delta; // between yellow & magenta else if( g == max ) h = 2 + ( b - r ) / delta; // between cyan & yellow else h = 4 + ( r - g ) / delta; // between magenta & cyan h *= 60; // degrees if( h < 0 ) h += 360; return new double[]{h,s,v}; }

    Read the article

  • "Pattern matching" of algebraic type data constructors

    - by jetxee
    Let's consider a data type with many constructors: data T = Alpha Int | Beta Int | Gamma Int Int | Delta Int I want to write a function to check if two values are produced with the same constructor: sameK (Alpha _) (Alpha _) = True sameK (Beta _) (Beta _) = True sameK (Gamma _ _) (Gamma _ _) = True sameK _ _ = False Maintaining sameK is not much fun, it is potentially buggy. For example, when new constructors are added to T, it's easy to forget to update sameK. I omitted one line to give an example: -- it’s easy to forget: -- sameK (Delta _) (Delta _) = True The question is how to avoid boilerplate in sameK? Or how to make sure it checks for all T constructors? The workaround I found is to use separate data types for each of the constructors, deriving Data.Typeable, and declaring a common type class, but I don't like this solution, because it is much less readable and otherwise just a simple algebraic type works for me: {-# LANGUAGE DeriveDataTypeable #-} import Data.Typeable class Tlike t where value :: t -> t value = id data Alpha = Alpha Int deriving Typeable data Beta = Beta Int deriving Typeable data Gamma = Gamma Int Int deriving Typeable data Delta = Delta Int deriving Typeable instance Tlike Alpha instance Tlike Beta instance Tlike Gamma instance Tlike Delta sameK :: (Tlike t, Typeable t, Tlike t', Typeable t') => t -> t' -> Bool sameK a b = typeOf a == typeOf b

    Read the article

  • How do you prevent Git from printing 'remote:' on each line of the output of a post-recieve hook?

    - by Matt Hodan
    I recently configured an EC2 instance with a Git deployment workflow that resembles Heroku, but I can't seem to figure out how Heroku prevents the Git post-receive hook from outputting 'remote:' on each line. Consider the following two examples (one from my EC2 project and one from a Heroku project): My EC2 project: git push prod master Counting objects: 9, done. Delta compression using up to 2 threads. Compressing objects: 100% (5/5), done. Writing objects: 100% (5/5), 456 bytes, done. Total 5 (delta 3), reused 0 (delta 0) remote: remote: Receiving push remote: Deploying updated files (by resetting HEAD) remote: HEAD is now at bf17da8 test commit remote: Running bundler to install gem dependencies remote: Fetching source index for http://rubygems.org/ remote: Installing rake (0.8.7) remote: Installing abstract (1.0.0) ... remote: Installing railties (3.0.0) remote: Installing rails (3.0.0) remote: Your bundle is complete! It was installed into ./.bundle/gems remote: Launching (by restarting Passenger)... done remote: To ssh://[email protected]/~/apps/app_name e8bd06f..bf17da8 master -> master Heroku: $> git push heroku master Counting objects: 179, done. Delta compression using up to 2 threads. Compressing objects: 100% (89/89), done. Writing objects: 100% (105/105), 42.70 KiB, done. Total 105 (delta 53), reused 0 (delta 0) -----> Heroku receiving push -----> Rails app detected -----> Gemfile detected, running Bundler version 1.0.3 Unresolved dependencies detected; Installing... Using --without development:test Fetching source index for http://rubygems.org/ Installing rake (0.8.7) Installing abstract (1.0.0) ... Installing railties (3.0.0) Installing rails (3.0.0) Your bundle is complete! It was installed into ./.bundle/gems Compiled slug size is 4.8MB -----> Launching... done http://your_app_name.heroku.com deployed to Heroku To [email protected]:your_app_name.git 3bf6e8d..642f01a master -> master

    Read the article

  • Highlighting Changes in Java

    - by Buzz Lightyear
    Basically, i have done my program so that it will display differences in strings and display the whole line. I want to highlight (in a colour) the differences in the line. Example: Original at line 5 <rect x="60.01" width="855.38" id="rect_1" y="-244.35" height="641.13" style="stroke-width: 1; stroke: rgb(0, 0, 0); fill: none; "/> Edited at line 5 <rect x="298.43" width="340.00" y="131.12" height="380.00" id="rect_1" style="stroke-width: 1; stroke: rgb(0, 0, 0); fill: rgb(255, 102, 0); "/> In this example, the width is different from the 'original' from the 'edited' version. I would like to be able to highlight that difference and any other difference. My code so far: Patch patch = DiffUtils.diff(centralFile, remoteFile); StringBuffer resultsBuff = new StringBuffer(remoteFileData.length); for (Delta delta : patch.getDeltas()) { resultsBuff.append("Original at line " + delta.getOriginal().getPosition() + "\n"); for (Object line : delta.getOriginal().getLines()) { resultsBuff.append(" " + line + "\n"); } resultsBuff.append("Edited at line " + delta.getRevised().getPosition() + "\n"); for (Object line : delta.getRevised().getLines()) { resultsBuff.append(" " + line + "\n"); } resultsBuff.append("\n"); } return resultsBuff.toString(); } That will display two whole lines like the example before (the original and the edited version) I want to be able to highlight the changes that have actually been made, is there any way to do this in Java?

    Read the article

  • Registering InputListener in libGDX

    - by JPRO
    I'm just getting started with libGDX and have run into a snag registering an InputListener for a button. I've gone through many examples and this code appears correct to me but the associated callback never triggers ("touched" is not printed to console). I'm just posting the code with the abstract game screen and the implementing screen. The application starts successfully with a label of "Exit" in the bottom left hand corner, but clicking the button/label does nothing. I'm guessing the fix is something simple. What am I overlooking? public abstract class GameScreen<T> implements Screen { protected final T game; protected final SpriteBatch batch; protected final Stage stage; public GameScreen(T game) { this.game = game; this.batch = new SpriteBatch(); this.stage = new Stage(0, 0, true); } @Override public final void render(float delta) { update(delta); // Clear the screen with the given RGB color (black) Gdx.gl.glClearColor(0f, 0f, 0f, 1f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.act(delta); stage.draw(); } public abstract void update(float delta); @Override public void resize(int width, int height) { stage.setViewport(width, height, true); } @Override public void show() { Gdx.input.setInputProcessor(stage); } // hide, pause, resume, dipose } public class ExampleScreen extends GameScreen<MyGame> { private TextButton exitButton; public ExampleScreen(MyGame game) { super(game); } @Override public void show() { super.show(); TextButton.TextButtonStyle buttonStyle = new TextButton.TextButtonStyle(); buttonStyle.font = Font.getFont("Origicide", 32); buttonStyle.fontColor = Color.WHITE; exitButton = new TextButton("Exit", buttonStyle); exitButton.addListener(new InputListener() { @Override public void touchUp (InputEvent event, float x, float y, int pointer, int button) { System.out.println("touched"); } }); stage.addActor(exitButton); } @Override public void update(float delta) { } }

    Read the article

  • libgdx arrays onTouch() method and delays for objects

    - by johnny-b
    i am trying to create random bullets but it is not working for some reason. also how can i make a delay so the bullets come every 30 seconds or 1 minute???? also the onTouch method does not work and it is not taking the bullet away???? shall i put the array in the GameRender class? thanks public class GameWorld { public static Ball ball; private Bullet bullet1; private ScrollHandler scroller; private Array<Bullet> bullets = new Array<Bullet>(); public GameWorld() { ball = new Ball(280, 273, 32, 32); bullet = new Bullet(-300, 200); scroller = new ScrollHandler(0); bullets.add(new Bullet(bullet.getX(), bullet.getY())); bullets = new Array<Bullet>(); Bullet bullet = null; float bulletX = 0.0f; float bulletY = 0.0f; for (int i=0; i < 10; i++) { bulletX = MathUtils.random(-10, 10); bulletY = MathUtils.random(-10, 10); bullet = new Bullet(bulletX, bulletY); bullets.add(bullet); } } public void update(float delta) { ball.update(delta); bullet.update(delta); scroller.update(delta); } public static Ball getBall() { return ball; } public ScrollHandler getScroller() { return scroller; } public Bullet getBullet1() { return bullet1; } } i also tried this and it is not working, i used this in the GameRender class Array<Bullet> enemies=new Array<Bullet>(); //in the constructor of the class enemies.add(new Bullet(bullet.getX(), bullet.getY())); // this throws an exception for some reason??? this is in the render method for(int i=0; i<bullet.size; i++) bullet.get(i).draw(batcher); //this i am using in any method that will allow me from the constructor to update to render for(int i=0; i<bullet.size; i++) bullet.get(i).update(delta); this is not taking the bullet out @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { for(int i=0; i<bullet.size; i++) if(bullet.get(i).getBounds().contains(screenX,screenY)) bullet.removeIndex(i--); return false; } thanks for the help anyone.

    Read the article

  • Use depth bias for shadows in deferred shading

    - by cubrman
    We are building a deferred shading engine and we have a problem with shadows. To add shadows we use two maps: the first one stores the depth of the scene captured by the player's camera and the second one stores the depth of the scene captured by the light's camera. We then ran a shader that analyzes the two maps and outputs the third one with the ready shadow areas for the current frame. The problem we face is a classic one: Self-Shadowing: A standard way to solve this is to use the slope-scale depth bias and depth offsets, however as we are doing things in a deferred way we cannot employ this algorithm. Any attempts to set depth bias when capturing light's view depth produced no or unsatisfying results. So here is my question: MSDN article has a convoluted explanation of the slope-scale: bias = (m × SlopeScaleDepthBias) + DepthBias Where m is the maximum depth slope of the triangle being rendered, defined as: m = max( abs(delta z / delta x), abs(delta z / delta y) ) Could you explain how I can implement this algorithm manually in a shader? Maybe there are better ways to fix this problem for deferred shadows?

    Read the article

  • Optimal communication pattern to update subscribers

    - by hpc
    What is the optimal way to update the subscriber's local model on changes C on a central model M? ( M + C - M_c) The update can be done by the following methods: Publish the updated model M_c to all subscribers. Drawback: if the model is big in contrast to the change it results in much more data to be communicated. Publish change C to all subscribes. The subscribers will then update their local model in the same way as the server does. Drawback: The client needs to know the business logic to update the model in the same way as the server. It must be assured that the subscribed model stays equal to the central model. Calculate the delta (or patch) of the change (M_c - M = D_c) and transfer the delta. Drawback: This requires that calculating and applying the delta (M + D_c = M_c) is an cheap/easy operation. If a client newly subscribes it must be initialized. This involves sending the current model M. So method 1 is always required. Think of playing chess as a concrete example: Subscribers send moves and want to see the latest chess board state. The server checks validity of the move and applies it to the chess board. The server can then send the updated chessboard (method 1) or just send the move (method 2) or send the delta (method 3): remove piece on field D4, put tower on field D8.

    Read the article

  • Python TEA implementation

    - by Gaks
    Anybody knows proper python implementation of TEA (Tiny Encryption Algorithm)? I tried the one I've found here: http://sysadminco.com/code/python-tea/ - but it does not seem to work properly. It returns different results than other implementations in C or Java. I guess it's caused by completely different data types in python (or no data types in fact). Here's the code and an example: def encipher(v, k): y=v[0];z=v[1];sum=0;delta=0x9E3779B9;n=32 w=[0,0] while(n>0): y += (z << 4 ^ z >> 5) + z ^ sum + k[sum & 3] y &= 4294967295L # maxsize of 32-bit integer sum += delta z += (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3] z &= 4294967295L n -= 1 w[0]=y; w[1]=z return w def decipher(v, k): y=v[0] z=v[1] sum=0xC6EF3720 delta=0x9E3779B9 n=32 w=[0,0] # sum = delta<<5, in general sum = delta * n while(n>0): z -= (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3] z &= 4294967295L sum -= delta y -= (z << 4 ^ z >> 5) + z ^ sum + k[sum&3] y &= 4294967295L n -= 1 w[0]=y; w[1]=z return w Python example: >>> import tea >>> key = [0xbe168aa1, 0x16c498a3, 0x5e87b018, 0x56de7805] >>> v = [0xe15034c8, 0x260fd6d5] >>> res = tea.encipher(v, key) >>> "%X %X" % (res[0], res[1]) **'70D16811 F935148F'** C example: #include <unistd.h> #include <stdio.h> void encipher(unsigned long *const v,unsigned long *const w, const unsigned long *const k) { register unsigned long y=v[0],z=v[1],sum=0,delta=0x9E3779B9, a=k[0],b=k[1],c=k[2],d=k[3],n=32; while(n-->0) { sum += delta; y += (z << 4)+a ^ z+sum ^ (z >> 5)+b; z += (y << 4)+c ^ y+sum ^ (y >> 5)+d; } w[0]=y; w[1]=z; } int main() { unsigned long v[] = {0xe15034c8, 0x260fd6d5}; unsigned long key[] = {0xbe168aa1, 0x16c498a3, 0x5e87b018, 0x56de7805}; unsigned long res[2]; encipher(v, res, key); printf("%X %X\n", res[0], res[1]); return 0; } $ ./tea **D6942D68 6F87870D** Please note, that both examples were run with the same input data (v and key), but results were different. I'm pretty sure C implementation is correct - it comes from a site referenced by wikipedia (I couldn't post a link to it because I don't have enough reputation points yet - some antispam thing)

    Read the article

  • readonly keyword

    - by nmarun
    This is something new that I learned about the readonly keyword. Have a look at the following class: 1: public class MyClass 2: { 3: public string Name { get; set; } 4: public int Age { get; set; } 5:  6: private readonly double Delta; 7:  8: public MyClass() 9: { 10: Initializer(); 11: } 12:  13: public MyClass(string name = "", int age = 0) 14: { 15: Name = name; 16: Age = age; 17: Initializer(); 18: } 19:  20: private void Initializer() 21: { 22: Delta = 0.2; 23: } 24: } I have a couple of public properties and a private readonly member. There are two constructors – one that doesn’t take any parameters and the other takes two parameters to initialize the public properties. I’m also calling the Initializer method in both constructors to initialize the readonly member. Now when I build this, the code breaks and the Error window says: “A readonly field cannot be assigned to (except in a constructor or a variable initializer)” Two things after I read this message: It’s such a negative statement. I’d prefer something like: “A readonly field can be assigned to (or initialized) only in a constructor or through a variable initializer” But in my defense, I AM assigning it in a constructor (only indirectly). All I’m doing is creating a method that does it and calling it in a constructor. Turns out, .net was not ‘frameworked’ this way. We need to have the member initialized directly in the constructor. If you have multiple constructors, you can just use the ‘this’ keyword on all except the default constructors to call the default constructor. This default constructor can then initialize your readonly members. This will ensure you’re not repeating the code in multiple places. A snippet of what I’m talking can be seen below: 1: public class Person 2: { 3: public int UniqueNumber { get; set; } 4: public string Name { get; set; } 5: public int Age { get; set; } 6: public DateTime DateOfBirth { get; set; } 7: public string InvoiceNumber { get; set; } 8:  9: private readonly string Alpha; 10: private readonly int Beta; 11: private readonly double Delta; 12: private readonly double Gamma; 13:  14: public Person() 15: { 16: Alpha = "FDSA"; 17: Beta = 2; 18: Delta = 3.0; 19: Gamma = 0.0989; 20: } 21:  22: public Person(int uniqueNumber) : this() 23: { 24: UniqueNumber = uniqueNumber; 25: } 26: } See the syntax in line 22 and you’ll know what I’m talking about. So the default constructor gets called before the one in line 22. These are known as constructor initializers and they allow one constructor to call another. The other ‘myth’ I had about readonly members is that you can set it’s value only once. This was busted as well (I recall Adam and Jamie’s show). Say you’ve initialized the readonly member through a variable initializer. You can over-write this value in any of the constructors any number of times. 1: public class Person 2: { 3: public int UniqueNumber { get; set; } 4: public string Name { get; set; } 5: public int Age { get; set; } 6: public DateTime DateOfBirth { get; set; } 7: public string InvoiceNumber { get; set; } 8:  9: private readonly string Alpha = "asdf"; 10: private readonly int Beta = 15; 11: private readonly double Delta = 0.077; 12: private readonly double Gamma = 1.0; 13:  14: public Person() 15: { 16: Alpha = "FDSA"; 17: Beta = 2; 18: Delta = 3.0; 19: Gamma = 0.0989; 20: } 21:  22: public Person(int uniqueNumber) : this() 23: { 24: UniqueNumber = uniqueNumber; 25: Beta = 3; 26: } 27:  28: public Person(string name, DateTime dob) : this() 29: { 30: Name = name; 31: DateOfBirth = dob; 32:  33: Alpha = ";LKJ"; 34: Gamma = 0.0898; 35: } 36:  37: public Person(int uniqueNumber, string name, int age, DateTime dob, string invoiceNumber) : this() 38: { 39: UniqueNumber = uniqueNumber; 40: Name = name; 41: Age = age; 42: DateOfBirth = dob; 43: InvoiceNumber = invoiceNumber; 44:  45: Alpha = "QWER"; 46: Beta = 5; 47: Delta = 1.0; 48: Gamma = 0.0; 49: } 50: } In the above example, every constructor over-writes the values for the readonly members. This is perfectly valid. There is a possibility that based on the way the object is instantiated, the readonly member will have a different value. Well, that’s all I have for today and read this as it’s on a related topic.

    Read the article

  • Java collision detection and player movement: tips

    - by Loris
    I have read a short guide for game develompent (java, without external libraries). I'm facing with collision detection and player (and bullets) movements. Now i put the code. Most of it is taken from the guide (should i link this guide?). I'm just trying to expand and complete it. This is the class that take care of updates movements and firing mechanism (and collision detection): public class ArenaController { private Arena arena; /** selected cell for movement */ private float targetX, targetY; /** true if droid is moving */ private boolean moving = false; /** true if droid is shooting to enemy */ private boolean shooting = false; private DroidController droidController; public ArenaController(Arena arena) { this.arena = arena; this.droidController = new DroidController(arena); } public void update(float delta) { Droid droid = arena.getDroid(); //droid movements if (moving) { droidController.moveDroid(delta, targetX, targetY); //check if arrived if (droid.getX() == targetX && droid.getY() == targetY) moving = false; } //firing mechanism if(shooting) { //stop shot if there aren't bullets if(arena.getBullets().isEmpty()) { shooting = false; } for(int i = 0; i < arena.getBullets().size(); i++) { //current bullet Bullet bullet = arena.getBullets().get(i); System.out.println(bullet.getBounds()); //angle calculation double angle = Math.atan2(bullet.getEnemyY() - bullet.getY(), bullet.getEnemyX() - bullet.getX()); //increments x and y bullet.setX((float) (bullet.getX() + (Math.cos(angle) * bullet.getSpeed() * delta))); bullet.setY((float) (bullet.getY() + (Math.sin(angle) * bullet.getSpeed() * delta))); //collision with obstacles for(int j = 0; j < arena.getObstacles().size(); j++) { Obstacle obs = arena.getObstacles().get(j); if(bullet.getBounds().intersects(obs.getBounds())) { System.out.println("Collision detect!"); arena.removeBullet(bullet); } } //collisions with enemies for(int j = 0; j < arena.getEnemies().size(); j++) { Enemy ene = arena.getEnemies().get(j); if(bullet.getBounds().intersects(ene.getBounds())) { System.out.println("Collision detect!"); arena.removeBullet(bullet); } } } } } public boolean onClick(int x, int y) { //click on empty cell if(arena.getGrid()[(int)(y / Arena.TILE)][(int)(x / Arena.TILE)] == null) { //coordinates targetX = x / Arena.TILE; targetY = y / Arena.TILE; //enables movement moving = true; return true; } //click on enemy: fire if(arena.getGrid()[(int)(y / Arena.TILE)][(int)(x / Arena.TILE)] instanceof Enemy) { //coordinates float enemyX = x / Arena.TILE; float enemyY = y / Arena.TILE; //new bullet Bullet bullet = new Bullet(); //start coordinates bullet.setX(arena.getDroid().getX()); bullet.setY(arena.getDroid().getY()); //end coordinates (enemie) bullet.setEnemyX(enemyX); bullet.setEnemyY(enemyY); //adds bullet to arena arena.addBullet(bullet); //enables shooting shooting = true; return true; } return false; } As you can see for collision detection i'm trying to use Rectangle object. Droid example: import java.awt.geom.Rectangle2D; public class Droid { private float x; private float y; private float speed = 20f; private float rotation = 0f; private float damage = 2f; public static final int DIAMETER = 32; private Rectangle2D rectangle; public Droid() { rectangle = new Rectangle2D.Float(x, y, DIAMETER, DIAMETER); } public float getX() { return x; } public void setX(float x) { this.x = x; //rectangle update rectangle.setRect(x, y, DIAMETER, DIAMETER); } public float getY() { return y; } public void setY(float y) { this.y = y; //rectangle update rectangle.setRect(x, y, DIAMETER, DIAMETER); } public float getSpeed() { return speed; } public void setSpeed(float speed) { this.speed = speed; } public float getRotation() { return rotation; } public void setRotation(float rotation) { this.rotation = rotation; } public float getDamage() { return damage; } public void setDamage(float damage) { this.damage = damage; } public Rectangle2D getRectangle() { return rectangle; } } For now, if i start the application and i try to shot to an enemy, is immediately detected a collision and the bullet is removed! Can you help me with this? If the bullet hit an enemy or an obstacle in his way, it must disappear. Ps: i know that the movements of the bullets should be managed in another class. This code is temporary. update I realized what happens, but not why. With those for loops (which checks collisions) the movements of the bullets are instantaneous instead of gradual. In addition to this, if i add the collision detection to the Droid, the method intersects returns true ALWAYS while the droid is moving! public void moveDroid(float delta, float x, float y) { Droid droid = arena.getDroid(); int bearing = 1; if (droid.getX() > x) { bearing = -1; } if (droid.getX() != x) { droid.setX(droid.getX() + bearing * droid.getSpeed() * delta); //obstacles collision detection for(Obstacle obs : arena.getObstacles()) { if(obs.getRectangle().intersects(droid.getRectangle())) { System.out.println("Collision detected"); //ALWAYS HERE } } //controlla se è arrivato if ((droid.getX() < x && bearing == -1) || (droid.getX() > x && bearing == 1)) droid.setX(x); } bearing = 1; if (droid.getY() > y) { bearing = -1; } if (droid.getY() != y) { droid.setY(droid.getY() + bearing * droid.getSpeed() * delta); if ((droid.getY() < y && bearing == -1) || (droid.getY() > y && bearing == 1)) droid.setY(y); } }

    Read the article

  • Are "skip deltas" unique to svn?

    - by echinodermata
    The good folks who created the SVN version control system use a structure they refer to as "skip deltas" to store the revision history of files internally. A revision is stored as a delta against an earlier revision. However, revision N is not necessarily stored as a delta against revision N-1, like this: 0 <- 1 <- 2 <- 3 <- 4 <- 5 <- 6 <- 7 <- 8 <- 9 Instead, revision N is stored as a delta against N-f(N), where f(N) is the greatest power of two that divides N: 0 <- 1 2 <- 3 4 <- 5 6 <- 7 0 <------ 2 4 <------ 6 0 <---------------- 4 0 <------------------------------------ 8 <- 9 (Superficially it looks like a skip list but really it's not that similar - for instance, skip deltas are not interested in supporting insertion in the middle of the list.) You can read more about it here. My question is: Do other systems use skip deltas? Were skip deltas known/used/published before SVN, or did the creators of SVN invent it themselves?

    Read the article

  • Python 3: timestamp to datetime: where does this additional hour come from?

    - by Beau Martínez
    I'm using the following functions: # The epoch used in the datetime API. EPOCH = datetime.datetime.fromtimestamp(0) def timedelta_to_seconds(delta): seconds = (delta.microseconds * 1e6) + delta.seconds + (delta.days * 86400) seconds = abs(seconds) return seconds def datetime_to_timestamp(date, epoch=EPOCH): # Ensure we deal with `datetime`s. date = datetime.datetime.fromordinal(date.toordinal()) epoch = datetime.datetime.fromordinal(epoch.toordinal()) timedelta = date - epoch timestamp = timedelta_to_seconds(timedelta) return timestamp def timestamp_to_datetime(timestamp, epoch=EPOCH): # Ensure we deal with a `datetime`. epoch = datetime.datetime.fromordinal(epoch.toordinal()) epoch_difference = timedelta_to_seconds(epoch - EPOCH) adjusted_timestamp = timestamp - epoch_difference date = datetime.datetime.fromtimestamp(adjusted_timestamp) return date And using them with the passed code: twenty = datetime.datetime(2010, 4, 4) print(twenty) print(datetime_to_timestamp(twenty)) print(timestamp_to_datetime(datetime_to_timestamp(twenty))) And getting the following results: 2010-04-04 00:00:00 1270339200.0 2010-04-04 01:00:00 For some reason, I'm getting an additional hour added in the last call, despite my code having, as far as I can see, no flaws. Where is this additional hour coming from?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >