Author Archive

Class attributes with examples in jQuery

jQuery Class Attributes are explained with examples below:

.addClass()
Adds one or more classes to each element in the set of matched elements.
.addClass(class)
Parameters: class: One or more class names to be added to the class attribute of each matched element
Return Value
The jQuery object, for chaining purposes.
Description
It’s important to note that this method does not replace a class; it simply adds
the class.
More than one class may be added at a time, separated by a space, to the set of matched elements, like so: $(‘p’).addClass(‘myclass yourclass’).
This method is often used with .removeClass() to switch elements’ classes from one to another, like so:
$(‘p’).removeClass(‘myclass noclass’).addClass(‘yourclass’)
Here, the myclass and noclass classes are removed from all paragraphs, while yourclass is added.

.removeClass()
Removes one or all classes from each element in the set of matched elements.
.removeClass([class])
Parameters: class (optional): A class name to be removed from the class attribute of each matched element
Return Value
The jQuery object, for chaining purposes.
Description
If a class name is included as a parameter, then only that class will be removed from the set of matched elements. If no class names are specified in the parameter, all classes will be removed.
More than one class may be removed at a time, separated by a space, from the set of matched elements, like so: $(‘p’).removeClass(‘myclass yourclass’).
This method is often used with .addClass() to switch elements’ classes from one to another, like so:
$(‘p’).removeClass(‘myclass’).addClass(‘yourclass’)
Here, the class myclass is removed from all the paragraphs, while yourclass
is added. To replace all existing classes with another class, use .attr(‘class’,'new-class’) instead.

.toggleClass()
If the class is present, .toggleClass() removes it from each element in the set of matched elements; if it is not present, it adds the class.
.toggleClass(class)
Parameters : class: A class name to be toggled in the class attribute of each element in the matched set
Return Value
The jQuery object, for chaining purposes.
Description
This method takes one or more class names as its parameter. If an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added. For example, we can apply .toggleClass() to a simple <div>:
<div class=”tumble”>Some text.</div>
The first time we apply $(‘div.tumble’).toggleClass(‘bounce’), we get
the following:
<div class=”tumble bounce”>Some text.</div>
The second time we apply $(‘div.tumble’).toggleClass(‘bounce’), the <div> class is returned to the single tumble value:
<div class=”tumble”>Some text.</div>
Applying .toggleClass ( ‘bounce spin’ ) to the same <div> alternates between <div class = “tumble bounce spin’> and <div class=”tumble’>.

 

Fetching data from remote server in Android

fetching data from remote server in Android
The following example will help you to learn on fetching data from remote server in android
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class httpsData extends Activity {
/** Called when the activity is first created. */
ImageView img;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//calling the DownloadDataFromServer function for fetching data from remote server.
String str = DownloadDataFromServer(“http://www.schogini.in/test/”);

//display the text via TextView
TextView tv1 = (TextView) findViewById(R.id.TextView1);
tv1.setText ( str );
}

private String DownloadDataFromServer ( String URL )
{
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection ( URL );
} catch ( IOException e1 ) {
// TODO Auto-generated catch block
e1.printStackTrace ();
return “”;
}

InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = “”;
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ( ( charRead = isr.read ( inputBuffer ) )>0 )
{
String readString = String.copyValueOf ( inputBuffer,  0,  charRead );
str += readString;
inputBuffer = new char [ BUFFER_SIZE ];
}
in.close();
} catch ( IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace ();
return “”;
}
return str;
}
//The function below is used to access remote url and read data from the remote file
private InputStream OpenHttpConnection ( String urlString )
throws IOException
{
InputStream in = null;
int response = -1;

URL url = new URL ( urlString );
URLConnection conn = url.openConnection ();

if  (  ! ( conn instanceof HttpURLConnection ) )
throw new IOException ( “Not an HTTP connection” );
// we can connect server via two methods: GET and POST, here connects server via GET method.
try {
HttpURLConnection httpConn = ( HttpURLConnection ) conn;
httpConn.setAllowUserInteraction ( false );
httpConn.setInstanceFollowRedirects ( true );
httpConn.setRequestMethod ( “GET” );
httpConn.connect ();
response = httpConn.getResponseCode ();
if ( response == HttpURLConnection.HTTP_OK ) {
in = httpConn.getInputStream ();
}
}
catch ( Exception ex )
{
throw new IOException (  ”Error connecting”  );
}
return in;
}

}
XML file should be like following:
<?xml version = “1.0″ encoding = “utf-8″ ?>
<manifest xmlns:android = “http://schemas.android.com/apk/res/android”
package = “com.schogini.httpsData”
android:versionCode = “1″
android:versionName = “1.0.0″  >
<uses-permission android:name = “android.permission.INTERNET” />
<application android:icon = “@drawable/ic_launcher”
android:label = “@string/app_name” >
<activity android:name = “.httpsData”
android:label = “@string/app_name” >
<intent-filter>
<action android:name = “android.intent.action.MAIN” />
<category android:name = “android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>
</manifest>

 

