Search Results

Search found 711 results on 29 pages for 'pos'.

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

  • Queries regarding Geometry Shaders

    - by maverick9888
    I am dealing with geometry shaders using GL_ARB_geometry_shader4 extension. My code goes like : GLfloat vertices[] = { 0.5,0.25,1.0, 0.5,0.75,1.0, -0.5,0.75,1.0, -0.5,0.25,1.0, 0.6,0.35,1.0, 0.6,0.85,1.0, -0.6,0.85,1.0, -0.6,0.35,1.0 }; glProgramParameteriEXT(psId, GL_GEOMETRY_INPUT_TYPE_EXT, GL_TRIANGLES); glProgramParameteriEXT(psId, GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_TRIANGLE_STRIP); glLinkProgram(psId); glBindAttribLocation(psId,0,"Position"); glEnableVertexAttribArray (0); glVertexAttribPointer(0, 3, GL_FLOAT, 0, 0, vertices); glDrawArrays(GL_TRIANGLE_STRIP,0,4); My vertex shader is : #version 150 in vec3 Position; void main() { gl_Position = vec4(Position,1.0); } Geometry shader is : #version 150 #extension GL_EXT_geometry_shader4 : enable in vec4 pos[3]; void main() { int i; vec4 vertex; gl_Position = pos[0]; EmitVertex(); gl_Position = pos[1]; EmitVertex(); gl_Position = pos[2]; EmitVertex(); gl_Position = pos[0] + vec4(0.3,0.0,0.0,0.0); EmitVertex(); EndPrimitive(); } Nothing is rendered with this code. What exactly should be the mode in glDrawArrays() ? How does the GL_GEOMETRY_OUTPUT_TYPE_EXT parameter will affect glDrawArrays() ? What I expect is 3 vertices will be passed on to Geometry Shader and using those we construct a primitive of size 4 (assuming GL_TRIANGLE_STRIP requires 4 vertices). Can somebody please throw some light on this ?

    Read the article

  • Introducing Oracle Retail Mobile Point-of-Service

    - by user801960
    Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:"Times New Roman"; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} Oracle recently announced the introduction of Oracle Retail Mobile Point-of-Service, a mobile extension to the Oracle Retail Point-of-Service (POS) used by many retailers internationally. Oracle Retail Mobile POS offers wide ranging cost and efficiency benefits by allowing staff resource to be used more effectively whilst also reducing spend associated with fixed POS solutions. For retailers utilising Oracle Retail Stores Solutions, additional benefits can be realised. Oracle Retail Mobile POS works with these solutions to allow store personnel to check in-store inventory, access product information and specifications, and perform tasks such as the printing or emailing of receipts and the activation of gift cards.  As Oracle Retail Mobile POS is an extension of Oracle Retail Point-of-Service, retailers can benefit from seamless integration with existing systems, simple upgrade procedures and seamless delivery across the business. However, the solution’s scalable and flexible architecture also supports multiple mobile operators and systems, so retailers are not locked into particular vendors. As well as being popular with retailers, Mobile POS has also proved to be well liked by consumers as it facilitates improved customer service levels. Retail staff are able to spend more time with consumers on the shop floor, access requested inventory information, and perform tasks that would traditionally have needed to be completed at a fixed cash register. Additional information can be accessed on Oracle Retail Point-of-Service or read the press announcement Oracle Introduces Mobile Point-of-Service for Retailers. Normal 0 false false false EN-US X-NONE X-NONE

    Read the article

  • Bullet Physics - Casting a ray straight down from a rigid body (first person camera)

    - by Hydrocity
    I've implemented a first person camera using Bullet--it's a rigid body with a capsule shape. I've only been using Bullet for a few days and physics engines are new to me. I use btRigidBody::setLinearVelocity() to move it and it collides perfectly with the world. The only problem is the Y-value moves freely, which I temporarily solved by setting the Y-value of the translation vector to zero before the body is moved. This works for all cases except when falling from a height. When the body drops off a tall object, you can still glide around since the translate vector's Y-value is being set to zero, until you stop moving and fall to the ground (the velocity is only set when moving). So to solve this I would like to try casting a ray down from the body to determine the Y-value of the world, and checking the difference between that value and the Y-value of the camera body, and disable or slow down movement if the difference is large enough. I'm a bit stuck on simply casting a ray and determining the Y-value of the world where it struck. I've implemented this callback: struct AllRayResultCallback : public btCollisionWorld::RayResultCallback{ AllRayResultCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld) : m_rayFromWorld(rayFromWorld), m_rayToWorld(rayToWorld), m_closestHitFraction(1.0){} btVector3 m_rayFromWorld; btVector3 m_rayToWorld; btVector3 m_hitNormalWorld; btVector3 m_hitPointWorld; float m_closestHitFraction; virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace) { if(rayResult.m_hitFraction < m_closestHitFraction) m_closestHitFraction = rayResult.m_hitFraction; m_collisionObject = rayResult.m_collisionObject; if(normalInWorldSpace){ m_hitNormalWorld = rayResult.m_hitNormalLocal; } else{ m_hitNormalWorld = m_collisionObject->getWorldTransform().getBasis() * rayResult.m_hitNormalLocal; } m_hitPointWorld.setInterpolate3(m_rayFromWorld, m_rayToWorld, m_closestHitFraction); return 1.0f; } }; And in the movement function, I have this code: btVector3 from(pos.x, pos.y + 1000, pos.z); // pos is the camera's rigid body position btVector3 to(pos.x, 0, pos.z); // not sure if 0 is correct for Y AllRayResultCallback callback(from, to); Base::getSingletonPtr()->m_btWorld->rayTest(from, to, callback); So I have the callback.m_hitPointWorld vector, which seems to just show the position of the camera each frame. I've searched Google for examples of casting rays, as well as the Bullet documentation, and it's been hard to just find an example. An example is really all I need. Or perhaps there is some method in Bullet to keep the rigid body on the ground? I'm using Ogre3D as a rendering engine, and casting a ray down is quite straightforward with that, however I want to keep all the ray casting within Bullet for simplicity. Could anyone point me in the right direction? Thanks.

    Read the article

  • Pygame: Save a list of objects/classes/surfaces

    - by Sam Tubb
    I am working on a game, in which you can create mazes. You place blocks on a 16x16 grid, while choosing from a variety of block to make the level with. Whenever you create a block, it adds this class: class Block(object): def __init__(self,x,y,spr): self.x=x self.y=y self.sprite=spr self.rect=self.sprite.get_rect(x=self.x,y=self.y) to a list called instances. I tried shelving it to a .bin file, but it returns some error dealing with surfaces. How can I go about saving and loading levels? Any help is appreciated! :) Here is the whole code for reference: import pygame from pygame.locals import * #initstuff pygame.init() screen=pygame.display.set_mode((640,480)) pygame.display.set_caption('PiMaze') instances=[] #loadsprites menuspr=pygame.image.load('images/menu.png').convert() b1spr=pygame.image.load('images/b1.png').convert() b2spr=pygame.image.load('images/b2.png').convert() currentbspr=b1spr curspr=pygame.image.load('images/curs.png').convert() curspr.set_colorkey((0,255,0)) #menu menuspr.set_alpha(185) menurect=menuspr.get_rect(x=-260,y=4) class MenuItem(object): def __init__(self,pos,spr): self.x=pos[0] self.y=pos[1] self.sprite=spr self.pos=(self.x,self.y) self.rect=self.sprite.get_rect(x=self.x,y=self.y) class Block(object): def __init__(self,x,y,spr): self.x=x self.y=y self.sprite=spr self.rect=self.sprite.get_rect(x=self.x,y=self.y) while True: #menu items b1menu=b1spr.get_rect(x=menurect.left+32,y=48) b2menu=b2spr.get_rect(x=menurect.left+64,y=48) menuitems=[MenuItem(b1menu,b1spr),MenuItem(b2menu,b2spr)] screen.fill((20,30,85)) mse=pygame.mouse.get_pos() key=pygame.key.get_pressed() placepos=((mse[0]/16)*16,(mse[1]/16)*16) if key[K_q]: if mse[0]<260: if menurect.right<255: menurect.right+=1 else: if menurect.left>-260: menurect.left-=1 else: if menurect.left>-260: menurect.left-=1 for e in pygame.event.get(): if e.type==QUIT: exit() if menurect.right<100: if e.type==MOUSEBUTTONUP: if e.button==1: to_remove = [i for i in instances if i.rect.collidepoint(placepos)] for i in to_remove: instances.remove(i) if not to_remove: instances.append(Block(placepos[0],placepos[1],currentbspr)) for i in instances: screen.blit(i.sprite,i.rect) if not key[K_q]: screen.blit(curspr,placepos) screen.blit(menuspr,menurect) for item in menuitems: screen.blit(item.sprite,item.pos) if item.rect.collidepoint(mse): if pygame.mouse.get_pressed()==(1,0,0): currentbspr=item.sprite pygame.draw.rect(screen, ((255,0,0)), item, 1) pygame.display.flip()

    Read the article

  • Check if an object is facing another based on angles

    - by Isaiah
    I already have something that calculates the bearing angle to get one object to face another. You give it the positions and it returns the angle to get one to face the other. Now I need to figure out how tell if on object is facing toward another object within a specified field and I can't find any information about how to do this. The objects are obj1 and obj2. Their angles are at obj1.angle and obj2.angle. Their vectors are at obj1.pos and obj2.pos. It's in the format [x,y]. The angle to have one face directly at another is found with direction(obj1.pos,obj2.pos). I want to set the function up like this: isfacing(obj1,obj2,area){...} and return true/false depending if it's in the specified field area to the angle to directly see it. I've got a base like this: var isfacing = function (obj1,obj2,area){ var toface = direction(obj1.pos,obj2.pos); if(toface+area >= obj1.angle && ob1.angle >= toface-area){ return true; } return false; } But my problem is that the angles are in 360 degrees, never above 360 and never below 0. How can I account for that in this? If the first object's angle is say at 0 and say I subtract a field area of 20 or so. It'll check if it's less than -20! If I fix the -20 it becomes 340 but x < 340 isn't what I want, I'd have to x 340 in that case. Is there someone out there with more sleep than I that can help a new dev pulling an all-nighter just to get enemies to know if they're attacking in the right direction? I hope I'm making this harder than it seems. I'd just make them always face the main char if the producer didn't want attacks from behind to work while blocking. In which case I'll need the function above anyways. I've tried to give as much info as I can think would help. Also this is in 2d.

    Read the article

  • Creating smooth lighting transitions using tiles in HTML5/JavaScript game

    - by user12098
    I am trying to implement a lighting effect in an HTML5/JavaScript game using tile replacement. What I have now is kind of working, but the transitions do not look smooth/natural enough as the light source moves around. Here's where I am now: Right now I have a background map that has a light/shadow spectrum PNG tilesheet applied to it - going from darkest tile to completely transparent. By default the darkest tile is drawn across the entire level on launch, covering all other layers etc. I am using my predetermined tile sizes (40 x 40px) to calculate the position of each tile and store its x and y coordinates in an array. I am then spawning a transparent 40 x 40px "grid block" entity at each position in the array The engine I'm using (ImpactJS) then allows me to calculate the distance from my light source entity to every instance of this grid block entity. I can then replace the tile underneath each of those grid block tiles with a tile of the appropriate transparency. Currently I'm doing the calculation like this in each instance of the grid block entity that is spawned on the map: var dist = this.distanceTo( ig.game.player ); var percentage = 100 * dist / 960; if (percentage < 2) { // Spawns tile 64 of the shadow spectrum tilesheet at the specified position ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 64 ); } else if (percentage < 4) { ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 63 ); } else if (percentage < 6) { ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 62 ); } // etc... (sorry about the weird spacing, I still haven't gotten the hang of pasting code in here properly) The problem is that like I said, this type of calculation does not make the light source look very natural. Tile switching looks too sharp whereas ideally they would fade in and out smoothly using the spectrum tilesheet (I copied the tilesheet from another game that manages to do this, so I know it's not a problem with the tile shades. I'm just not sure how the other game is doing it). I'm thinking that perhaps my method of using percentages to switch out tiles could be replaced with a better/more dynamic proximity forumla of some sort that would allow for smoother transitions? Might anyone have any ideas for what I can do to improve the visuals here, or a better way of calculating proximity with the information I'm collecting about each tile? (PS: I'm reposting this from Stack Overflow at someone's suggestion, sorry about the duplicate!)

    Read the article

  • Weird order when painting triangle outlines using GL_LINE_STRIP

    - by RayDeeA
    I'm developing an app for iOS-Plaftorms using OpenGL. Currently I'm having a weird issue when painting a plane (terrain) which consists of multiple subplanes, where each subplane consists of 2 triangles forming a rect. I'm painting this terrain as a wireframe by using a call to glDrawElements and provide the parameters GL_Line_Strip and the precalculated indices. The problem is that the triangles get painted in the wrong order or are rather vertically mirrored. They do not get painted in the order how I specified the indices, which is confusing. This is the simplified code to generate the vertices: for(NSInteger y = - gridSegmentsY / 2; y < gridSegmentsY / 2; y ++) { for(NSInteger x = - gridSegmentsX / 2; x < gridSegmentsX / 2; x ++) { vertices[pos++] = x * 5; vertices[pos++] = y * 5; vertices[pos++] = 0; } } This is how I generate the indices including degenerated ones (To use as IBO). pos = 0; for(int y = 0; y < gridSegmentsY - 1; y ++) { if (y > 0) { // Degenerate begin: repeat first vertex indices[pos++] = (unsigned short)(y * gridSegmentsY); } for(int x = 0; x < gridSegmentsX; x++) { // One part of the strip indices[pos++] = (unsigned short)((y * gridSegmentsY) + x); indices[pos++] = (unsigned short)(((y + 1) * gridSegmentsY) + x); } if (y < gridSegmentsY - 2) { // Degenerate end: repeat last vertex indices[pos++] = (unsigned short)(((y + 1) * gridSegmentsY) + (gridSegmentsX - 1)); } } So in this part... indices[pos++] = (unsigned short)((y * gridSegmentsY) + x); indices[pos++] = (unsigned short)(((y + 1) * gridSegmentsY) + x); ...I'm setting the first index in the indices array to point to the current (x,y) and the next index to (x,y+1). I'm doin' this for all x's in the current strip, then I'm handling degenerated triangles and repeat this procedure for the next strip (y+1). This method is taken from http://www.learnopengles.com/android-lesson-eight-an-introduction-to-index-buffer-objects-ibos/ So I expect the resulting mesh to get painted like: a----b----c | /| /| | / | / | | / | / | |/ |/ | d----e----f | /| /| | / | / | | / | / | |/ |/ | g----h----i by painting it as described using: glDrawElements(GL_LINE_STRIP, indexCount, GL_UNSIGNED_SHORT, 0); ...since I expect GL_Line_Strip to paint first a line from (a-d), then from (d-b), then (b, e)... and so on (as specified in the indices calculation) But what actually gets painted is: *----*----* |\ |\ | | \ | \ | | \ | \ | | \| \| *----*----* |\ |\ | | \ | \ | | \ | \ | | \| \| *----*----* So the triangles are somehow painted in the wrong order and I need to know why? ;). Does somebody know? Does the problem lie in using GL_Line_Strip or is there a bug in my code? My eye is at (0.0f, 0.0f, 20.0f) and looks at (0,0,0). The mesh is painted along the x-axis & y-axis from left to right with z = 0, so the mesh should not be flipped or anything.

    Read the article

  • Can you suggest some UI related flex 3 interview questions for a senior pos?

    - by mohan talluri
    Our Company is looking for a sr.flex developer. As part of interview process customized UI understanding and implementation is also included. I am Usability&design Lead for the same product team have some understanding of flex 3 but am not sure if pure UI/usability questions can be answered by flex developer. So can you suggest some UI related questions to see if he/she has competency to refer a prototype(html/mockup's) and build the same UI in flex.

    Read the article

  • JSON element detection

    - by user3614570
    I’ve created a string… {"atts": [{"name": "wedw"}, {"type": "---"}]} I pile a bunch of these together in an array based on user input and attach them to another string to complete a JSON object that tests out as valid. So I end up with a global array called fields with a bunch of these little snippets. So how do I change the name "weds" with a new name? I’ve tried... function changefieldname(pos){ var obj = JSON.parse(jsonstring); var oldname = obj.tracelog.fields[pos].atts[0]["name"]; var newname = document.getElementById("newlogfieldname"+pos).value; fields[pos].replace(oldname, newname); //writejson(); } And a bunch of variations. I know everything is checking out correct interms of the variables pos, oldname, and newname. I also know that fields[pos] returns the string in the array I want to correct but it’s not happy. I also tried converting fields[pos] to a string, but the replace function doesn't work on it. I’m sure there is a good reason.

    Read the article

  • flash core engine by Dinesh [closed]

    - by hdinesh
    This post was a dump of the following code (without the highlights). No question, just a dump. Please update this q. with a real question to have it reopened. You (the asker) risk to be flagged as spammer (if not already) and a bad reputation. This is a q/a site, not a site to promote your own code libraries. package facers { import flash.display.*; import flash.events.*; import flash.geom.ColorTransform; import flash.utils.Dictionary; import org.papervision3d.cameras.*; import org.papervision3d.scenes.*; import org.papervision3d.objects.*; import org.papervision3d.objects.special.*; import org.papervision3d.objects.primitives.*; import org.papervision3d.materials.*; import org.papervision3d.events.FileLoadEvent; import org.papervision3d.materials.special.*; import org.papervision3d.materials.shaders.*; import org.papervision3d.materials.utils.*; import org.papervision3d.lights.*; import org.papervision3d.render.*; import org.papervision3d.view.*; import org.papervision3d.events.InteractiveScene3DEvent; import org.papervision3d.events.*; import org.papervision3d.core.utils.*; import org.papervision3d.core.geom.renderables.Vertex3D; import caurina.transitions.*; public class Main extends Sprite { public var viewport :BasicView; public var displayObject :DisplayObject3D; private var light :PointLight3D; private var shadowPlane :Plane; private var dataArray :Array; private var material :BitmapFileMaterial; private var planeByContainer :Dictionary = new Dictionary(); private var paperSize :Number = 0.5; private var cloudSize :Number = 1500; private var rotSize :Number = 360; private var maxAlbums :Number = 50; private var num :Number = 0; public function Main():void { trace("START APPLICATION"); viewport = new BasicView(1024, 690, true, true, CameraType.FREE); viewport.camera.zoom = 50; viewport.camera.extra = { goPosition: new DisplayObject3D(),goTarget: new DisplayObject3D() }; addChild(viewport); displayObject = new DisplayObject3D(); viewport.scene.addChild(displayObject); createAlbum(); addEventListener(Event.ENTER_FRAME, onRenderEvent); } private function createAlbum() { dataArray = new Array("images/thums/pic1.jpg", "images/thums/pic2.jpg", "images/thums/pic3.jpg", "images/thums/pic4.jpg", "images/thums/pic5.jpg", "images/thums/pic6.jpg", "images/thums/pic7.jpg", "images/thums/pic8.jpg", "images/thums/pic9.jpg", "images/thums/pic10.jpg", "images/thums/pic1.jpg", "images/thums/pic2.jpg", "images/thums/pic3.jpg", "images/thums/pic4.jpg", "images/thums/pic5.jpg", "images/thums/pic6.jpg", "images/thums/pic7.jpg", "images/thums/pic8.jpg", "images/thums/pic9.jpg", "images/thums/pic10.jpg"); for (var i:int = 0; i < dataArray.length; i++) { material = new BitmapFileMaterial(dataArray[i]); material.doubleSided = true; material.addEventListener(FileLoadEvent.LOAD_COMPLETE, loadMaterial); } } public function loadMaterial(event:Event) { var plane:Plane = new Plane(material, 300, 180); displayObject.addChild(plane); var _x:int = Math.random() * cloudSize - cloudSize/2; var _y:int = Math.random() * cloudSize - cloudSize/2; var _z:int = Math.random() * cloudSize - cloudSize/2; var _rotationX:int = Math.random() * rotSize; var _rotationY:int = Math.random() * rotSize; var _rotationZ:int = Math.random() * rotSize; Tweener.addTween(plane, { x:_x, y:_y, z:_z, rotationX:_rotationX, rotationY:_rotationY, rotationZ:_rotationZ, time:5, transition:"easeIn" } ); } protected function onRenderEvent(event:Event):void { var rotY: Number = (mouseY-(stage.stageHeight/2))/(900/2)*(1200); var rotX: Number = (mouseX-(stage.stageWidth/2))/(600/2)*(-1200); displayObject.rotationY = viewport.camera.x + (rotX - viewport.camera.x) / 50; displayObject.rotationX = viewport.camera.y + (rotY - viewport.camera.y) / 30; viewport.singleRender(); } } } package designLab.events { import flash.display.BlendMode; import flash.display.Sprite; import flash.events.Event; import flash.filters.BlurFilter; // Import designLab import designLab.layer.IntroLayer; import designLab.shadow.ShadowCaster; import designLab.utils.LayerConstant; // Import Papervision3D import org.papervision3d.cameras.*; import org.papervision3d.scenes.*; import org.papervision3d.objects.*; import org.papervision3d.objects.special.*; import org.papervision3d.objects.primitives.*; import org.papervision3d.materials.*; import org.papervision3d.materials.special.*; import org.papervision3d.materials.shaders.*; import org.papervision3d.materials.utils.*; import org.papervision3d.lights.*; import org.papervision3d.render.*; import org.papervision3d.view.*; import org.papervision3d.events.InteractiveScene3DEvent; import org.papervision3d.events.*; import org.papervision3d.core.utils.*; import org.papervision3d.core.geom.renderables.Vertex3D; public class CoreEnging extends Sprite { public var viewport :BasicView; // Create BasicView public var displayObject :DisplayObject3D; // Create DisplayObject public var shadowCaster :ShadowCaster; // Create ShadowCaster private var light :PointLight3D; // Create PointLight private var shadowPlane :Plane; // Create Plane private var layer :LayerConstant; // Create constant resource layer private static var instance :CoreEnging; // Create CoreEnging class static instance // CoreEnging class static instance mathod function public static function getinstance() { if (instance != null) return instance; else { instance = new CoreEnging(); return instance; } } // CoreEnging constrictor public function CoreEnging () { trace("INFO: Design Lab Application : Core Enging v0.1"); layer = new LayerConstant(); viewport = new BasicView(900, 600, true, true, CameraType.FREE); // pass the width, height, scaleToStage, interactive, cameraType to BasicView viewport.camera.zoom = 100; // Define the zoom level of camera addChild(viewport); createFloor(); // Create the floor displayObject = new DisplayObject3D(); // Create new instance of DisplayObject viewport.scene.addChild(displayObject); // Add the DisplayObject to the BasicView light = new PointLight3D(); // Create new instance of PointLight light.z = -50; // Position the Z of create instance light.x = 0; //Position the X of create instance light.rotationZ = 45; //Position the rotation angel of the Z of create instance light.y = 500; //Position the Y of create instance shadowCaster = new ShadowCaster("shadow", 0x000000, BlendMode.MULTIPLY, .1, [new BlurFilter(20, 20, 1)]); // pass shadowcaster name, color, blend mode, alpha and filters shadowCaster.setType(ShadowCaster.SPOTLIGHT); // Define the shadow type addEventListener(Event.ENTER_FRAME, onRenderEvent); // Add frame render event } // Start create floor public function createFloor() { var spr:Sprite = new Sprite(); // Create Sprite spr.graphics.beginFill(0xFFFFFF); // Define the fill color for sprite spr.graphics.drawRect(0, 0, 600, 600); // Define the X, Y, width, height of the sprite var sprMaterial:MovieMaterial = new MovieMaterial(spr, true, true, true); //Create a texture from an existing sprite instance shadowPlane = new Plane(sprMaterial, 2000, 2000, 1, 1); // create new instance of the Plane and pass the texture material, width, height, segmentsW and segmentsH shadowPlane.rotationX = 80; //Position the rotation angel of the X of Plane shadowPlane.y = -200; //Position the Y of Plane viewport.scene.addChild(shadowPlane); // Add the Plane to the BasicView } // switch method function of the page layer control public function addLayer(type:String) { switch (type) { case layer.INTRO: var intro:IntroLayer = new IntroLayer(); break; } } // Create get mathod function for DisplayObject public function getDisplayObject():DisplayObject3D { return displayObject; } // Create get mathod function for BasicView public function getViewport():BasicView { return viewport; } // Rendering function protected function onRenderEvent(event:Event):void { var rotY: Number = (mouseY-(stage.stageHeight/2))/(900/2)*(1200); var rotX: Number = (mouseX-(stage.stageWidth/2))/(600/2)*(-1200); displayObject.rotationY = viewport.camera.x + (rotX - viewport.camera.x) / 50; displayObject.rotationX = viewport.camera.y + (rotY - viewport.camera.y) / 30; // Remove the shadow shadowCaster.invalidate(); // create new shadow on DisplayObject move shadowCaster.castModel(displayObject, light, shadowPlane); viewport.singleRender(); } } } package designLab.layer { import flash.display.Sprite; import flash.events.Event; // Import designLab import designLab.materials.iBusinessCard; import designLab.events.CoreEnging; // Import Papervision3D import org.papervision3d.objects.primitives.Cube; import org.papervision3d.materials.ColorMaterial; import org.papervision3d.materials.MovieMaterial; public class IntroLayer { // IntroLayer constrictor public function IntroLayer() { trace("INFO: Load Intro layer"); var indexDP:DP_index = new DP_index(); //Create the library MovieClip var blackMaterial:MovieMaterial = new MovieMaterial(indexDP, true); //Create a texture from an existing library MovieClip instance blackMaterial.smooth = true; blackMaterial.doubleSided = false; var mycolor:ColorMaterial = new ColorMaterial(0x000000); //Create solid color material var mycard:iBusinessCard = new iBusinessCard(blackMaterial, blackMaterial, mycolor, 372, 10, 207); // Create custom 3D cube object to pass the Front, Back, All, CubeWidth, CubeDepth and CubeHeight CoreEnging.getinstance().getDisplayObject().addChild(mycard.create3DCube()); // Add the custom 3D cube to the DisplayObject } } } package designLab.materials { import flash.display.*; import flash.events.*; // Import Papervision3D import org.papervision3d.materials.*; import org.papervision3d.materials.utils.MaterialsList; import org.papervision3d.objects.primitives.Cube; public class iBusinessCard extends Sprite { private var materialsList :MaterialsList; private var cube :Cube; private var Front :MovieMaterial = new MovieMaterial(); private var Back :MovieMaterial = new MovieMaterial(); private var All :ColorMaterial = new ColorMaterial(); private var CubeWidth :Number; private var CubeDepth :Number; private var CubeHeight :Number; public function iBusinessCard(Front:MovieMaterial, Back:MovieMaterial, All:ColorMaterial, CubeWidth:Number, CubeDepth:Number, CubeHeight:Number) { setFront(Front); setBack(Back); setAll(All); setCubeWidth(CubeWidth); setCubeDepth(CubeDepth); setCubeHeight(CubeHeight); } public function create3DCube():Cube { materialsList = new MaterialsList(); materialsList.addMaterial(Front, "front"); materialsList.addMaterial(Back, "back"); materialsList.addMaterial(All, "left"); materialsList.addMaterial(All, "right"); materialsList.addMaterial(All, "top"); materialsList.addMaterial(All, "bottom"); cube = new Cube(materialsList, CubeWidth, CubeDepth, CubeHeight); cube.x = 0; cube.y = 0; cube.z = 0; cube.rotationY = 180; return cube; } public function setFront(Front:MovieMaterial) { this.Front = Front; } public function getFront():MovieMaterial { return Front; } public function setBack(Back:MovieMaterial) { this.Back = Back; } public function getBack():MovieMaterial { return Back; } public function setAll(All:ColorMaterial) { this.All = All; } public function getAll():ColorMaterial { return All; } public function setCubeWidth(CubeWidth:Number) { this.CubeWidth = CubeWidth; } public function getCubeWidth():Number { return CubeWidth; } public function setCubeDepth(CubeDepth:Number) { this.CubeDepth = CubeDepth; } public function getCubeDepth():Number { return CubeDepth; } public function setCubeHeight(CubeHeight:Number) { this.CubeHeight = CubeHeight; } public function getCubeHeight():Number { return CubeHeight; } } } package designLab.shadow { import flash.display.Sprite; import flash.filters.BlurFilter; import flash.geom.Point; import flash.geom.Rectangle; import flash.utils.Dictionary; import org.papervision3d.core.geom.TriangleMesh3D; import org.papervision3d.core.geom.renderables.Triangle3D; import org.papervision3d.core.geom.renderables.Vertex3D; import org.papervision3d.core.math.BoundingSphere; import org.papervision3d.core.math.Matrix3D; import org.papervision3d.core.math.Number3D; import org.papervision3d.core.math.Plane3D; import org.papervision3d.lights.PointLight3D; import org.papervision3d.materials.MovieMaterial; import org.papervision3d.objects.DisplayObject3D; import org.papervision3d.objects.primitives.Plane; public class ShadowCaster { private var vertexRefs:Dictionary; private var numberRefs:Dictionary; private var lightRay:Number3D = new Number3D() private var p3d:Plane3D = new Plane3D(); public var color:uint = 0; public var alpha:Number = 0; public var blend:String = ""; public var filters:Array; public var uid:String; private var _type:String = "point"; private var dir:Number3D; private var planeBounds:Dictionary; private var targetBounds:Dictionary; private var models:Dictionary; public static var DIRECTIONAL:String = "dir"; public static var SPOTLIGHT:String = "spot"; public function ShadowCaster(uid:String, color:uint = 0, blend:String = "multiply", alpha:Number = 1, filters:Array=null) { this.uid = uid; this.color = color; this.alpha = alpha; this.blend = blend; this.filters = filters ? filters : [new BlurFilter()]; numberRefs = new Dictionary(true); targetBounds = new Dictionary(true); planeBounds = new Dictionary(true); models = new Dictionary(true); } public function castModel(model:DisplayObject3D, light:PointLight3D, plane:Plane, faces:Boolean = true, cull:Boolean = false):void{ var ar:Array; if(models[model]) { ar = models[model]; }else{ ar = new Array(); getChildMesh(model, ar); models[model] = ar; } var reset:Boolean = true; for each(var t:TriangleMesh3D in ar){ if(faces) castFaces(light, t, plane, cull, reset); else castBoundingSphere(light, t, plane, 0.75, reset); reset = false; } } private function getChildMesh(do3d:DisplayObject3D, ar):void{ if(do3d is TriangleMesh3D) ar.push(do3d); for each(var d:DisplayObject3D in do3d.children) getChildMesh(d, ar); } public function setType(type:String="point"):void{ _type = type; } public function getType():String{ return _type; } public function castBoundingSphere(light:PointLight3D, target:TriangleMesh3D, plane:Plane, scaleRadius:Number=0.8, clear:Boolean = true):void{ var planeVertices:Array = plane.geometry.vertices; //convert to target space? var world:Matrix3D = plane.world; var inv:Matrix3D = Matrix3D.inverse(plane.transform); var lp:Number3D = new Number3D(light.x, light.y, light.z); Matrix3D.multiplyVector(inv, lp); p3d.setNormalAndPoint(plane.geometry.faces[0].faceNormal, new Number3D()); var b:BoundingSphere = target.geometry.boundingSphere; var bounds:Object = planeBounds[plane]; if(!bounds){ bounds = plane.boundingBox(); planeBounds[plane] = bounds; } var tbounds:Object = targetBounds[target]; if(!tbounds){ tbounds = target.boundingBox(); targetBounds[target] = tbounds; } var planeMovie:Sprite = Sprite(MovieMaterial(plane.material).movie); var movieSize:Point = new Point(planeMovie.width, planeMovie.height); var castClip:Sprite = getCastClip(plane); castClip.blendMode = this.blend; castClip.filters = this.filters; castClip.alpha = this.alpha; if(clear) castClip.graphics.clear(); vertexRefs = new Dictionary(true); var tlp:Number3D = new Number3D(light.x, light.y, light.z); Matrix3D.multiplyVector(Matrix3D.inverse(target.world), tlp); var center:Number3D = new Number3D(tbounds.min.x+tbounds.size.x*0.5, tbounds.min.y+tbounds.size.y*0.5, tbounds.min.z+tbounds.size.z*0.5); var dif:Number3D = Number3D.sub(lp, center); dif.normalize(); var other:Number3D = new Number3D(); other.x = -dif.y; other.y = dif.x; other.z = 0; other.normalize(); var cross:Number3D = Number3D.cross(new Number3D(plane.transform.n12, plane.transform.n22, plane.transform.n32), p3d.normal); cross.normalize(); //cross = new Number3D(-dif.y, dif.x, 0); //cross.normalize(); cross.multiplyEq(b.radius*scaleRadius); if(_type == DIRECTIONAL){ var oPos:Number3D = new Number3D(target.x, target.y, target.z); Matrix3D.multiplyVector(target.world, oPos); Matrix3D.multiplyVector(inv, oPos); dir = new Number3D(oPos.x-lp.x, oPos.y-lp.y, oPos.z-lp.z); } //numberRefs = new Dictionary(true); var pos:Number3D; var c2d:Point; var r2d:Point; //_type = SPOTLIGHT; pos = projectVertex(new Vertex3D(center.x, center.y, center.z), lp, inv, target.world); c2d = get2dPoint(pos, bounds.min, bounds.size, movieSize); pos = projectVertex(new Vertex3D(center.x+cross.x, center.y+cross.y, center.z+cross.z), lp, inv, target.world); r2d = get2dPoint(pos, bounds.min, bounds.size, movieSize); var dx:Number = r2d.x-c2d.x; var dy:Number = r2d.y-c2d.y; var rad:Number = Math.sqrt(dx*dx+dy*dy); castClip.graphics.beginFill(color); castClip.graphics.moveTo(c2d.x, c2d.y); castClip.graphics.drawCircle(c2d.x, c2d.y, rad); castClip.graphics.endFill(); } public function getCastClip(plane:Plane):Sprite{ var planeMovie:Sprite = Sprite(MovieMaterial(plane.material).movie); var movieSize:Point = new Point(planeMovie.width, planeMovie.height); var castClip:Sprite;// = new Sprite(); if(planeMovie.getChildByName("castClip"+uid)) return Sprite(planeMovie.getChildByName("castClip"+uid)); else{ castClip = new Sprite(); castClip.name = "castClip"+uid; castClip.scrollRect = new Rectangle(0, 0, movieSize.x, movieSize.y); //castClip.alpha = 0.4; planeMovie.addChild(castClip); return castClip; } } public function castFaces(light:PointLight3D, target:TriangleMesh3D, plane:Plane, cull:Boolean=false, clear:Boolean = true):void{ var planeVertices:Array = plane.geometry.vertices; //convert to target space? var world:Matrix3D = plane.world; var inv:Matrix3D = Matrix3D.inverse(plane.transform); var lp:Number3D = new Number3D(light.x, light.y, light.z); Matrix3D.multiplyVector(inv, lp); var tlp:Number3D; if(cull){ tlp = new Number3D(light.x, light.y, light.z); Matrix3D.multiplyVector(Matrix3D.inverse(target.world), tlp); } //Matrix3D.multiplyVector(Matrix3D.inverse(target.transform), tlp); //p3d.setThreePoints(planeVertices[0].getPosition(), planeVertices[1].getPosition(), planeVertices[2].getPosition()); p3d.setNormalAndPoint(plane.geometry.faces[0].faceNormal, new Number3D()); if(_type == DIRECTIONAL){ var oPos:Number3D = new Number3D(target.x, target.y, target.z); Matrix3D.multiplyVector(target.world, oPos); Matrix3D.multiplyVector(inv, oPos); dir = new Number3D(oPos.x-lp.x, oPos.y-lp.y, oPos.z-lp.z); } var bounds:Object = planeBounds[plane]; if(!bounds){ bounds = plane.boundingBox(); planeBounds[plane] = bounds; } var castClip:Sprite = getCastClip(plane); castClip.blendMode = this.blend; castClip.filters = this.filters; castClip.alpha = this.alpha; var planeMovie:Sprite = Sprite(MovieMaterial(plane.material).movie); var movieSize:Point = new Point(planeMovie.width, planeMovie.height); if(clear) castClip.graphics.clear(); vertexRefs = new Dictionary(true); //numberRefs = new Dictionary(true); var pos:Number3D; var p2d:Point; var s2d:Point; var hitVert:Number3D = new Number3D(); for each(var t:Triangle3D in target.geometry.faces){ if( cull){ hitVert.x = t.v0.x; hitVert.y = t.v0.y; hitVert.z = t.v0.z; if(Number3D.dot(t.faceNormal, Number3D.sub(tlp, hitVert)) <= 0) continue; } castClip.graphics.beginFill(color); pos = projectVertex(t.v0, lp, inv, target.world); s2d = get2dPoint(pos, bounds.min, bounds.size, movieSize); castClip.graphics.moveTo(s2d.x, s2d.y); pos = projectVertex(t.v1, lp, inv, target.world); p2d = get2dPoint(pos, bounds.min, bounds.size, movieSize); castClip.graphics.lineTo(p2d.x, p2d.y); pos = projectVertex(t.v2, lp, inv, target.world); p2d = get2dPoint(pos, bounds.min, bounds.size, movieSize); castClip.graphics.lineTo(p2d.x, p2d.y); castClip.graphics.lineTo(s2d.x, s2d.y); castClip.graphics.endFill(); } } public function invalidate():void{ invalidateModels(); invalidatePlanes(); } public function invalidatePlanes():void{ planeBounds = new Dictionary(true); } public function invalidateTargets():void{ numberRefs = new Dictionary(true); targetBounds = new Dictionary(true); } public function invalidateModels():void{ models = new Dictionary(true); invalidateTargets(); } private function get2dPoint(pos3D:Number3D, min3D:Number3D, size3D:Number3D, movieSize:Point):Point{ return new Point((pos3D.x-min3D.x)/size3D.x*movieSize.x, ((-pos3D.y-min3D.y)/size3D.y*movieSize.y)); } private function projectVertex(v:Vertex3D, light:Number3D, invMat:Matrix3D, world:Matrix3D):Number3D{ var pos:Number3D = vertexRefs[v]; if(pos) return pos; var n:Number3D = numberRefs[v]; if(!n){ n = new Number3D(v.x, v.y, v.z); Matrix3D.multiplyVector(world, n); Matrix3D.multiplyVector(invMat, n); numberRefs[v] = n; } if(_type == SPOTLIGHT){ lightRay.x = light.x; lightRay.y = light.y; lightRay.z = light.z; }else{ lightRay.x = n.x-dir.x; lightRay.y = n.y-dir.y; lightRay.z = n.z-dir.z; } pos = p3d.getIntersectionLineNumbers(lightRay, n); vertexRefs[v] = pos; return pos; } } } package designLab.utils { public class LayerConstant { public const INTRO:String = "INTRO"; // Intro layer string constant } }*emphasized text*

    Read the article

  • Application Interface between a PC and an embedded device

    - by sasayins
    Hi, How can I make an application interface so that a PC application can communicate to an embedded device like a POS terminal? Like for example, an embedded device like POS terminal that has an embedded linux as an OS. Then I want a PC application to communicate in that POS terminal and access its module hardware like for example its magnetic stripe reader. What implementation should I create in the device, should I use CORBA or something related in that technology so that a PC application can communicate in the POS terminal? Many thanks.

    Read the article

  • QValidator for hex input

    - by Evan Teran
    I have a Qt widget which should only accept a hex string as input. It is very simple to restrict the input characters to [0-9A-Fa-f], but I would like to have it display with a delimiter between "bytes" so for example if the delimiter is a space, and the user types 0011223344 I would like the line edit to display 00 11 22 33 44 Now if the user presses the backspace key 3 times, then I want it to display 00 11 22 3. I almost have what i want, so far there is only one subtle bug involving using the delete key to remove a delimiter. Does anyone have a better way to implement this validator? Here's my code so far: class HexStringValidator : public QValidator { public: HexStringValidator(QObject * parent) : QValidator(parent) {} public: virtual void fixup(QString &input) const { QString temp; int index = 0; // every 2 digits insert a space if they didn't explicitly type one Q_FOREACH(QChar ch, input) { if(std::isxdigit(ch.toAscii())) { if(index != 0 && (index & 1) == 0) { temp += ' '; } temp += ch.toUpper(); ++index; } } input = temp; } virtual State validate(QString &input, int &pos) const { if(!input.isEmpty()) { // TODO: can we detect if the char which was JUST deleted // (if any was deleted) was a space? and special case this? // as to not have the bug in this case? const int char_pos = pos - input.left(pos).count(' '); int chars = 0; fixup(input); pos = 0; while(chars != char_pos) { if(input[pos] != ' ') { ++chars; } ++pos; } // favor the right side of a space if(input[pos] == ' ') { ++pos; } } return QValidator::Acceptable; } }; For now this code is functional enough, but I'd love to have it work 100% as expected. Obviously the ideal would be the just separate the display of the hex string from the actual characters stored in the QLineEdit's internal buffer but I have no idea where to start with that and I imagine is a non-trivial undertaking. In essence, I would like to have a Validator which conforms to this regex: "[0-9A-Fa-f]( [0-9A-Fa-f])*" but I don't want the user to ever have to type a space as delimiter. Likewise, when editing what they types, the spaces should be managed implicitly.

    Read the article

  • Android Expandable List View Update

    - by Gaurav Arora
    I am implementing a chatting application, where I have made a service to listen all the presence changed. On the change of the presence I want to update the data and I am unable to update the data that is showing in the expandable list view. Please suggest me a means to do the same. public class UserMenuActivity extends ExpandableListActivity { private XMPPConnection connection; String name,availability,subscriptionStatus; TextView tv_Status; /** Variable Define here */ private String[] data = { "View my profile", "New Multiperson Chat", "New Broad Cast Message", "New Contact Category", "New Group", "Invite to CCM", "Search", "Expand All", "Settings", "Help", "Close" }; private String[] data_Contact = { "Rename Category","Move Contact to Category", "View my profile", "New Multiperson Chat", "New Broad Cast Message", "New Contact Category", "New Group", "Invite to CCM", "Search", "Expand All", "Settings", "Help", "Close" }; private String[] data_child_contact = { "Open chat", "Delete Contact","View my profile", "New Multiperson Chat", "New Broad Cast Message", "New Contact Category", "New Group", "Invite to CCM", "Search", "Expand All", "Settings", "Help", "Close" }; private String[] menuItem = { "Chats", "Contacts", "CGM Groups", "Pending","Request" }; private List<String> menuItemList = Arrays.asList(menuItem); private int commonGroupPosition = 0; private String etAlertVal; private DatabaseHelper dbHelper; private int categoryID, listPos; /** New Code here.. */ private ArrayList<String> groupNames; private ArrayList<ArrayList<ChildItems>> childs; private UserMenuAdapter adapter; private Object object; private String[] data2 = { "PIN Michelle", "IP Call" }; private ListView mlist2; private ImageButton mimBtnMenu; private LinearLayout mllpopmenu; private View popupView; private PopupWindow popupWindow; private AlertDialog.Builder alert; private EditText input; private TextView mtvUserName, mtvUserTagLine; private ExpandableListView mExpandableListView; public static List<CategoryDataClass> categoryList; private boolean menuType = false; private String childValContact=""; public static Context context; @Override public void onBackPressed() { if (mllpopmenu.getVisibility() == View.VISIBLE) { mllpopmenu.setVisibility(View.INVISIBLE); } else { if (CCMStaticVariable.CommonConnection.isConnected()) { CCMStaticVariable.CommonConnection.disconnect(); } super.onBackPressed(); } } @SuppressWarnings("unchecked") @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { if (mllpopmenu.getVisibility() == View.VISIBLE) { mllpopmenu.setVisibility(View.INVISIBLE); } else { if (commonGroupPosition >= 4 && menuType == true) { if(childValContact == ""){ mllpopmenu.setVisibility(View.VISIBLE); mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this, R.layout.listviewtext, R.id.tvMenuText, data_Contact)); }else{ mllpopmenu.setVisibility(View.VISIBLE); mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this, R.layout.listviewtext, R.id.tvMenuText, data_child_contact)); } } else if (commonGroupPosition == 0) { mllpopmenu.setVisibility(View.VISIBLE); mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this, R.layout.listviewtext, R.id.tvMenuText, data)); } } return true; } return super.onKeyDown(keyCode, event); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.usermenulayout); dbHelper = new DatabaseHelper(UserMenuActivity.this); //this.context = context.getApplicationContext(); XMPPConn.getContactList(); connection = CCMStaticVariable.CommonConnection; Presence userPresence = new Presence(Presence.Type.available); userPresence.setPriority(24); userPresence.setMode(Presence.Mode.away); connection.sendPacket(userPresence); } @Override protected void onResume() { super.onResume(); Presence userPresence = new Presence(Presence.Type.available); userPresence.setPriority(24); userPresence.setMode(Presence.Mode.away); connection.sendPacket(userPresence); XMPPConn.getContactList(); setExpandableListView(); } public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { if (groupPosition == 1 && childPosition == 0) { startActivity(new Intent(UserMenuActivity.this, InvitetoCCMActivity.class)); } else if (groupPosition == 1 && childPosition != 0) { Intent intent = new Intent(UserMenuActivity.this, UserChatActivity.class); intent.putExtra("userNameVal", XMPPConn.mfriendList.get(childPosition - 1).friendName); startActivity(intent); } else if (groupPosition == 2 && childPosition == 0) { startActivity(new Intent(UserMenuActivity.this, CreateGroupActivity.class)); } else if (groupPosition == 2 && childPosition != 0) { String GROUP_NAME = childs.get(groupPosition).get(childPosition) .getName().toString(); int end = GROUP_NAME.indexOf("("); CCMStaticVariable.groupName = GROUP_NAME.substring(0, end).trim(); startActivity(new Intent(UserMenuActivity.this, GroupsActivity.class)); } else if (groupPosition >= 4) { childValContact = childs.get(groupPosition).get(childPosition).getName().trim(); showToast("user==>"+childValContact, 0); } return false; } private void setExpandableListView() { /***###############GROUP ARRAY ############################*/ final ArrayList<String> groupNames = new ArrayList<String>(); groupNames.add("Chats (2)"); groupNames.add("Contacts (" + XMPPConn.mfriendList.size() + ")"); groupNames.add("CGM Groups (" + XMPPConn.mGroupList.size() + ")"); groupNames.add("Pending (1)"); XMPPConn.getGroup(); categoryList = dbHelper.getAllCategory(); /**Group From Sever*/ if (XMPPConn.mGroupList.size() > 0) { for (int g = 0; g < XMPPConn.mGroupList.size(); g++) { XMPPConn.getGroupContact(XMPPConn.mGroupList.get(g).groupName); groupNames.add(XMPPConn.mGroupList.get(g).groupName + "(" + XMPPConn.mGroupContactList.size()+ ")"); } } if(categoryList.size() > 0){ for (int cat = 0; cat < categoryList.size(); cat++) { groupNames.add(categoryList.get(cat).getCategoryName()+ "(0)"); } } this.groupNames = groupNames; /*** ###########CHILD ARRAY * #################*/ ArrayList<ArrayList<ChildItems>> childs = new ArrayList<ArrayList<ChildItems>>(); ArrayList<ChildItems> child = new ArrayList<ChildItems>(); child.add(new ChildItems("Alisha", "Hi",0)); child.add(new ChildItems("Michelle", "Good Morning",0)); childs.add(child); child = new ArrayList<ChildItems>(); child.add(new ChildItems("", "",0)); if (XMPPConn.mfriendList.size() > 0) { for (int n = 0; n < XMPPConn.mfriendList.size(); n++) { child.add(new ChildItems(XMPPConn.mfriendList.get(n).friendNickName, XMPPConn.mfriendList.get(n).friendStatus, XMPPConn.mfriendList.get(n).friendState)); } } childs.add(child); /************** CGM Group Child here *********************/ child = new ArrayList<ChildItems>(); child.add(new ChildItems("", "",0)); if (XMPPConn.mGroupList.size() > 0) { for (int grop = 0; grop < XMPPConn.mGroupList.size(); grop++) { child.add(new ChildItems( XMPPConn.mGroupList.get(grop).groupName + " (" + XMPPConn.mGroupList.get(grop).groupUserCount + ")", "",0)); } } childs.add(child); child = new ArrayList<ChildItems>(); child.add(new ChildItems("Shuchi", "Pending (Waiting for Authorization)",0)); childs.add(child); /************************ Group Contact List *************************/ if (XMPPConn.mGroupList.size() > 0) { for (int g = 0; g < XMPPConn.mGroupList.size(); g++) { /** Contact List */ XMPPConn.getGroupContact(XMPPConn.mGroupList.get(g).groupName); child = new ArrayList<ChildItems>(); for (int con = 0; con < XMPPConn.mGroupContactList.size(); con++) { child.add(new ChildItems( XMPPConn.mGroupContactList.get(con).friendName, XMPPConn.mGroupContactList.get(con).friendStatus,0)); } childs.add(child); } } if(categoryList.size() > 0){ for (int cat = 0; cat < categoryList.size(); cat++) { child = new ArrayList<ChildItems>(); child.add(new ChildItems("-none-", "",0)); childs.add(child); } } this.childs = childs; /** Set Adapter here */ adapter = new UserMenuAdapter(this, groupNames, childs); setListAdapter(adapter); object = this; mlist2 = (ListView) findViewById(R.id.list2); mimBtnMenu = (ImageButton) findViewById(R.id.imBtnMenu); mllpopmenu = (LinearLayout) findViewById(R.id.llpopmenu); mtvUserName = (TextView) findViewById(R.id.tvUserName); mtvUserTagLine = (TextView) findViewById(R.id.tvUserTagLine); //Set User name.. System.out.println("CCMStaticVariable.loginUserName===" + CCMStaticVariable.loginUserName); if (!CCMStaticVariable.loginUserName.equalsIgnoreCase("")) { mtvUserName.setText("" + CCMStaticVariable.loginUserName); } /** Expandable List set here.. */ mExpandableListView = (ExpandableListView) this .findViewById(android.R.id.list); mExpandableListView.setOnGroupClickListener(new OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { XMPPConn.getContactList(); if (parent.isGroupExpanded(groupPosition)) { commonGroupPosition = 0; }else{ commonGroupPosition = groupPosition; } String GROUP_NAME = groupNames.get(groupPosition); int end = groupNames.get(groupPosition).indexOf("("); String GROUP_NAME_VALUE = GROUP_NAME.substring(0, end).trim(); if (menuItemList.contains(GROUP_NAME_VALUE)) { menuType = false; CCMStaticVariable.groupCatName = GROUP_NAME_VALUE; } else { menuType = true; CCMStaticVariable.groupCatName = GROUP_NAME_VALUE; } long findCatId = dbHelper.getCategoryID(GROUP_NAME_VALUE); if (findCatId != 0) { categoryID = (int) findCatId; } childValContact=""; showToast("Clicked on==" + GROUP_NAME_VALUE, 0); return false; } }); /** Click on item */ mlist2.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long arg3) { if (commonGroupPosition >= 4) { if(childValContact == ""){ if (pos == 0) { showAlertEdit(CCMStaticVariable.groupCatName); } /** Move contact to catgory */ if (pos == 1) { startActivity(new Intent(UserMenuActivity.this,AddContactCategoryActivity.class)); } }else{ if(pos == 0){ Intent intent = new Intent(UserMenuActivity.this,UserChatActivity.class); intent.putExtra("userNameVal",childValContact); startActivity(intent); } if(pos == 1){ XMPPConn.removeEntry(childValContact); showToast("Contact deleted sucessfully", 0); Intent intent = new Intent(UserMenuActivity.this,UserMenuActivity.class); } } } else { /** MyProfile */ if (pos == 0) { startActivity(new Intent(UserMenuActivity.this, MyProfileActivity.class)); } /** New multiperson chat start */ if (pos == 1) { startActivity(new Intent(UserMenuActivity.this, NewMultipersonChatActivity.class)); } /** New Broadcast message */ if (pos == 2) { startActivity(new Intent(UserMenuActivity.this, NewBroadcastMessageActivity.class)); } /** Click on add category */ if (pos == 3) { showAlertAdd(); } if (pos == 4) { startActivity(new Intent(UserMenuActivity.this, CreateGroupActivity.class)); } if (pos == 5) { startActivity(new Intent(UserMenuActivity.this, InvitetoCCMActivity.class)); } if (pos == 6) { startActivity(new Intent(UserMenuActivity.this, SearchActivity.class)); } if (pos == 7) { onGroupExpand(2); for (int i = 0; i < groupNames.size(); i++) { mExpandableListView.expandGroup(i); } } /** Click on settings */ if (pos == 8) { startActivity(new Intent(UserMenuActivity.this, SettingsActivity.class)); } if (pos == 10) { System.exit(0); } if (pos == 14) { if (mllpopmenu.getVisibility() == View.VISIBLE) { mllpopmenu.setVisibility(View.INVISIBLE); if (popupWindow.isShowing()) { popupWindow.dismiss(); } } else { mllpopmenu.setVisibility(View.VISIBLE); mlist2.setAdapter(new ArrayAdapter( UserMenuActivity.this, R.layout.listviewtext, R.id.tvMenuText, data)); } } } } }); } /** Toast message display here.. */ private void showToast(String msg, int time) { Toast.makeText(this, msg, time).show(); } public String showSubscriptionStatus(String friend){ return friend; } } Service.class public class UpdaterService extends Service { private XMPPConnection connection; String Friend; String user = ""; @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show(); super.onCreate(); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub showToast("My Service Started", 0); connection = getConnection(); if (connection.isConnected()) { final Roster roster = connection.getRoster(); RosterListener r1 = new RosterListener() { @Override public void presenceChanged(Presence presence) { // TODO Auto-generated method stub XMPPConn.getContactList(); } @Override public void entriesUpdated(Collection<String> arg0) { // TODO Auto-generated method stub //notification("entriesUpdated"); } @Override public void entriesDeleted(Collection<String> arg0) { // TODO Auto-generated method stub //notification("entriesDeleted"); } @Override public void entriesAdded(Collection<String> arg0) { // TODO Auto-generated method stub Iterator<String> it = arg0.iterator(); if (it.hasNext()) { user = it.next(); } RosterEntry entry = roster.getEntry(user); if(entry.getType().toString().equalsIgnoreCase("to")){ int index_of_Alpha = Friend.indexOf("@"); String subID = Friend.substring(0, index_of_Alpha); notification("Hi "+subID+" wants to add you"); } } }; if (roster != null) { roster.setSubscriptionMode(Roster.SubscriptionMode.manual); System.out.println("subscription going on"); roster.addRosterListener(r1); } } else { showToast("Connection lost-", 0); } } protected void showToast(String msg, int time) { Toast.makeText(this, msg, time).show(); } private XMPPConnection getConnection() { return CCMStaticVariable.CommonConnection; } /** Notification manager */ private void notification(CharSequence message) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); int icon = R.drawable.ic_launcher; CharSequence tickerText = message; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); Context context = getApplicationContext(); CharSequence contentTitle = "CCM"; CharSequence contentText = message; Intent notificationIntent = new Intent(this, ManageNotification.class); notificationIntent.putExtra("Subscriber_ID",user ); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); notification.flags |= Notification.FLAG_AUTO_CANCEL; final int HELLO_ID = 1; mNotificationManager.notify(HELLO_ID, notification); } } Here is my adapter class public class UserMenuAdapter extends BaseExpandableListAdapter { private ArrayList<String> groups; private ArrayList<ArrayList<ChildItems>> childs; private Context context; public LayoutInflater inflater; ImageView img_availabiliy; private static final int[] EMPTY_STATE_SET = {}; private static final int[] GROUP_EXPANDED_STATE_SET = {android.R.attr.state_expanded}; private static final int[][] GROUP_STATE_SETS = { EMPTY_STATE_SET, // 0 GROUP_EXPANDED_STATE_SET // 1 }; public UserMenuAdapter(Context context, ArrayList<String> groups, ArrayList<ArrayList<ChildItems>> childs) { this.context = context; this.groups = groups; this.childs = childs; inflater = LayoutInflater.from(context); } @Override public Object getChild(int groupPosition, int childPosition) { return childs.get(groupPosition).get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { return (long) (groupPosition * 1024 + childPosition); } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { View v = null; if (convertView != null) v = convertView; else v = inflater.inflate(R.layout.child_layout, parent, false); ChildItems ci = (ChildItems) getChild(groupPosition, childPosition); TextView tv = (TextView) v.findViewById(R.id.tvChild); tv.setText(ci.getName()); TextView tv2 = (TextView) v.findViewById(R.id.tvChild2); tv2.setText(ci.getDailyStatus()); img_availabiliy = (ImageView)v.findViewById(R.id.img_childlayout_AVAILABILITY); ImageView friendPics = (ImageView)v.findViewById(R.id.ivFriendPics); if(ci.getStatusState() == 1){ img_availabiliy.setImageResource(R.drawable.online); } else if(ci.getStatusState()==0){ img_availabiliy.setImageResource(R.drawable.offline); } else if (ci.getStatusState()==2) { img_availabiliy.setImageResource(R.drawable.away); } else if(ci.getStatusState()==3){ img_availabiliy.setImageResource(R.drawable.busy); } else{ img_availabiliy.setImageDrawable(null); } if((groupPosition == 1 && childPosition == 0)){ friendPics.setImageResource(R.drawable.inviteto_ccm); img_availabiliy.setVisibility(View.INVISIBLE); } else if(groupPosition == 2 && childPosition == 0){ friendPics.setImageResource(R.drawable.new_ccmgroup); img_availabiliy.setVisibility(View.VISIBLE); }else{ if(ci.getPicture()!= null){ Bitmap bitmap = BitmapFactory.decodeByteArray(ci.getPicture(), 0, ci.getPicture().length); bitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, true); friendPics.setImageBitmap(bitmap); }else{ friendPics.setImageResource(R.drawable.avatar); } img_availabiliy.setVisibility(View.VISIBLE); } return v; } @Override public int getChildrenCount(int groupPosition) { return childs.get(groupPosition).size(); } @Override public Object getGroup(int groupPosition) { return groups.get(groupPosition); } @Override public int getGroupCount() { return groups.size(); } @Override public long getGroupId(int groupPosition) { return (long) (groupPosition * 1024); } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { View v = null; if (convertView != null) v = convertView; else v = inflater.inflate(R.layout.group_layout, parent, false); String gt = (String) getGroup(groupPosition); TextView tv2 = (TextView) v.findViewById(R.id.tvGroup); if (gt != null) tv2.setText(gt); /**Set Image on group layout, Max/min*/ View ind = v.findViewById( R.id.explist_indicator); View groupInd = v.findViewById( R.id.llgroup); if( ind != null ) { ImageView indicator = (ImageView)ind; if( getChildrenCount( groupPosition ) == 0 ) { indicator.setVisibility( View.INVISIBLE ); } else { indicator.setVisibility( View.VISIBLE ); int stateSetIndex = ( isExpanded ? 1 : 0) ; Drawable drawable = indicator.getDrawable(); drawable.setState(GROUP_STATE_SETS[stateSetIndex]); } } if( groupInd != null ) { RelativeLayout indicator2 = (RelativeLayout)groupInd; if( getChildrenCount( groupPosition ) == 0 ) { indicator2.setVisibility( View.INVISIBLE ); } else { indicator2.setVisibility( View.VISIBLE ); int stateSetIndex = ( isExpanded ? 1 : 0) ; Drawable drawable2 = indicator2.getBackground(); drawable2.setState(GROUP_STATE_SETS[stateSetIndex]); } } return v; } @Override public boolean hasStableIds() { return true; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } public void onGroupCollapsed(int groupPosition) { } public void onGroupExpanded(int groupPosition) { } } I just want to update my list in ON PRESENCE CHANGED method in the Service class.. Please suggest me a means to do the same.

    Read the article

  • How to have struct members accessible in different ways

    - by Paul J. Lucas
    I want to have a structure token that has start/end pairs for position, sentence, and paragraph information. I also want the members to be accessible in two different ways: as a start/end pair and individually. Given: struct token { struct start_end { int start; int end; }; start_end pos; start_end sent; start_end para; typedef start_end token::*start_end_ptr; }; I can write a function, say distance(), that computes the distance between any of the three start/end pairs like: int distance( token const &i, token const &j, token::start_end_ptr mbr ) { return (j.*mbr).start - (i.*mbr).end; } and call it like: token i, j; int d = distance( i, j, &token::pos ); that will return the distance of the pos pair. But I can also pass &token::sent or &token::para and it does what I want. Hence, the function is flexible. However, now I also want to write a function, say max(), that computes the maximum value of all the pos.start or all the pos.end or all the sent.start, etc. If I add: typedef int token::start_end::*int_ptr; I can write the function like: int max( list<token> const &l, token::int_ptr p ) { int m = numeric_limits<int>::min(); for ( list<token>::const_iterator i = l.begin(); i != l.end(); ++i ) { int n = (*i).pos.*p; // NOT WHAT I WANT: It hard-codes 'pos' if ( n > m ) m = n; } return m; } and call it like: list<token> l; l.push_back( i ); l.push_back( j ); int m = max( l, &token::start_end::start ); However, as indicated in the comment above, I do not want to hard-code pos. I want the flexibility of accessible the start or end of any of pos, sent, or para that will be passed as a parameter to max(). I've tried several things to get this to work (tried using unions, anonymous unions, etc.) but I can't come up with a data structure that allows the flexibility both ways while having each value stored only once. Any ideas how to organize the token struct so I can have what I want? Attempt at clarification Given struct of pairs of integers, I want to be able to "slice" the data in two distinct ways: By passing a pointer-to-member of a particular start/end pair so that the called function operates on any pair without knowing which pair. The caller decides which pair. By passing a pointer-to-member of a particular int (i.e., only one int of any pair) so that the called function operates on any int without knowing either which int or which pair said int is from. The caller decides which int of which pair. Another example for the latter would be to sum, say, all para.end or all sent.start. Also, and importantly: for #2 above, I'd ideally like to pass only a single pointer-to-member to reduce the burden on the caller. Hence, me trying to figure something out using unions.

    Read the article

  • Trying to create text boxes dynammically and remove them

    - by fari
    I am using VB.NET vb 2008 . I am trying to create text boxes dynammically and remove them here is the code i have written so far Private Sub setTextBox() Dim num As Integer Dim pos As Integer num = Len(word) temp = String.Copy(word) Dim intcount As Integer remove() GuessBox.Visible = True letters.Visible = True pos = 0 'To create the dynamic text box and add the controls For intcount = 0 To num - 1 Txtdynamic = New TextBox Txtdynamic.Width = 20 Txtdynamic.Visible = True Txtdynamic.MaxLength = 1 Txtdynamic.Location = New Point(pos + 5, 0) pos = pos + 30 'set the font size Txtdynamic.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Txtdynamic.Name = "txtdynamic_" & intcount & "_mycntrl" Txtdynamic.Enabled = False Txtdynamic.Text = "" Panel1.Controls.Add(Txtdynamic) Next Panel1.Visible = True Controls.Add(Panel1) Controls.Add(GuessBox) Controls.Add(letters) letter = "" letters.Text = "" hang_lable.Text = "" tries = 0 End Sub`enter code here` Function remove() For Each ctrl In Panel1.Controls Panel1.Controls.Remove(ctrl) Next End Function I am able to create the textboxes but only a few of them are removed. by using For Each ctrl In Panel1.Controls it doesn't retrieve all the controls and some ae duplicated as well.

    Read the article

  • why won't my ajax work asynchronously

    - by payling
    I'm having trouble understanding why my code will not work asynchronously. When running asynchronously the get_price.php always receives the same $_GET value even though the alert before outputs a unique $_GET value. var arraySize = "<? echo count($_SESSION['items']); ?>"; //get items count var pos = 0; var pid; var qty; getPriceAjax(); function getPriceAjax() { pid = document.cartItemForm.elements[pos].id; //product id qty = document.cartItemForm.elements[pos].value; //quantity alert('Product: ' + pid + ' Quantity: ' + qty); $.ajax({ url:"includes/ajax_php/get_price.php", type:"GET", data:'pid='+pid+'&qty='+qty, async:true, cache:false, success:function(data){ while(pos < arraySize) { document.getElementById(pid + 'result').innerHTML=data; pos++; getPriceAjax(); } } }) }

    Read the article

  • Javascript Closure question.

    - by Tony
    Why the following code prints "0-100"? (function () { for ( var i = 100; i >= 0; i -= 5) { (function() { var pos = i; setTimeout(function() { console.log(" pos = " + pos); }, (pos + 1)*10); })(); } })(); I declare pos = i , which should be in a descending order. This code originated from John Resig' fadeIn() function in his book Pro javascript techniques.

    Read the article

  • I am using vb 2008 . I am trying to create text boxes dynammically and remove them here isthe code i

    - by fari
    Private Sub setTextBox() Dim num As Integer Dim pos As Integer num = Len(word) temp = String.Copy(word) Dim intcount As Integer remove() GuessBox.Visible = True letters.Visible = True pos = 0 'To create the dynamic text box and add the controls For intcount = 0 To num - 1 Txtdynamic = New TextBox Txtdynamic.Width = 20 Txtdynamic.Visible = True Txtdynamic.MaxLength = 1 Txtdynamic.Location = New Point(pos + 5, 0) pos = pos + 30 'set the font size Txtdynamic.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Txtdynamic.Name = "txtdynamic_" & intcount & "_mycntrl" Txtdynamic.Enabled = False Txtdynamic.Text = "" Panel1.Controls.Add(Txtdynamic) Next Panel1.Visible = True Controls.Add(Panel1) Controls.Add(GuessBox) Controls.Add(letters) letter = "" letters.Text = "" hang_lable.Text = "" tries = 0 End Sub`enter code here` Function remove() For Each ctrl In Panel1.Controls Panel1.Controls.Remove(ctrl) Next End Function I am able to create the textboxes but only a few of them are removed. by using For Each ctrl In Panel1.Controls it doesn't retrieve all the controls and some ae duplicated as well. Can anyone pls help me. Thanks

    Read the article

  • Generics not so generic !!

    - by Aymen
    Hi I tried to implement a generic binary search algorithm in scala. Here it is : type Ord ={ def <(x:Any):Boolean def >(x:Any):Boolean } def binSearch[T <: Ord ](x:T,start:Int,end:Int,t:Array[T]):Boolean = { if (start > end) return false val pos = (start + end ) / 2 if(t(pos)==x) true else if (t(pos) < x) binSearch(x,pos+1,end,t) else binSearch(x,start,pos-1,t) } everything is OK until I tried to actually use it (xD) : binSearch(3,0,4,Array(1,2,5,6)) the compiler is pretending that Int not a member of Ord, well what shall I do to solve this ? Thanks

    Read the article

  • simple collision detection with box2dweb

    - by skywalker
    im beginner in box2dweb that version of box2d for javascript i wrote simple gravity system and i want to detect the collision between the box and the ground , when the falling box hit the ground execute simple function like function sucs(){alert("the box on the floor !")}; this is my code var CANVAS_WIDTH = 1024, CANVAS_HEIGHT = 700, SCALE = 30; var b2Vec2 = Box2D.Common.Math.b2Vec2 , b2BodyDef = Box2D.Dynamics.b2BodyDef , b2Body = Box2D.Dynamics.b2Body , b2FixtureDef = Box2D.Dynamics.b2FixtureDef , b2Fixture = Box2D.Dynamics.b2Fixture , b2World = Box2D.Dynamics.b2World , b2MassData = Box2D.Collision.Shapes.b2MassData , b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape , b2CircleShape = Box2D.Collision.Shapes.b2CircleShape , b2DebugDraw = Box2D.Dynamics.b2DebugDraw; var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); var world = new b2World(new b2Vec2(0, 8), true); var fixDef = new b2FixtureDef(); var bodyDef = new b2BodyDef(); fixDef.density = 1.0; fixDef.friction = 0.5; bodyDef.type = b2Body.b2_staticBody; fixDef.shape = new b2PolygonShape; fixDef.shape.SetAsBox(20, 2); bodyDef.position.Set(10, 400 / 30 + 1.8); world.CreateBody(bodyDef).CreateFixture(fixDef); fixDef.density = 1.0; fixDef.friction = 0.5; fixDef.restitution = 0.3; bodyDef.type = b2Body.b2_dynamicBody; bodyDef.position.Set(50 / SCALE, 0 / SCALE); //bodyDef.linearVelocity.Set((Math.random() * 12) + 2, (Math.random() * 12) + 2); fixDef.shape = new b2PolygonShape(); fixDef.shape.SetAsBox(25 / SCALE, 25 / SCALE); world.CreateBody(bodyDef).CreateFixture(fixDef); var debugDraw = new b2DebugDraw(); debugDraw.SetSprite(document.getElementById("canvas").getContext("2d")); debugDraw.SetDrawScale(30.0); debugDraw.SetFillAlpha(0.5); debugDraw.SetLineThickness(1.0); debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit); world.SetDebugDraw(debugDraw); var image = new Image(); image.src = "image.png"; window.setInterval(gameLoop, 1000 / 60); function gameLoop() { world.Step(1 / 60, 8, 3); world.ClearForces(); context.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); b = world.GetBodyList() var pos = b.GetPosition(); context.save(); context.translate(pos.x * SCALE, pos.y * SCALE); context.rotate(b.GetAngle()); context.drawImage(image, -25, -25); context.restore(); b = b.GetNext(); pos = b.GetPosition(); context.save(); context.translate(pos.x * SCALE, pos.y * SCALE); //b.GetAngle()++; context.rotate(b.GetAngle()); context.drawImage(image, -25, -25); context.restore(); world.DrawDebugData(); };

    Read the article

  • Why are my Unity procedural animations jerky?

    - by Phoenix Perry
    I'm working in Unity and getting some crazy weird motion behavior. I have a plane and I'm moving it. It's ever so slightly getting about 1 pixel bigger and smaller. It looks like the it's kind of getting squeezed sideways by a pixel. I'm moving a plane by cos and sin so it will spin on the x and z axes. If the planes are moving at Time.time, everything is fine. However, if I put in slower speed multiplier, I get an amazingly weird jerk in my animation. I get it with or without the lerp. How do I fix it? I want it to move very slowly. Is there some sort of invisible grid in unity? Some sort of minimum motion per frame? I put a visual sample of the behavior here. Here's the relevant code: public void spin() { for (int i = 0; i < numPlanes; i++ ) { GameObject g = planes[i] as GameObject; //alt method //currentRotation += speed * Time.deltaTime * 100; //rotation.eulerAngles = new Vector3(0, currentRotation, 0); //g.transform.position = rotation * rotationRadius; //sine method g.GetComponent<PlaneSetup>().pos.x = g.GetComponent<PlaneSetup>().radiusX * (Mathf.Cos((Time.time*speed) + g.GetComponent<PlaneSetup>().startAngle)); g.GetComponent<PlaneSetup>().pos.z = g.GetComponent<PlaneSetup>().radius * Mathf.Sin((Time.time*speed) + g.GetComponent<PlaneSetup>().startAngle); g.GetComponent<PlaneSetup>().pos.y = g.GetComponent<Transform>().position.y; ////offset g.GetComponent<PlaneSetup>().pos.z += 20; g.GetComponent<PlaneSetup>().posLerp.x = Mathf.Lerp(g.transform.position.x,g.GetComponent<PlaneSetup>().pos.x, .5f); g.GetComponent<PlaneSetup>().posLerp.z = Mathf.Lerp(g.transform.position.z, g.GetComponent<PlaneSetup>().pos.z, .5f); g.GetComponent<PlaneSetup>().posLerp.y = g.GetComponent<Transform>().position.y; g.transform.position = g.GetComponent<PlaneSetup>().posLerp; } Invoke("spin",0.0f); } The full code is on github. There is literally nothing else going on. I've turned off all other game objects so it's only the 40 planes with a texture2D shader. I removed it from Invoke and tried it in Update -- still happens. With a set frame rate or not, the same problem occurs. Tested it in Fixed Update. Same issue. The script on the individual plane doesn't even have an update function in it. The data on it could functionally live in a struct. I'm getting between 90 and 123 fps. Going to investigate and test further. I put this in an invoke function to see if I could get around it just occurring in update. There are no physics on these shapes. It's a straight procedural animation. Limited it to 1 plane - still happens. Thoughts? Removed the shader - still happening.

    Read the article

  • How to use a list of values in Excel as filter in a query

    - by Luca Zavarella
    It often happens that a customer provides us with a list of items for which to extract certain information. Imagine, for example, that our clients wish to have the header information of the sales orders only for certain orders. Most likely he will give us a list of items in a column in Excel, or, less probably, a simple text file with the identification code:     As long as the given values ??are at best a dozen, it costs us nothing to copy and paste those values ??in our SSMS and place them in a WHERE clause, using the IN operator, making sure to include the quotes in the case of alphanumeric elements (the database sample is AdventureWorks2008R2): SELECT * FROM Sales.SalesOrderHeader AS SOH WHERE SOH.SalesOrderNumber IN ( 'SO43667' ,'SO43709' ,'SO43726' ,'SO43746' ,'SO43782' ,'SO43796') Clearly, the need to add commas and quotes becomes an hassle when dealing with hundreds of items (which of course has happened to us!). It’d be comfortable to do a simple copy and paste, leaving the items as they are pasted, and make sure the query works fine. We can have this commodity via a User Defined Function, that returns items in a table. Simply we’ll provide the function with an input string parameter containing the pasted items. I give you directly the T-SQL code, where comments are there to clarify what was written: CREATE FUNCTION [dbo].[SplitCRLFList] (@List VARCHAR(MAX)) RETURNS @ParsedList TABLE ( --< Set the item length as your needs Item VARCHAR(255) ) AS BEGIN DECLARE --< Set the item length as your needs @Item VARCHAR(255) ,@Pos BIGINT --< Trim TABs due to indentations SET @List = REPLACE(@List, CHAR(9), '') --< Trim leading and trailing spaces, then add a CR\LF at the end of the list SET @List = LTRIM(RTRIM(@List)) + CHAR(13) + CHAR(10) --< Set the position at the first CR/LF in the list SET @Pos = CHARINDEX(CHAR(13) + CHAR(10), @List, 1) --< If exist other chars other than CR/LFs in the list then... IF REPLACE(@List, CHAR(13) + CHAR(10), '') <> '' BEGIN --< Loop while CR/LFs are over (not found = CHARINDEX returns 0) WHILE @Pos > 0 BEGIN --< Get the heading list chars from the first char to the first CR/LF and trim spaces SET @Item = LTRIM(RTRIM(LEFT(@List, @Pos - 1))) --< If the so calulated item is not empty... IF @Item <> '' BEGIN --< ...insert it in the @ParsedList temporary table INSERT INTO @ParsedList (Item) VALUES (@Item) --(CAST(@Item AS int)) --< Use the appropriate conversion if needed END --< Remove the first item from the list... SET @List = RIGHT(@List, LEN(@List) - @Pos - 1) --< ...and set the position to the next CR/LF SET @Pos = CHARINDEX(CHAR(13) + CHAR(10), @List, 1) --< Repeat this block while the upon loop condition is verified END END RETURN END At this point, having created the UDF, our query is transformed trivially in: SELECT * FROM Sales.SalesOrderHeader AS SOH WHERE SOH.SalesOrderNumber IN ( SELECT Item FROM SplitCRLFList('SO43667 SO43709 SO43726 SO43746 SO43782 SO43796') AS SCL) Convenient, isn’t it? You can find the script DBA_SplitCRLFList.sql here. Bye!!

    Read the article

  • what is the best way to use loops to detect events while the main loop is running?

    - by yao jiang
    I am making an "game" that has pathfinding using pygame. I am using Astar algo. I have a main loop which draws the whole map. In the loop I check for events. If user press "enter" or "space", random start and end are selected, then animation starts and it will try to get from start to end. My draw function is stupid as hell right now, it works as expected but I feel that I am doing it wrong. It'll draw everything to the end of the animation. I am also detecting events in there as well. What is a better way of implementing the draw function such that it will draw one "step" at a time while checking for events? animating = False; while loop: check events: if not animating: # space or enter press will choose random start/end coords if enter_pressed or space_pressed: start, end = choose_coords route = find_route(start, end) draw(start, end, grid, route) else: # left click == generate an event to block the path # right click == user can choose a new destination if left_mouse_click: gen_event() reroute() elif right_mouse_click: new_end = new_end() new_start = current_pos() route = find_route(new_start, new_end) draw(new_start, new_end, grid, route) # draw out the grid def draw(start, end, grid, route_coord): # draw the end coords color = red; pick_image(screen, color, width*end[1],height*end[0]); pygame.display.flip(); # then draw the rest of the route for i in range(len(route_coord)): # pausing because we want animation time.sleep(speed); # get the x/y coords x,y = route_coord[i]; event_on = False; if grid[x][y] == 2: color = green; elif grid[x][y] == 3: color = blue; for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 3: print "destination change detected, rerouting"; # get mouse position, px coords pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; grid[r][c] = 4; end = [r, c]; elif event.button == 1: print "user generated event"; pos = pygame.mouse.get_pos(); # get grid coord c = pos[0] // width; r = pos[1] // height; # mark it as a block for now grid[r][c] = 1; event_on = True; if check_events([x,y]) or event_on: # there is an event # mark it as a block for now grid[y][x] = 1; pick_image(screen, event_x, width*y, height*x); pygame.display.flip(); # then find a new route new_start = route_coord[i-1]; marked_grid, route_coord = find_route(new_start, end, grid); draw(new_start, end, grid, route_coord); return; # just end draw here so it wont throw the "index out of range" error elif grid[x][y] == 4: color = red; pick_image(screen, color, width*y, height*x); pygame.display.flip(); # clear route coord list, otherwise itll just add more unwanted coords route_coord_list[:] = [];

    Read the article

  • How to choose light version of databse system

    - by adopilot
    I am starting one POS (Point of sale) project. Targeting system is going to be written in C# .NET 2 WinForms and as main database server We are going to use MS-SQL Server. As we have a lot of POS devices in chain for one store I will love to have backend local data base system on each POS device. Scenario are following: When main server goes down!! POS application should continue working "off-line" with local database, until connection to main server come up again. Now I am in dilemma which local database is going to be most adoptable for me. Here is some notes for helping me point me in right direction: To be Light "My POS devices art usually old and suffering with performances" To be Free "I have a lot of devices and I do not wont additional cost beside main SQL serer" One day Ill love to try all that port on Mono and Linux OS. Here is what I've researched so far: Simple XML "Light but I am afraid of performance, My main table of items is average of 10K records" SQL-Expres "I am afraid that my POS devices is poor with hardware for SQLExpres, and also hard to install on each device and configure" Less known Advantage Database Server have free distribution of offline ADT system. DBF with extended Library,"Respect for good old DBFs but that era is behind Me with clipper and DBFs" MS Access Sqlite "Mostly like for now, but I am afraid how it is going to pair with MS SQL do they have same Data taypes". I know that in this SO is a lot of subjective data, but at least can someone recommended some others lite database system, or things that I shod most take attention before I choice database.

    Read the article

  • How to choose light version of database system

    - by adopilot
    I am starting one POS (Point of sale) project. Targeting system is going to be written in C# .NET 2 WinForms and as main database server We are going to use MS-SQL Server. As we have a lot of POS devices in chain for one store I will love to have backend local data base system on each POS device. Scenario are following: When main server goes down!! POS application should continue working "off-line" with local database, until connection to main server come up again. Now I am in dilemma which local database is going to be most adoptable for me. Here is some notes for helping me point me in right direction: To be Light "My POS devices art usually old and suffering with performances" To be Free "I have a lot of devices and I do not wont additional cost beside main SQL serer" One day Ill love to try all that port on Mono and Linux OS. Here is what I've researched so far: Simple XML "Light but I am afraid of performance, My main table of items is average of 10K records" SQL-Express "I am afraid that my POS devices is poor with hardware for SQLExpress, and also hard to install on each device and configure" Less known Advantage Database Server have free distribution of offline ADT system. DBF with extended Library,"Respect for good old DBFs but that era is behind Me with clipper and DBFs" MS Access Sqlite "Mostly like for now, but I am afraid how it is going to pair with MS SQL do they have same Data types". I know that in this SO is a lot of subjective data, but at least can someone recommended some others lite database system, or things that I shod most take attention before I choice database.

    Read the article

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