Following are examples of using CSS selectors in jQuery:

Element: T
All elements that have a tag name of T.
Example
1. $(‘div’): selects all elements with a tag name of div in the document
2. $(‘em’): selects all elements with a tag name of em in the document
Description
jQuery uses JavaScript’s getElementsByTagName() function for tag-name selectors.

ID: #myid
The unique element with an ID equal to myid.

Examples
1. $(‘#myid’): selects the unique element with id=’myid’, regardless of its
tag name
2. $(‘p#myid’): selects a single paragraph with an id of ‘myid’; in other words, the unique element <p id=’myid’>
Description
Each id value must be used only once within a document. If more than one element has been assigned the same id, queries that use that id will only select the first matched element in the DOM.
It might not be immediately clear why someone might want to specify a tag name associated with a particular id, since that id needs to be unique anyway. However, some situations in which parts of the DOM are user-generated may require a more specific expression to avoid false positives. Furthermore, when the same script is run on more than one page, it might be necessary to identify the id’s element, since the pages could be associating the same id with different elements. For example, Page A might have <h1 id=’title’> while Page B has <h2 id=’title’>.
For a plain id selector such as example 2 above, jQuery uses the JavaScript function getElementById(). If the script’s execution speed is paramount, the plain id selector should be used.

Class: .myclass
All elements that have a class of myclass.
Examples
1. $(‘.myclass’): selects all elements that have a class of myclass
2. $(‘p.myclass’): selects all paragraphs that have a class of myclass
3. $(‘.myclass.otherclass’): selects all elements that have a class of myclass and otherclass
Description
In terms of speed, example 2 is generally preferable to example 1 (if we can limit the query to a given tag name) because it first uses the native JavaScript function getElementsByTagName() to filter its search, and then looks for the class within the matched subset of DOM elements. Conversely, there is currently no native getElementsByClassName() for jQuery to use, so using a bare class name forces jQuery to match it against every element in the DOM. The difference in speed varies, however, with the complexity of the page and the number of DOM elements.

As always, remember that development time is typically the most valuable resource. Do not focus on optimization of selector speed unless it is clear that performance needs to be improved.
As a CSS selector, the multiple-class syntax of example 3 is supported by all modern web browsers, but not by Internet Explorer versions 6 and below, which makes the syntax especially handy for applying styles cross-browser through jQuery.
Descendant: E F
All elements matched by F that are descendants of an element matched by E.
Examples
1. $(‘#container p’): selects all elements matched by <p> that are descendants of an element that has an id of container
2. $(‘a img’): selects all elements matched by <img> that are descendants of an element matched by <a>
Description
A descendant of an element could be a child, grandchild, great-grandchild,
and so on, of that element. For example, in the following HTML, the <img>
element is a descendant of the <span>, <p>, <div id=”inner”>, and
<div id=”container”> elements:
<div id=”container”>
<div id=”inner”>
<p>
<span><img src=”example.jpg” alt=”" /></span>
</p>
</div>
</div>
Child: E > F
All elements matched by F that are children of an element matched by E.
Examples
1. $(‘li > ul’): selects all elements matched by <ul> that are children of an element matched by <li>
2. $(‘p > code’): selects all elements matched by <code> that are children of an element matched by <p>

Description
As a CSS selector, the child combinator is supported by all modern web browsers including Safari, Mozilla/Firefox, and Internet Explorer 7, but notably not by Internet Explorer versions 6 and below. Example 1 is a handy way to select all nested unordered lists (i.e. excepting the top level).
The child combinator can be thought of as a more specific form of the (single-space) descendant combinator in that it selects only first-level descendants. Therefore, in the following HTML, the <img> element is a child only of the <span> element.
<div id=”container”>
<div id=”inner”>
<p>
<span><img src=”example.jpg” alt=”" /></span>
</p>
</div>
</div>
Adjacent Sibling: E + F
All elements matched by F that immediately follow, and have the same parent as, an element matched by E.
Examples
1. $(‘ul + p’): selects all elements by <p> (paragraph) that immediately follow a sibling element matched by <ul> (unordered list)
2. $(‘strong + em’): selects all elements matched by <em> that immediately follow a sibling element matched by <strong>
Description
One important point to consider with both the + combinator and the ~ combinator (covered next) is that they only select siblings. Consider the following HTML:
<div id=”container”>
<ul>
<li></li>
<li></li>
</ul>
<p>
<img/>
</p>
</div>

$(‘ul + p’) selects <p> because it immediately follows <ul> and the two elements share the same parent, <div id=”container”>.
$(‘ul + img’) selects nothing because (among other reasons) <ul> is one level higher in the DOM tree than <img>.
$(‘li + img’) selects nothing because, even though <li> and <img> are on the same level in the DOM tree, they do not share the same parent.
General Sibling: E ~ F
All elements matched by F that follow, and have the same parent as, an element matched by E.
Examples
1. $(‘p ~ ul’): selects all elements matched by <ul> that follow a sibling element matched by <p>
2. $(‘code ~ code’): selects all elements matched by <code> that follow a sibling element matched by <code>
Description
One important point to consider with both the + combinator and the ~ combinator is that they only select siblings. The notable difference between the two is their respective reach. While the + combinator reaches only to the immediately following sibling element, the ~ combinator extends that reach to all following sibling elements.
Consider the following HTML:
<ul>
<li class=”first”></li>
<li class=”second”></li>
<li class=”third></li>
</ul>
<ul>
<li class=”fourth”></li>
<li class=”fifth”></li>
<li class=”sixth”></li>
</ul>
$(‘li.first ~ li’) selects <li class=”second”> and <li class=”third”>.
$(‘li.first + li’) selects <li class=”second”>.

Multiple Elements: E,F,G


Selects all elements matched by selector expressions E, F, or G.
Examples
1. $(‘code, em, strong’): selects all elements matched by <code> or <em> or <strong>
2. $(‘p strong, .myclass’): selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class of myclass
Description
This comma (,) combinator is an efficient way to select disparate elements.

Nth Child (:nth-child(n))
All elements that are the nth child of their parent.
Examples
1. $(‘li:nth-child(2)’): selects all elements matched by <li> that are the second child of their parent
2. $(‘p:nth-child(5)’): selects all elements matched by <p> that are the fifth child of their parent
Description
Because jQuery’s implementation of :nth-child(n) is strictly derived from the CSS specification, the value of n is 1-based, meaning that the counting starts at 1. For all other selector expressions, however, jQuery follows JavaScript’s “0-based” counting. Therefore, given a single <ul> containing two <li>s, $(‘li:nth-child(1)’) selects the first <li> while $(‘li:nth(1)’) selects the second.

First Child (:first-child)
All elements that are the first child of their parent:
Examples
1. $(‘li:first-child’): selects all elements matched by <li> that are the first child of their parent
2. $(strong:first-child’): selects all elements matched by <strong> that are the first child of their parent
Description
The :first-child pseudo-class is shorthand for :nth-child(1). For more information on :X-child pseudo-classes, see the discussion for :nth-child(n).
Last Child (:last-child)
All elements that are the last child of their parent.
Examples
1. $(‘li:last-child’): selects all elements matched by <li> that are the last child of their parent
2. $(‘code:last-child’): selects all elements matched by <code> that are the last child of their parent

 

In android you can select images from gallery and store it in your application as a part of your application image.

Create an xml file like following:

<LinearLayout xmlns:android = “http://schemas.android.com/apk/res/android”
xmlns:tools = “http://schemas.android.com/tools”
android:layout_width = “fill_parent”
android:layout_height = “fill_parent”>
<Button
android:id = “@+id/button1″
android:layout_width = “wrap_content”
android:layout_height = “wrap_content”
android:text = “Select Image from Gallery” />
</LinearLayout>

The mainActivity.java should be like following:

public class MainActivity extends Activity implements OnClickListener {

Button selectImage;
private static int SELECT_IMAGE = 1;
String imagePath;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.activity_main);

selectImage = (Button) findViewById(R.id.Button1);
selectImage.setOnClickListener(this);

}

public void onClick(View v) {

Intent intent = new Intent();
intent.setType(“image/*”);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, “Select Image”), SELECT_IMAGE);

}

public void onActivityResult(int requestCode, int resultCode, Intent data) {

if (resultCode == RESULT_OK) {

if (requestCode == SELECT_IMAGE) {
Uri selectedImageUri = data.getData();
imagePath = getPath(selectedImageUri);

Bitmap bmp = BitmapFactory.decodeFile(imagePath);
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + “/KepnerTregoe/”;
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, “myImage.png”); //name your image
try {
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Toast.makeText(getApplicationContext(), imagePath, Toast.LENGTH_SHORT).show();

}
}
}

public String getPath(Uri uri) {

String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}

 

Texture Drawing in XNA

Because XNA 2D programming is almost entirely a process of moving sprites around the screen, you might expect that loading and drawing bitmaps in an XNA program is fairly easy, and you would be correct.
The first project is called XnaLocalBitmap, so named because this bitmap will be stored as part of the program’s content. To add a new bitmap to the program’s content project, right-click the XnaLocalBitmapContent project name, select Add and then New Item, and then Bitmap File. You can create the bitmap right in Visual Studio.

To add this file as part of the program’s content, right-click the XnaLocalBitmapContent project in Visual Studio, select Add and Existing Item, and then navigate to the file. Once the file shows up, you can right-click it to display Properties, and you’ll see that it has an Asset Name of “Hello.”
The goal is to display this bitmap centered on the screen. Define a field in the Game1.cs file to store the Texture2D and another field for the position:

public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D helloTexture;
Vector2 position;

}
Both fields are set during the LoadContent method. Use the same generic method to load the Texture2D as you use to load a SpriteFont. The Texture2D class has properties named Width and Height that provide the dimensions of the bitmap in pixels.

protected override void LoadContent()
{
spriteBatch = new SpriteBatch ( GraphicsDevice );
helloTexture = this.Content.Load <Texture2D> (“Hello”);
Viewport viewport = this.GraphicsDevice.Viewport;
position = new Vector2 (  (viewport.Width – helloTexture.Width  ) / 2,
(viewport.Height – helloTexture.Height) / 2);
}

The SpriteBatch class has seven Draw methods to render bitmaps. This one is certainly the simplest:

protected override void Draw (GameTime gameTime)
{
GraphicsDevice.Clear ( Color.Navy );
spriteBatch.Begin ();
spriteBatch.Draw ( helloTexture, position, Color.White );
spriteBatch.End ();
base.Draw ( gameTime );
}

The final argument to Draw is a color that can be used to attenuate the existing colors in the bitmap. Use Color.White if you want the bitmap’s colors to display without any alteration.

 

Example of json parsing in android

Use the org.json parser classes that are baked into Android. The SDK comes with a very efficient set of classes for parsing JSON formatted strings in the org.json package. Simply create a new JSONObject or JSONArray from the formatted string data and you’ll be armed with a set of accessor methods to get primitive data or nested JSONObjects and JSONArrays from within.

This JSON parser is strict by default, meaning that it will halt with an Exception when encountering invalid JSON data or an invalid key. Accessor methods that prefix with ”get” will throw a JSONException if the requested value is not found. In some cases this behavior is not ideal, and for the there is a companion set of methods that are prefixed with ”opt”. These methods will return null instead of throwing an exception when a value for the requested key is not found. In addition, many of them have an overloaded version that also takes a fallback parameter to return instead of null.

{
“person”: {
“name”: “John”,
“age”: 30,
“children”: [
{
"name": "Ben"
"age": 5
},
{
"name": "Sarah"
"age": 7
},
{
"name": "Tom"
"age": 9
}
]
}
}

This defines a single object with three values: name (String), age (Integer), and children. The parameter entitled ”children” is an array of three more objects, each with their own name and age.

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical”>
<TextView
android:id=”@+id/line1″
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
/>
<TextView
android:id=”@+id/line2″
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
/>
<TextView
android:id=”@+id/line3″
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”T
/>
</LinearLayout>

public class MyActivity extends Activity {
private static final String JSON_STRING =
“{\”person\”:{\”name\”:\”Tom\”,\”age\”:30,\”children\”:
[{\"name\":\"Ben\",\"age\":5}," + "\"name\":\"Sarah\",\"age\":7},
{\"name\":\"Tom\",\"age\":9}]}}”;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView line1 = (TextView)findViewById(R.id.line1);
TextView line2 = (TextView)findViewById(R.id.line2);
TextView line3 = (TextView)findViewById(R.id.line3);
try {
JSONObject person = (new JSONObject(JSON_STRING)).getJSONObject(“person”);
String name = person.getString(“name”);
line1.setText(“This person’s name is ” + name);
line2.setText(name + ” is ” + person.getInt(“age”) + ” years old.”);
line3.setText(name + ” has ” + person.getJSONArray(“children”).length()
+ ” children.”);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
For this example, the JSON string has been hard-coded as a constant. When the
Activity is created, the string is turned into a JSONObject, at which point all its data can be accessed as key-value pairs, just as if it were stored in a Map or Dictionary. All the business logic is wrapped in a try/catch statement since we are using the strict methods for accessing data.

Functions like JSONObject.getString() and JSONObject.getInt() are used to reads
primitive data out and place it in the TextView; the getJSONArray() method pulls out the nested ”children” array. JSONArray has the same set of accessor methods as JSONObject to read data, but they take an index into the array as a parameter instead of the name of the key.

 

custom object overlays in android

The custom objects are basically 3D boxes in 4 different colors. They rotate and
so on depending on the view of the marker.
public class CustomObject1 extends ARObject {
public CustomObject1(String name, String patternName,
double markerWidth, double[] markerCenter) {
super(name, patternName, markerWidth, markerCenter);
float mat_ambientf[] = {0f, 1.0f, 0f, 1.0f};
float mat_flashf[] = {0f, 1.0f, 0f, 1.0f};
float mat_diffusef[] = {0f, 1.0f, 0f, 1.0f};
float mat_flash_shinyf[] = {50.0f};
mat_ambient = GraphicsUtil.makeFloatBuffer(mat_ambientf);
mat_flash = GraphicsUtil.makeFloatBuffer(mat_flashf);
mat_flash_shiny =
GraphicsUtil.makeFloatBuffer(mat_flash_shinyf);
mat_diffuse = GraphicsUtil.makeFloatBuffer(mat_diffusef);
}
public CustomObject1(String name, String patternName,
double markerWidth, double[] markerCenter, float[]
customColor) {
super(name, patternName, markerWidth, markerCenter);
float mat_flash_shinyf[] = {50.0f};
mat_ambient = GraphicsUtil.makeFloatBuffer(customColor);
mat_flash = GraphicsUtil.makeFloatBuffer(customColor);
mat_flash_shiny =
GraphicsUtil.makeFloatBuffer(mat_flash_shinyf);
mat_diffuse = GraphicsUtil.makeFloatBuffer(customColor);
}
private SimpleBox box = new SimpleBox();
private FloatBuffer mat_flash;
private FloatBuffer mat_ambient;
private FloatBuffer mat_flash_shiny;
private FloatBuffer mat_diffuse;
@Override
public final void draw(GL10 gl) {
super.draw(gl);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_SPECULAR,mat_flash);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_SHININESS, mat_flash_shiny);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_DIFFUSE, mat_diffuse);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT, mat_ambient);
gl.glColor4f(0, 1.0f, 0, 1.0f);
gl.glTranslatef( 0.0f, 0.0f, 12.5f );
box.draw(gl);
}
@Override
public void init(GL10 gl) {
}
}
The other three CustomObject classes are exactly the same as CustomObject1, except we change the colors a bit. Following are the changes you need to make for CustomObject2.
public CustomObject2(String name, String patternName,
double markerWidth, double[] markerCenter) {
super(name, patternName, markerWidth, markerCenter);
float mat_ambientf[] = {1.0f, 0f, 0f, 1.0f};
float mat_flashf[] = {1.0f, 0f, 0f, 1.0f};
float mat_diffusef[] = {1.0f, 0f, 0f, 1.0f};
float mat_flash_shinyf[] = {50.0f};
mat_ambient = GraphicsUtil.makeFloatBuffer(mat_ambientf);
mat_flash = GraphicsUtil.makeFloatBuffer(mat_flashf);
mat_flash_shiny =
GraphicsUtil.makeFloatBuffer(mat_flash_shinyf);
mat_diffuse = GraphicsUtil.makeFloatBuffer(mat_diffusef);
}
//Same code everywhere else, except the draw() method
@Override
public final void draw(GL10 gl) {
super.draw(gl);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_SPECULAR,mat_flash);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_SHININESS, mat_flash_shiny);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_DIFFUSE, mat_diffuse);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT, mat_ambient);
gl.glColor4f(1.0f, 0, 0, 1.0f);
gl.glTranslatef( 0.0f, 0.0f, 12.5f );
box.draw(gl);
}
public CustomObject3(String name, String patternName,
double markerWidth, double[] markerCenter) {
super(name, patternName, markerWidth, markerCenter);
float mat_ambientf[] = {0f, 0f, 1.0f, 1.0f};
float mat_flashf[] = {0f, 0f, 1.0f, 1.0f};
float mat_diffusef[] = {0f, 0f, 1.0f, 1.0f};
float mat_flash_shinyf[] = {50.0f};
mat_ambient = GraphicsUtil.makeFloatBuffer(mat_ambientf);
mat_flash = GraphicsUtil.makeFloatBuffer(mat_flashf);
mat_flash_shiny = GraphicsUtil.makeFloatBuffer(mat_flash_shinyf);
mat_diffuse = GraphicsUtil.makeFloatBuffer(mat_diffusef);
}
//Same code everywhere else, except the draw() method
@Override
public final void draw(GL10 gl) {
super.draw(gl);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK,
GL10.GL_SPECULAR,mat_flash);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_SHININESS, mat_flash_shiny);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_DIFFUSE, mat_diffuse);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT, mat_ambient);
gl.glColor4f(0f, 0, 1.0, 1.0f);
gl.glTranslatef( 0.0f, 0.0f, 12.5f );
box.draw(gl);
}
And finally, the changes for CustomObject4 follow:
public CustomObject4(String name, String patternName,
double markerWidth, double[] markerCenter) {
super(name, patternName, markerWidth, markerCenter);
float mat_ambientf[] = {1.0f, 0f, 1.0f, 1.0f};
float mat_flashf[] = {1.0f, 0f, 1.0f, 1.0f};
float mat_diffusef[] = {1.0f, 0f, 1.0f, 1.0f};
float mat_flash_shinyf[] = {50.0f};
mat_ambient = GraphicsUtil.makeFloatBuffer(mat_ambientf);
mat_flash = GraphicsUtil.makeFloatBuffer(mat_flashf);
mat_flash_shiny = GraphicsUtil.makeFloatBuffer(mat_flash_shinyf);
mat_diffuse = GraphicsUtil.makeFloatBuffer(mat_diffusef);
}
//Same code everywhere else, except the draw() method
@Override
public final void draw(GL10 gl) {
super.draw(gl);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_SPECULAR,mat_flash);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_SHININESS, mat_flash_shiny);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_DIFFUSE, mat_diffuse);
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT, mat_ambient);
gl.glColor4f(1.0f, 0, 1.0, 1.0f);
gl.glTranslatef( 0.0f, 0.0f, 12.5f );
box.draw(gl);
}
Now we have only CustomRenderer.java to deal with. This class allows us to do any non-AR stuff as well as set up the OpenGL environment.
public class CustomRenderer implements OpenGLRenderer {
private float[] ambientlight1 = {.3f, .3f, .3f, 1f};
private float[] diffuselight1 = {.7f, .7f, .7f, 1f};
private float[] specularlight1 = {0.6f, 0.6f, 0.6f, 1f};
private float[] lightposition1 = {20.0f,-40.0f,100.0f,1f};
private FloatBuffer lightPositionBuffer1 =
GraphicsUtil.makeFloatBuffer(lightposition1);
private FloatBuffer specularLightBuffer1 =
GraphicsUtil.makeFloatBuffer(specularlight1);
private FloatBuffer diffuseLightBuffer1 =
GraphicsUtil.makeFloatBuffer(diffuselight1);
private FloatBuffer ambientLightBuffer1 =
GraphicsUtil.makeFloatBuffer(ambientlight1);
public final void draw(GL10 gl) {
}
public final void setupEnv(GL10 gl) {
gl.glEnable(GL10.GL_LIGHTING);
gl.glLightfv(GL10.GL_LIGHT1, GL10.GL_AMBIENT,
ambientLightBuffer1);
gl.glLightfv(GL10.GL_LIGHT1, GL10.GL_DIFFUSE,
diffuseLightBuffer1);
gl.glLightfv(GL10.GL_LIGHT1, GL10.GL_SPECULAR,
specularLightBuffer1);
gl.glLightfv(GL10.GL_LIGHT1, GL10.GL_POSITION,
lightPositionBuffer1);
gl.glEnable(GL10.GL_LIGHT1);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
initGL(gl);
}
public final void initGL(GL10 gl) {
gl.glDisable(GL10.GL_COLOR_MATERIAL);
gl.glEnable(GL10.GL_CULL_FACE);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glDisable(GL10.GL_COLOR_MATERIAL);
gl.glEnable(GL10.GL_LIGHTING);
gl.glEnable(GL10.GL_CULL_FACE);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_NORMALIZE);
}
}
In the variable declarations, we specify the different types of lighting and create FloatBuffers from them. The setupEnv() is called before we display any of the boxes. It sets up the lighting and other OpenGL-specific stuff. The initGL() method is called once when the Surface is created.
Finally, the AndroidManifest.xml needs to be updated:
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.paar.ch3marker”
android:versionCode = “1″
android:versionName = “1.0″ >
<uses-sdk android:minSdkVersion=”7″ />
<application
android:icon = “@drawable/ic_launcher”
android:label = “@string/app_name” >
<activity
android:label = “@string/app_name”
android:name = “.Activity”
android:clearTaskOnLaunch = “true”
android:screenOrientation = “landscape”
android:noHistory = “true”>
<intent-filter >
<action android:name = “android.intent.action.MAIN” />
<category android:name = “android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>
<uses-permission android:name = “android.permission.CAMERA”/>
<uses-permission android:name = “android.permission.WRITE_EXTERNAL_STORAGE”/>
<uses-feature android:name = “android.hardware.camera” />
<uses-feature android:name = “android.hardware.camera.autofocus” />
</manifest>

Marker identification script for android

Markers are visual cues used by AR apps to know where to put overlays. You select any easily identifiable image (like a black question mark on a white background). One copy of the image is saved in your app, while another is printed out and put somewhere in the real world (or painted if you have a very steady hand). Marker recognition is an ongoing part of research in the field of artificial intelligence.
We will be using an open source Android library called AndAR to help us with the marker recognition. The details of the AndAR project can be found at http://code.google.com/p/andar. The application will have four markers that it will recognize. For each of the markers, we will supply a .patt file that AndAR can use to recognize the markers. These files describe how the markers look in a way that AndAR can understand. You can also create and supply your own markers, if you don’t like the ones provided or are feeling bored and adventurous. There are a few limitations, though:
a. The marker must be square in shape.
b. The borders must contrast well.
c. The border must be a solid color.

The markers can be black and white or color.

public class Activity extends AndARActivity {
private ARObject someObject;
private ARToolkit artoolkit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CustomRenderer renderer = new CustomRenderer();
setNonARRenderer(renderer);
try {
artoolkit = getArtoolkit();
someObject = new CustomObject1
(“test”, “marker_at16.patt”, 80.0, new double[]{0,0});
artoolkit.registerARObject(someObject);
someObject = new CustomObject2
(“test”, “marker_peace16.patt”, 80.0, new
double[]{0,0});
artoolkit.registerARObject(someObject);
someObject = new CustomObject3
(“test”, “marker_rupee16.patt”, 80.0, new
double[]{0,0});
artoolkit.registerARObject(someObject);
someObject = new CustomObject4
(“test”, “marker_hand16.patt”, 80.0, new double[]{0,0});
artoolkit.registerARObject(someObject);
} catch (AndARException ex){
System.out.println(“”);
}
startPreview();
}
public void uncaughtException(Thread thread, Throwable ex) {
Log.e(“AndAR EXCEPTION”, ex.getMessage());
finish();
}
}
In the onCreate() method, we first get the savedInstanceState. After that, we create a reference to the CustomRenderer class, which we will create a few pages down the line. We then set the non-AR renderer. Now comes the main part of the class. We register all four of the markers with AndAR and their related objects. CustomObject1-4 are classes that define what is to be augmented over each marker. Finally, the uncaughtException() method is used to cleanly exit the app if a fatal exception happens.

Creating a Split Screen with XNA

To create a split screen, we need to two different viewports. We have only been using one up until now and we actually retrieved it in our camera’s Initialization method. We simply grabbed the GraphicsDevice.Viewport property to get our camera’s viewport.
Because we want to display two screens in one we need to define our two new viewports and then let the cameras (we will need two cameras) know about them so we can get the desired effect.
Because we want to display two screens in one we need to define our two new viewports and then let the cameras (we will need two cameras) know about them so we can get the desired effect. To start we will need to add the following private member fields to our Game1.cs code:

private Viewport defaultViewport;
private Viewport topViewport;
private Viewport bottomViewport;
private separatorViewport;
private bool twoPlayers = true;
private FirstPersonCamera camera2;
Then at the end of our LoadGraphicsContent method we will need to define those viewports
and create our cameras and pass the new values. We do this in the following code:
if (twoPlayers)
{
defaultViewport = graphics.GraphicsDevice.Viewport;
topViewport = defaultViewport;
bottomViewport = defaultViewport;
topViewport.Height = topViewport.Height / 2;
separatorViewport.Y = topViewport.Height – 1;
separatorViewport.Height = 3;
bottomViewport.Y = topViewport.Height + 1;
bottomViewport.Height = (bottomViewport.Height / 2) – 1;
camera.Viewport = topViewport;

camera2 = new FirstPersonCamera(this);
camera2.Viewport = bottomViewport;
camera2.Position = new Vector3(0.0f, 0.0f, -3.0f);
camera2.Orientation = new Vector3(0.0f, 0.0f, 1.0f);
camera2.PlayerIndex = PlayerIndex.Two;
Components.Add(camera2);
}
We discussed briefly that we would need more than one camera to pull this off. This is because we have our view and projection matrices associated with our camera class. It makes sense that we will have two cameras because the camera is showing what the player is seeing. Each player needs his or her own view into the game. Our initial camera is still set up in our game’s constructor but our second camera will get added here. Our first camera gets the default viewport associated with it. The first thing the preceding code is doing is checking to see if we are in a two-player game. For a real game, this should be determined by an options menu or something similar, but for now we have just initialized the value to true when we initialized the twoPlayer variable.

Inside of the two-player condition the first thing we do is set our default viewport to what we are currently using (the graphic device’s viewport). Then we set our top viewport to the same value. We also initialize our bottomViewport to our defaultViewport value. The final thing we do with our viewports is resize them to account for two players. We divide the height in two (we are making two horizontal viewports) on both. We then set our bottom viewport’s Y property to be one more than the height of our bottom. This effectively puts the bottom viewport right underneath our top viewport.
While still in the two-player condition we change our first camera’s viewport to use the top viewport. Then we set up our second camera by setting more properties. Not only do we set the viewport for this camera to the bottom viewport we have, but we also set a new camera position as well as the orientation of the camera. Finally, we set the player index. None of these properties is exposed from our camera object, so we need to open our Camera.cs file and make some changes to account for this. First, we need to add a new private member field to hold our player index. We just assumed it was player 1 before. We can set up our protected (so our FirstPersonCamera class can access it) index as an integer as follows:

protected int playerIndex = 0;

Now, we can actually modify our input code that controls our camera to use this index instead of the hard-coded value 0 for our game pads. In the camera’s Update method we can change any instance of input.GamePads[0] to input.GamePads[playerIndex]. We also need to do the same for the FirstPersonCamera object. We did not update the keyboard code and will not for the sake of time. However, to implement multiple users where both can use the keyboard we should create a mapping for each player and check accordingly.
In general, it is a good practice to have a keyboard mapping so that if gamers do not like the controls we have defined in our games then they have a way to change them so it works more logically for them. The same can be said about creating a mapping for the game pads but many games simply give a choice of a couple of layouts. Because the code does not implement a keyboard mapping, the only way for us to control the separate screens differently is by having two game pads hooked up to our PC or Xbox 360. After we have changed our camera to take the player index into consideration before reading values from our game pad, we can add the following properties to our code:
public PlayerIndex PlayerIndex
{
get { return ((PlayerIndex)playerIndex); }
set { playerIndex = (int)value; }
}
public Vector3 Position
{
get { return (cameraPosition); }
set { cameraPosition = value; }
}
public Vector3 Orientation
{
get { return (cameraReference); }
set { cameraReference = value; }
}
public Vector3 Target
{
get { return (cameraTarget); }
set { cameraTarget = value; }
}
public Viewport Viewport
{
get
{
if (viewport == null)
viewport = graphics.GraphicsDevice.Viewport;
return ((Viewport)viewport);
}
set
{
viewport = value;
InitializeCamera();
}
}
We are simply exposing the camera’s position, orientation (reference), and target variables. For the player index property we are casting it to a PlayerIndex enumeration type. The final property is the Viewport property. We first check to see if our viewport variable is null and if so we set it to the graphics device’s viewport. When we set our Viewport property, we also call our InitializeCamera method again so it can recalculate its view and projection matrices. We need to set up a private member field for our viewport. We will allow it to have a default null value so we can declare it as follows:
private Viewport? viewport;
Because we are utilizing the Viewport type we will need to add the following using statement to our code:
using Microsoft.Xna.Framework.Graphics;
The only thing left for us to do now is to actually update our game’s drawing code to draw our scene twice. Because we are going to have to draw our scene twice (once for each camera) we will need to refactor our Draw code into a DrawScene method and pass in a camera reference. Our new code for the new Draw method is as follows:
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Viewport = camera.Viewport;
DrawScene(gameTime, camera);
if (twoPlayers)
{
graphics.GraphicsDevice.Viewport = camera2.Viewport;
DrawScene(gameTime, camera2);
//now clear the thick horizontal line between the two screens
graphics.GraphicsDevice.Viewport = separatorViewport;
graphics.GraphicsDevice.Clear(Color.Black);
}
base.Draw(gameTime);
}
We took all of the code that was inside of this method and put it into a new method DrawScene(GameTime gameTime, Camera camera). The code we put into the DrawScene method did not change from how it looked when it resided inside of the Draw method.
The first thing we do with the preceding code is set our graphics device’s viewport to be what our camera’s viewport is. We then draw the scene passing in our camera. Then we check to see if we have two players; if so we set the viewport appropriately and finally draw the scene for that camera. We can run our application and see that it is using a split screen.

The Geocoder class provides a method to translate from an address into a latitude longitude coordinate ( geocoding ) and from a latitude longitude coordinate into an address ( reverse geo coding ). Reverse geo coding might produce only a partial address, such as city and postal code, depending on the level of detail available to the location provider.
This script uses reverse geo coding to get an address from the device’s location and display to the screen. The Geocoder instance needs to be initiated with a context and optionally with a locale if different from the system locale. Here, it is explicitly set to Locale.ENGLISH. Then the getFromLocation() method provides a list of addresses associated with the area around the provided location. Here the maximum number of returned results is set to one ( for instance, the most likely address ).
The Geocoder returns a List of android.location.Address objects.This translation to an address depends on a backend service that is not included in the core Android framework.The Google Maps API provides a client Geocoder service, for example. However,
the translation returns an empty list if no such service exists on the target device. The address as a list of strings is dumped line by line into a String for display on the screen.

public class MyLocation extends Activity {
LocationManager mLocationManager;
Location mLocation;
TextView tv;
@Override
public void onCreate ( Bundle savedInstanceState ) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.main );
tv = ( TextView ) findViewById( R.id.tv1 );
mLocationManager = ( LocationManager )
getSystemService ( Context.LOCATION_SERVICE );
Criteria criteria = new Criteria();
criteria.setAccuracy ( Criteria.ACCURACY_FINE );
criteria.setPowerRequirement ( Criteria.POWER_LOW );
String locationprovider =
mLocationManager.getBestProvider (criteria, true);
mLocation =
mLocationManager.getLastKnownLocation ( locationprovider );
List<Address> addresses;
try {
Geocoder mGC = new Geocoder ( this, Locale.ENGLISH );
addresses = mGC.getFromLocation ( mLocation.getLatitude (),
mLocation.getLongitude (), 1 );
if ( addresses != null ) {
Address currentAddr = addresses.get (0);
StringBuilder mSB = new StringBuilder (“Address:\n”);
for ( int i=0; i< currentAddr.getMaxAddressLineIndex();  i++ ) {
mSB.append ( currentAddr.getAddressLine ( i ) ).append (“\n”);
}
tv.setText ( mSB.toString() );
}
} catch( IOException e ) {
tv.setText ( e.getMessage() );
}
}
}

 

Page 2 of 4612345...102030...Last »