code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.anycut; import android.app.Dialog; import android.app.ListActivity; import android.content.ContentUris; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.provider.Contacts; import android.provider.Contacts.People; import android.provider.Contacts.Phones; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; /** * Presents the user with a list of types of shortucts that can be created. * When Any Cut is launched through the home screen this is the activity that comes up. */ public class CreateShortcutActivity extends ListActivity implements DialogInterface.OnClickListener, Dialog.OnCancelListener { private static final boolean ENABLE_ACTION_ICON_OVERLAYS = false; private static final int REQUEST_PHONE = 1; private static final int REQUEST_TEXT = 2; private static final int REQUEST_ACTIVITY = 3; private static final int REQUEST_CUSTOM = 4; private static final int LIST_ITEM_DIRECT_CALL = 0; private static final int LIST_ITEM_DIRECT_TEXT = 1; private static final int LIST_ITEM_ACTIVITY = 2; private static final int LIST_ITEM_CUSTOM = 3; private static final int DIALOG_SHORTCUT_EDITOR = 1; private Intent mEditorIntent; @Override public void onCreate(Bundle savedState) { super.onCreate(savedState); setListAdapter(ArrayAdapter.createFromResource(this, R.array.mainMenu, android.R.layout.simple_list_item_1)); } @Override protected void onListItemClick(ListView list, View view, int position, long id) { switch (position) { case LIST_ITEM_DIRECT_CALL: { Intent intent = new Intent(Intent.ACTION_PICK, Phones.CONTENT_URI); intent.putExtra(Contacts.Intents.UI.TITLE_EXTRA_KEY, getText(R.string.callShortcutActivityTitle)); startActivityForResult(intent, REQUEST_PHONE); break; } case LIST_ITEM_DIRECT_TEXT: { Intent intent = new Intent(Intent.ACTION_PICK, Phones.CONTENT_URI); intent.putExtra(Contacts.Intents.UI.TITLE_EXTRA_KEY, getText(R.string.textShortcutActivityTitle)); startActivityForResult(intent, REQUEST_TEXT); break; } case LIST_ITEM_ACTIVITY: { Intent intent = new Intent(); intent.setClass(this, ActivityPickerActivity.class); startActivityForResult(intent, REQUEST_ACTIVITY); break; } case LIST_ITEM_CUSTOM: { Intent intent = new Intent(); intent.setClass(this, CustomShortcutCreatorActivity.class); startActivityForResult(intent, REQUEST_CUSTOM); break; } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent result) { if (resultCode != RESULT_OK) { return; } switch (requestCode) { case REQUEST_PHONE: { startShortcutEditor(generatePhoneShortcut(result, R.drawable.sym_action_call, "tel", Intent.ACTION_CALL)); break; } case REQUEST_TEXT: { startShortcutEditor(generatePhoneShortcut(result, R.drawable.sym_action_sms, "smsto", Intent.ACTION_SENDTO)); break; } case REQUEST_ACTIVITY: case REQUEST_CUSTOM: { startShortcutEditor(result); break; } } } @Override protected Dialog onCreateDialog(int dialogId) { switch (dialogId) { case DIALOG_SHORTCUT_EDITOR: { return new ShortcutEditorDialog(this, this, this); } } return super.onCreateDialog(dialogId); } @Override protected void onPrepareDialog(int dialogId, Dialog dialog) { switch (dialogId) { case DIALOG_SHORTCUT_EDITOR: { if (mEditorIntent != null) { // If the editor intent hasn't been set already set it ShortcutEditorDialog editor = (ShortcutEditorDialog) dialog; editor.setIntent(mEditorIntent); mEditorIntent = null; } } } } /** * Starts the shortcut editor * * @param shortcutIntent The shortcut intent to edit */ private void startShortcutEditor(Intent shortcutIntent) { mEditorIntent = shortcutIntent; showDialog(DIALOG_SHORTCUT_EDITOR); } public void onCancel(DialogInterface dialog) { // Remove the dialog, it won't be used again removeDialog(DIALOG_SHORTCUT_EDITOR); } public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON1) { // OK button ShortcutEditorDialog editor = (ShortcutEditorDialog) dialog; Intent shortcut = editor.getIntent(); setResult(RESULT_OK, shortcut); finish(); } // Remove the dialog, it won't be used again removeDialog(DIALOG_SHORTCUT_EDITOR); } /** * Returns an Intent describing a direct text message shortcut. * * @param result The result from the phone number picker * @return an Intent describing a phone number shortcut */ private Intent generatePhoneShortcut(Intent result, int actionResId, String scheme, String action) { Uri phoneUri = result.getData(); long personId = 0; String name = null; String number = null; int type; Cursor cursor = getContentResolver().query(phoneUri, new String[] { Phones.PERSON_ID, Phones.DISPLAY_NAME, Phones.NUMBER, Phones.TYPE }, null, null, null); try { cursor.moveToFirst(); personId = cursor.getLong(0); name = cursor.getString(1); number = cursor.getString(2); type = cursor.getInt(3); } finally { if (cursor != null) { cursor.close(); } } Intent intent = new Intent(); Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, personId); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, generatePhoneNumberIcon(personUri, type, actionResId)); // Make the URI a direct tel: URI so that it will always continue to work phoneUri = Uri.fromParts(scheme, number, null); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(action, phoneUri)); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); return intent; } /** * Generates a phone number shortcut icon. Adds an overlay describing the type of the phone * number, and if there is a photo also adds the call action icon. * * @param personUri The person the phone number belongs to * @param type The type of the phone number * @param actionResId The ID for the action resource * @return The bitmap for the icon */ private Bitmap generatePhoneNumberIcon(Uri personUri, int type, int actionResId) { final Resources r = getResources(); boolean drawPhoneOverlay = true; Bitmap photo = People.loadContactPhoto(this, personUri, 0, null); if (photo == null) { // If there isn't a photo use the generic phone action icon instead Bitmap phoneIcon = getPhoneActionIcon(r, actionResId); if (phoneIcon != null) { photo = phoneIcon; drawPhoneOverlay = false; } else { return null; } } // Setup the drawing classes int iconSize = (int) r.getDimension(android.R.dimen.app_icon_size); Bitmap icon = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(icon); // Copy in the photo Paint photoPaint = new Paint(); photoPaint.setDither(true); photoPaint.setFilterBitmap(true); Rect src = new Rect(0,0, photo.getWidth(),photo.getHeight()); Rect dst = new Rect(0,0, iconSize,iconSize); canvas.drawBitmap(photo, src, dst, photoPaint); // Create an overlay for the phone number type String overlay = null; switch (type) { case Phones.TYPE_HOME: overlay = "H"; break; case Phones.TYPE_MOBILE: overlay = "M"; break; case Phones.TYPE_WORK: overlay = "W"; break; case Phones.TYPE_PAGER: overlay = "P"; break; case Phones.TYPE_OTHER: overlay = "O"; break; } if (overlay != null) { Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); textPaint.setTextSize(20.0f); textPaint.setTypeface(Typeface.DEFAULT_BOLD); textPaint.setColor(r.getColor(R.color.textColorIconOverlay)); textPaint.setShadowLayer(3f, 1, 1, r.getColor(R.color.textColorIconOverlayShadow)); canvas.drawText(overlay, 2, 16, textPaint); } // Draw the phone action icon as an overlay if (ENABLE_ACTION_ICON_OVERLAYS && drawPhoneOverlay) { Bitmap phoneIcon = getPhoneActionIcon(r, actionResId); if (phoneIcon != null) { src.set(0,0, phoneIcon.getWidth(),phoneIcon.getHeight()); int iconWidth = icon.getWidth(); dst.set(iconWidth - 20, -1, iconWidth, 19); canvas.drawBitmap(phoneIcon, src, dst, photoPaint); } } return icon; } /** * Returns the icon for the phone call action. * * @param r The resources to load the icon from * @param resId The resource ID to load * @return the icon for the phone call action */ private Bitmap getPhoneActionIcon(Resources r, int resId) { Drawable phoneIcon = r.getDrawable(resId); if (phoneIcon instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) phoneIcon; return bd.getBitmap(); } else { return null; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.anycut; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.content.Intent.ShortcutIconResource; import android.graphics.Bitmap; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.ImageView; /** * A dialog that can edit a shortcut intent. For now the icon is displayed, and only * the name may be edited. */ public class ShortcutEditorDialog extends AlertDialog implements OnClickListener, TextWatcher { static final String STATE_INTENT = "intent"; private boolean mCreated = false; private Intent mIntent; private ImageView mIconView; private EditText mNameView; private OnClickListener mOnClick; private OnCancelListener mOnCancel; public ShortcutEditorDialog(Context context, OnClickListener onClick, OnCancelListener onCancel) { super(context); mOnClick = onClick; mOnCancel = onCancel; // Setup the dialog View view = getLayoutInflater().inflate(R.layout.shortcut_editor, null, false); setTitle(R.string.shortcutEditorTitle); setButton(context.getText(android.R.string.ok), this); setButton2(context.getText(android.R.string.cancel), mOnClick); setOnCancelListener(mOnCancel); setCancelable(true); setView(view); mIconView = (ImageView) view.findViewById(R.id.shortcutIcon); mNameView = (EditText) view.findViewById(R.id.shortcutName); } public void onClick(DialogInterface dialog, int which) { if (which == BUTTON1) { String name = mNameView.getText().toString(); if (TextUtils.isEmpty(name)) { // Don't allow an empty name mNameView.setError(getContext().getText(R.string.errorEmptyName)); return; } mIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); } mOnClick.onClick(dialog, which); } @Override protected void onCreate(Bundle state) { super.onCreate(state); if (state != null) { mIntent = state.getParcelable(STATE_INTENT); } mCreated = true; // If an intent is set make sure to load it now that it's safe if (mIntent != null) { loadIntent(mIntent); } } @Override public Bundle onSaveInstanceState() { Bundle state = super.onSaveInstanceState(); state.putParcelable(STATE_INTENT, getIntent()); return state; } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing } public void onTextChanged(CharSequence s, int start, int before, int count) { // Do nothing } public void afterTextChanged(Editable text) { if (text.length() == 0) { mNameView.setError(getContext().getText(R.string.errorEmptyName)); } else { mNameView.setError(null); } } /** * Saves the current state of the editor into the intent and returns it. * * @return the intent for the shortcut being edited */ public Intent getIntent() { mIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, mNameView.getText().toString()); return mIntent; } /** * Reads the state of the shortcut from the intent and sets up the editor * * @param intent A shortcut intent to edit */ public void setIntent(Intent intent) { mIntent = intent; if (mCreated) { loadIntent(intent); } } /** * Loads the editor state from a shortcut intent. * * @param intent The shortcut intent to load the editor from */ private void loadIntent(Intent intent) { // Show the icon Bitmap iconBitmap = intent.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (iconBitmap != null) { mIconView.setImageBitmap(iconBitmap); } else { ShortcutIconResource iconRes = intent.getParcelableExtra( Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (iconRes != null) { int res = getContext().getResources().getIdentifier(iconRes.resourceName, null, iconRes.packageName); mIconView.setImageResource(res); } else { mIconView.setVisibility(View.INVISIBLE); } } // Fill in the name field for editing mNameView.addTextChangedListener(this); mNameView.setText(intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME)); // Ensure the intent has the proper flags intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; import com.android.heightmapprofiler.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; /** * Main entry point for the HeightMapTest application. */ public class MainMenu extends PreferenceActivity implements Preference.OnPreferenceClickListener { private static final int ACTIVITY_TEST = 0; private static final int RESULTS_DIALOG = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.preferences); Preference runTestButton = getPreferenceManager().findPreference("runtest"); if (runTestButton != null) { runTestButton.setOnPreferenceClickListener(this); } } /** Creates the test results dialog and fills in a dummy message. */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; if (id == RESULTS_DIALOG) { String dummy = "No results yet."; CharSequence sequence = dummy.subSequence(0, dummy.length() -1); dialog = new AlertDialog.Builder(this) .setTitle(R.string.dialog_title) .setPositiveButton(R.string.dialog_ok, null) .setMessage(sequence) .create(); } return dialog; } /** * Replaces the dummy message in the test results dialog with a string that * describes the actual test results. */ protected void onPrepareDialog (int id, Dialog dialog) { if (id == RESULTS_DIALOG) { // Extract final timing information from the profiler. final ProfileRecorder profiler = ProfileRecorder.sSingleton; final long frameVerts = profiler.getAverageVerts(); final long frameTime = profiler.getAverageTime(ProfileRecorder.PROFILE_FRAME); final long frameMin = profiler.getMinTime(ProfileRecorder.PROFILE_FRAME); final long frameMax = profiler.getMaxTime(ProfileRecorder.PROFILE_FRAME); final long drawTime = profiler.getAverageTime(ProfileRecorder.PROFILE_DRAW); final long drawMin = profiler.getMinTime(ProfileRecorder.PROFILE_DRAW); final long drawMax = profiler.getMaxTime(ProfileRecorder.PROFILE_DRAW); final long simTime = profiler.getAverageTime(ProfileRecorder.PROFILE_SIM); final long simMin = profiler.getMinTime(ProfileRecorder.PROFILE_SIM); final long simMax = profiler.getMaxTime(ProfileRecorder.PROFILE_SIM); final float fps = frameTime > 0 ? 1000.0f / frameTime : 0.0f; String result = "Frame: " + frameTime + "ms (" + fps + " fps)\n" + "\t\tMin: " + frameMin + "ms\t\tMax: " + frameMax + "\n" + "Draw: " + drawTime + "ms\n" + "\t\tMin: " + drawMin + "ms\t\tMax: " + drawMax + "\n" + "Sim: " + simTime + "ms\n" + "\t\tMin: " + simMin + "ms\t\tMax: " + simMax + "\n" + "\nVerts per frame: ~" + frameVerts + "\n"; CharSequence sequence = result.subSequence(0, result.length() -1); AlertDialog alertDialog = (AlertDialog)dialog; alertDialog.setMessage(sequence); } } /** Shows the results dialog when the test activity closes. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); showDialog(RESULTS_DIALOG); } public boolean onPreferenceClick(Preference preference) { Intent i = new Intent(this, HeightMapTest.class); startActivityForResult(i, ACTIVITY_TEST); return true; } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; import android.os.SystemClock; /** * Implements a simple runtime profiler. The profiler records start and stop * times for several different types of profiles and can then return min, max * and average execution times per type. Profile types are independent and may * be nested in calling code. This object is a singleton for convenience. */ public class ProfileRecorder { // A type for recording actual draw command time. public static final int PROFILE_DRAW = 0; // A type for recording the time it takes to run a single simulation step. public static final int PROFILE_SIM = 2; // A type for recording the total amount of time spent rendering a frame. public static final int PROFILE_FRAME = 3; private static final int PROFILE_COUNT = PROFILE_FRAME + 1; private ProfileRecord[] mProfiles; private int mFrameCount; private long mVertexCount; public static ProfileRecorder sSingleton = new ProfileRecorder(); public ProfileRecorder() { mProfiles = new ProfileRecord[PROFILE_COUNT]; for (int x = 0; x < PROFILE_COUNT; x++) { mProfiles[x] = new ProfileRecord(); } } /** Starts recording execution time for a specific profile type.*/ public final void start(int profileType) { if (profileType < PROFILE_COUNT) { mProfiles[profileType].start(SystemClock.uptimeMillis()); } } /** Stops recording time for this profile type. */ public final void stop(int profileType) { if (profileType < PROFILE_COUNT) { mProfiles[profileType].stop(SystemClock.uptimeMillis()); } } /** Indicates the end of the frame.*/ public final void endFrame() { mFrameCount++; } /* Flushes all recorded timings from the profiler. */ public final void resetAll() { for (int x = 0; x < PROFILE_COUNT; x++) { mProfiles[x].reset(); } mFrameCount = 0; mVertexCount = 0L; } /* Returns the average execution time, in milliseconds, for a given type. */ public long getAverageTime(int profileType) { long time = 0; if (profileType < PROFILE_COUNT) { time = mProfiles[profileType].getAverageTime(mFrameCount); } return time; } /* Returns the minimum execution time in milliseconds for a given type. */ public long getMinTime(int profileType) { long time = 0; if (profileType < PROFILE_COUNT) { time = mProfiles[profileType].getMinTime(); } return time; } /* Returns the maximum execution time in milliseconds for a given type. */ public long getMaxTime(int profileType) { long time = 0; if (profileType < PROFILE_COUNT) { time = mProfiles[profileType].getMaxTime(); } return time; } public long getTotalVerts() { return mVertexCount; } public long getAverageVerts() { return mVertexCount / mFrameCount; } public void addVerts(long vertCount) { mVertexCount += vertCount; } /** * A simple class for storing timing information about a single profile * type. */ protected class ProfileRecord { private long mStartTime; private long mTotalTime; private long mMinTime; private long mMaxTime; public void start(long time) { mStartTime = time; } public void stop(long time) { if (mStartTime > 0) { final long timeDelta = time - mStartTime; mTotalTime += timeDelta; if (mMinTime == 0 || timeDelta < mMinTime) { mMinTime = timeDelta; } if (mMaxTime == 0 || timeDelta > mMaxTime) { mMaxTime = timeDelta; } } } public long getAverageTime(int frameCount) { long time = frameCount > 0 ? mTotalTime / frameCount : 0; return time; } public long getMinTime() { return mMinTime; } public long getMaxTime() { return mMaxTime; } public void startNewProfilePeriod() { mTotalTime = 0; } public void reset() { mTotalTime = 0; mStartTime = 0; mMinTime = 0; mMaxTime = 0; } } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; import javax.microedition.khronos.opengles.GL10; import android.graphics.Bitmap; // This class manages a regular grid of LandTile objects. In this sample, // all the objects are the same mesh. In a real game, they would probably be // different to create a more interesting landscape. // This class also abstracts the concept of tiles away from the rest of the // code, so that the collision system (amongst others) can query the height of any // given point in the world. public class LandTileMap { private MeshLibrary mMeshLibrary = new MeshLibrary(); private LandTile[] mTiles; private LandTile mSkybox; private float mWorldWidth; private float mWorldHeight; private int mTilesAcross; private int mSkyboxTexture; private boolean mUseColors; private boolean mUseTexture; private NativeRenderer mNativeRenderer; public LandTileMap( int tilesAcross, int tilesDown, Bitmap heightmap, Bitmap lightmap, boolean useColors, boolean useTexture, boolean useLods, int maxSubdivisions, boolean useFixedPoint) { Grid[] lodMeshes; int lodLevels = 1; if (useLods) { lodLevels = LandTile.LOD_LEVELS; } lodMeshes = new Grid[lodLevels]; final int subdivisionSizeStep = maxSubdivisions / lodLevels; for (int x = 0; x < lodLevels; x++) { final int subdivisions = subdivisionSizeStep * (lodLevels - x); lodMeshes[x] = HeightMapMeshMaker.makeGrid( heightmap, lightmap, subdivisions, LandTile.TILE_SIZE, LandTile.TILE_SIZE, LandTile.TILE_HEIGHT_THRESHOLD, useFixedPoint); } mMeshLibrary.addMesh(lodMeshes); LandTile[] tiles = new LandTile[tilesAcross * tilesDown]; for (int x = 0; x < tilesAcross; x++) { for (int y = 0; y < tilesDown; y++) { LandTile tile = new LandTile(useLods, maxSubdivisions); tile.setLods(lodMeshes, heightmap); tiles[x * tilesAcross + y] = tile; tile.setPosition(x * LandTile.TILE_SIZE, 0.0f, y * LandTile.TILE_SIZE); } } mTiles = tiles; mWorldWidth = tilesAcross * LandTile.TILE_SIZE; mWorldHeight = tilesDown * LandTile.TILE_SIZE; mTilesAcross = tilesAcross; mUseColors = useColors; mUseTexture = useTexture; } public void setLandTextures( int landTextures[] ) { for( LandTile landTile : mTiles ) { landTile.setLODTextures( landTextures ); } } public void setupSkybox(Bitmap heightmap, boolean useFixedPoint) { if (mSkybox == null) { mSkybox = new LandTile(mWorldWidth, 1024, mWorldHeight, 1, 16, 1000000.0f); mMeshLibrary.addMesh(mSkybox.generateLods(heightmap, null, useFixedPoint)); mSkybox.setPosition(0.0f, 0.0f, 0.0f); } } public float getHeight(float worldX, float worldZ) { float height = 0.0f; if (worldX > 0.0f && worldX < mWorldWidth && worldZ > 0.0f && worldZ < mWorldHeight) { int tileX = (int)(worldX / LandTile.TILE_SIZE); int tileY = (int)(worldZ / LandTile.TILE_SIZE); height = mTiles[tileX * mTilesAcross + tileY].getHeight(worldX, worldZ); } return height; } public void setTextures(int[] landTextures, int skyboxTexture) { setLandTextures( landTextures ); mSkyboxTexture = skyboxTexture; if (mNativeRenderer != null) { final int count = mTiles.length; for (int x = 0; x < count; x++) { mNativeRenderer.registerTile(landTextures, mTiles[x], false); } if (mSkybox != null) { // Work around since registerTile() takes an array of textures int textures[] = new int[1]; textures[0] = skyboxTexture; mNativeRenderer.registerTile(textures, mSkybox, true); } } } public void draw(GL10 gl, Vector3 cameraPosition) { if (mNativeRenderer != null) { mNativeRenderer.draw(true, true); } else { if (mSkyboxTexture != 0) { gl.glBindTexture(GL10.GL_TEXTURE_2D, mSkyboxTexture); } Grid.beginDrawing(gl, mUseTexture, mUseColors); if (mSkybox != null) { gl.glDepthMask(false); gl.glDisable(GL10.GL_DEPTH_TEST); mSkybox.draw(gl, cameraPosition); gl.glDepthMask(true); gl.glEnable(GL10.GL_DEPTH_TEST); } final int count = mTiles.length; for (int x = 0; x < count; x++) { mTiles[x].draw(gl, cameraPosition); } Grid.endDrawing(gl); } } public void generateHardwareBuffers(GL10 gl) { mMeshLibrary.generateHardwareBuffers(gl); } public void setNativeRenderer(NativeRenderer nativeRenderer) { mNativeRenderer = nativeRenderer; } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; import android.os.SystemClock; // Very simple game runtime. Implements basic movement and collision detection with the landscape. public class Game implements Runnable { private Vector3 mCameraPosition = new Vector3(100.0f, 128.0f, 400.0f); private Vector3 mTargetPosition = new Vector3(350.0f, 128.0f, 650.0f); private Vector3 mWorkVector = new Vector3(); private float mCameraXZAngle; private float mCameraYAngle; private float mCameraLookAtDistance = (float)Math.sqrt(mTargetPosition.distance2(mCameraPosition)); private boolean mCameraDirty = true; private boolean mRunning = true; private boolean mPaused = false; private Object mPauseLock = new Object(); private LandTileMap mTileMap; private final static float CAMERA_ORBIT_SPEED = 0.3f; private final static float CAMERA_MOVE_SPEED = 5.0f; private final static float VIEWER_HEIGHT = 15.0f; private SimpleGLRenderer mSimpleRenderer; public Game(SimpleGLRenderer renderer, LandTileMap tiles) { mSimpleRenderer = renderer; mTileMap = tiles; } public void run() { while (mRunning) { ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_SIM); long startTime = SystemClock.uptimeMillis(); if (mCameraDirty) { // snap the camera to the floor float height = mTileMap.getHeight(mCameraPosition.x, mCameraPosition.z); mCameraPosition.y = height + VIEWER_HEIGHT; updateCamera(); } long endTime = SystemClock.uptimeMillis(); ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_SIM); if (endTime - startTime < 16) { // we're running too fast! sleep for a bit to let the render thread do some work. try { Thread.sleep(16 - (endTime - startTime)); } catch (InterruptedException e) { // Interruptions are not a big deal here. } } synchronized(mPauseLock) { if (mPaused) { while (mPaused) { try { mPauseLock.wait(); } catch (InterruptedException e) { // OK if this is interrupted. } } } } } } synchronized private void updateCamera() { mWorkVector.set((float)Math.cos(mCameraXZAngle), (float)Math.sin(mCameraYAngle), (float)Math.sin(mCameraXZAngle)); mWorkVector.multiply(mCameraLookAtDistance); mWorkVector.add(mCameraPosition); mTargetPosition.set(mWorkVector); mSimpleRenderer.setCameraPosition(mCameraPosition.x, mCameraPosition.y, mCameraPosition.z); mSimpleRenderer.setCameraLookAtPosition(mTargetPosition.x, mTargetPosition.y, mTargetPosition.z); mCameraDirty = false; } synchronized public void rotate(float x, float y) { if (x != 0.0f) { mCameraXZAngle += x * CAMERA_ORBIT_SPEED; mCameraDirty = true; } if (y != 0.0f) { mCameraYAngle += y * CAMERA_ORBIT_SPEED; mCameraDirty = true; } } synchronized public void move(float amount) { mWorkVector.set(mTargetPosition); mWorkVector.subtract(mCameraPosition); mWorkVector.normalize(); mWorkVector.multiply(amount * CAMERA_MOVE_SPEED); mCameraPosition.add(mWorkVector); mTargetPosition.add(mWorkVector); mCameraDirty = true; } public void pause() { synchronized(mPauseLock) { mPaused = true; } } public void resume() { synchronized(mPauseLock) { mPaused = false; mPauseLock.notifyAll(); } } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; import javax.microedition.khronos.opengles.GL10; import android.graphics.Bitmap; // This class defines a single land tile. It is built from // a height map image and may contain several meshes defining different levels // of detail. public class LandTile { public final static float TILE_SIZE = 512; private final static float HALF_TILE_SIZE = TILE_SIZE / 2; public final static float TILE_HEIGHT_THRESHOLD = 0.4f; private final static int MAX_SUBDIVISIONS = 24; private final static float LOD_STEP_SIZE = 300.0f; public final static int LOD_LEVELS = 4; private final static float MAX_LOD_DISTANCE = LOD_STEP_SIZE * (LOD_LEVELS - 1); private final static float MAX_LOD_DISTANCE2 = MAX_LOD_DISTANCE * MAX_LOD_DISTANCE; private Grid mLODMeshes[]; private int mLODTextures[]; private Vector3 mPosition = new Vector3(); private Vector3 mCenterPoint = new Vector3(); private Bitmap mHeightMap; private float mHeightMapScaleX; private float mHeightMapScaleY; private int mLodLevels = LOD_LEVELS; private int mMaxSubdivisions = MAX_SUBDIVISIONS; private float mTileSizeX = TILE_SIZE; private float mTileSizeZ = TILE_SIZE; private float mHalfTileSizeX = HALF_TILE_SIZE; private float mHalfTileSizeZ = HALF_TILE_SIZE; private float mTileHeightScale = TILE_HEIGHT_THRESHOLD; private float mMaxLodDistance = MAX_LOD_DISTANCE; private float mMaxLodDistance2 = MAX_LOD_DISTANCE2; public LandTile() { } public LandTile(boolean useLods, int maxSubdivisions ) { if (!useLods) { mLodLevels = 1; } mMaxSubdivisions = maxSubdivisions; } public LandTile(float sizeX, float sizeY, float sizeZ, int lodLevelCount, int maxSubdivisions, float maxLodDistance) { mTileSizeX = sizeX; mTileSizeZ = sizeZ; mTileHeightScale = (1.0f / 255.0f) * sizeY; mLodLevels = lodLevelCount; mMaxSubdivisions = maxSubdivisions; mMaxLodDistance = maxLodDistance; mMaxLodDistance2 = maxLodDistance * maxLodDistance; mHalfTileSizeX = sizeX / 2.0f; mHalfTileSizeZ = sizeZ / 2.0f; } public void setLods(Grid[] lodMeshes, Bitmap heightmap) { mHeightMap = heightmap; mHeightMapScaleX = heightmap.getWidth() / mTileSizeX; mHeightMapScaleY = heightmap.getHeight() / mTileSizeZ; mLODMeshes = lodMeshes; } public void setLODTextures( int LODTextures[] ) { mLODTextures = LODTextures; } public Grid[] generateLods(Bitmap heightmap, Bitmap lightmap, boolean useFixedPoint) { final int subdivisionSizeStep = mMaxSubdivisions / mLodLevels; mLODMeshes = new Grid[mLodLevels]; for (int x = 0; x < mLodLevels; x++) { final int subdivisions = subdivisionSizeStep * (mLodLevels - x); mLODMeshes[x] = HeightMapMeshMaker.makeGrid(heightmap, lightmap, subdivisions, mTileSizeX, mTileSizeZ, mTileHeightScale, useFixedPoint); } mHeightMap = heightmap; mHeightMapScaleX = heightmap.getWidth() / mTileSizeX; mHeightMapScaleY = heightmap.getHeight() / mTileSizeZ; return mLODMeshes; } public final void setPosition(float x, float y, float z) { mPosition.set(x, y, z); mCenterPoint.set(x + mHalfTileSizeX, y, z + mHalfTileSizeZ); } public final void setPosition(Vector3 position) { mPosition.set(position); mCenterPoint.set(position.x + mHalfTileSizeX, position.y, position.z + mHalfTileSizeZ); } public final Vector3 getPosition() { return mPosition; } public final Vector3 getCenterPoint() { return mCenterPoint; } public final Grid[] getLods() { return mLODMeshes; } public final float getMaxLodDistance() { return mMaxLodDistance; } public float getHeight(float worldSpaceX, float worldSpaceZ) { final float tileSpaceX = worldSpaceX - mPosition.x; final float tileSpaceY = worldSpaceZ - mPosition.z; final float imageSpaceX = tileSpaceX * mHeightMapScaleX; final float imageSpaceY = tileSpaceY * mHeightMapScaleY; float height = 0.0f; if (imageSpaceX >= 0.0f && imageSpaceX < mHeightMap.getWidth() && imageSpaceY >= 0.0f && imageSpaceY < mHeightMap.getHeight()) { height = HeightMapMeshMaker.getBilinearFilteredHeight(mHeightMap, imageSpaceX, imageSpaceY, mTileHeightScale); } return height; } public void draw(GL10 gl, Vector3 cameraPosition) { mCenterPoint.y = cameraPosition.y; // HACK! final float distanceFromCamera2 = cameraPosition.distance2(mCenterPoint); int lod = mLodLevels - 1; if (distanceFromCamera2 < mMaxLodDistance2) { final int bucket = (int)((distanceFromCamera2 / mMaxLodDistance2) * mLodLevels); lod = Math.min(bucket, mLodLevels - 1); } gl.glPushMatrix(); gl.glTranslatef(mPosition.x, mPosition.y, mPosition.z); // TODO - should add some code to keep state of current Texture and only set it if a new texture is needed - // may be taken care of natively by OpenGL lib. if( mLODTextures != null ) { // Check to see if we have different LODs to choose from (i.e. Text LOD feature is turned on). If not then // just select the default texture if( mLODTextures.length == 1 ) { gl.glBindTexture(GL10.GL_TEXTURE_2D, mLODTextures[0]); } // if the LOD feature is enabled, use lod value to select correct texture to use else { gl.glBindTexture(GL10.GL_TEXTURE_2D, mLODTextures[lod]); } } ProfileRecorder.sSingleton.addVerts(mLODMeshes[lod].getVertexCount()); mLODMeshes[lod].draw(gl, true, true); gl.glPopMatrix(); } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; /** * Simple 3D vector class. Handles basic vector math for 3D vectors. */ public final class Vector3 { public float x; public float y; public float z; public static final Vector3 ZERO = new Vector3(0, 0, 0); public Vector3() { } public Vector3(float xValue, float yValue, float zValue) { set(xValue, yValue, zValue); } public Vector3(Vector3 other) { set(other); } public final void add(Vector3 other) { x += other.x; y += other.y; z += other.z; } public final void add(float otherX, float otherY, float otherZ) { x += otherX; y += otherY; z += otherZ; } public final void subtract(Vector3 other) { x -= other.x; y -= other.y; z -= other.z; } public final void multiply(float magnitude) { x *= magnitude; y *= magnitude; z *= magnitude; } public final void multiply(Vector3 other) { x *= other.x; y *= other.y; z *= other.z; } public final void divide(float magnitude) { if (magnitude != 0.0f) { x /= magnitude; y /= magnitude; z /= magnitude; } } public final void set(Vector3 other) { x = other.x; y = other.y; z = other.z; } public final void set(float xValue, float yValue, float zValue) { x = xValue; y = yValue; z = zValue; } public final float dot(Vector3 other) { return (x * other.x) + (y * other.y) + (z * other.z); } public final float length() { return (float) Math.sqrt(length2()); } public final float length2() { return (x * x) + (y * y) + (z * z); } public final float distance2(Vector3 other) { float dx = x - other.x; float dy = y - other.y; float dz = z - other.z; return (dx * dx) + (dy * dy) + (dz * dz); } public final float normalize() { final float magnitude = length(); // TODO: I'm choosing safety over speed here. if (magnitude != 0.0f) { x /= magnitude; y /= magnitude; z /= magnitude; } return magnitude; } public final void zero() { set(0.0f, 0.0f, 0.0f); } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; import android.graphics.Bitmap; import android.graphics.Color; // This class generates vertex arrays based on grayscale images. // It defines 1.0 (white) as the tallest point and 0.0 (black) as the lowest point, // and builds a mesh that represents that topology. public class HeightMapMeshMaker { public static final Grid makeGrid(Bitmap drawable, Bitmap lightmap, int subdivisions, float width, float height, float scale, boolean fixedPoint) { Grid grid = null; final float subdivisionRange = subdivisions - 1; final float vertexSizeX = width / subdivisionRange; final float vertexSizeZ = height / subdivisionRange; if (drawable != null) { grid = new Grid(subdivisions, subdivisions, fixedPoint); final float heightMapScaleX = drawable.getWidth() / subdivisionRange; final float heightMapScaleY = drawable.getHeight() / subdivisionRange; final float lightMapScaleX = lightmap != null ? lightmap.getWidth() / subdivisions : 0.0f; final float lightMapScaleY = lightmap != null ? lightmap.getHeight() / subdivisions : 0.0f; final float[] vertexColor = { 1.0f, 1.0f, 1.0f, 1.0f }; for (int i = 0; i < subdivisions; i++) { final float u = (float)(i + 1) / subdivisions; for (int j = 0; j < subdivisions; j++) { final float v = (float)(j + 1) / subdivisions; final float vertexHeight = getBilinearFilteredHeight(drawable, (heightMapScaleX * i), (heightMapScaleY * j), scale); if (lightmap != null) { final int lightColor = lightmap.getPixel((int)(lightMapScaleX * i), (int)(lightMapScaleY * j)); final float colorScale = 1.0f / 255.0f; vertexColor[0] = colorScale * Color.red(lightColor); vertexColor[1] = colorScale * Color.green(lightColor); vertexColor[2] = colorScale * Color.blue(lightColor); vertexColor[3] = colorScale * Color.alpha(lightColor); } grid.set(i, j, i * vertexSizeX, vertexHeight, j * vertexSizeZ, u, v, vertexColor); } } } return grid; } // In order to get a smooth gradation between pixels from a low-resolution height map, // this function uses a bilinear filter to calculate a weighted average of four pixels // surrounding the requested point. public static final float getBilinearFilteredHeight(Bitmap drawable, float x, float y, float scale) { final int topLeftPixelX = clamp((int)Math.floor(x), 0, drawable.getWidth() - 1); final int topLeftPixelY = clamp((int)Math.floor(y), 0, drawable.getHeight() - 1); final int bottomRightPixelX = clamp((int)Math.ceil(x), 0, drawable.getWidth() - 1); final int bottomRightPixelY = clamp((int)Math.ceil(y), 0, drawable.getHeight() - 1); final float topLeftWeightX = x - topLeftPixelX; final float topLeftWeightY = y - topLeftPixelY; final float bottomRightWeightX = 1.0f - topLeftWeightX; final float bottomRightWeightY = 1.0f - topLeftWeightY; final int topLeft = drawable.getPixel(topLeftPixelX, topLeftPixelY); final int topRight = drawable.getPixel(bottomRightPixelX, topLeftPixelY); final int bottomLeft = drawable.getPixel(topLeftPixelX, bottomRightPixelY); final int bottomRight = drawable.getPixel(bottomRightPixelX, bottomRightPixelY); final float red1 = bottomRightWeightX * Color.red(topLeft) + topLeftWeightX * Color.red(topRight); final float red2 = bottomRightWeightX * Color.red(bottomLeft) + topLeftWeightX * Color.red(bottomRight); final float red = bottomRightWeightY * red1 + topLeftWeightY * red2; final float height = red * scale; return height; } private static final int clamp(int value, int min, int max) { return value < min ? min : (value > max ? max : value); } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; // This is a central repository for all vertex arrays. It handles // generation and invalidation of VBOs from each mesh. public class MeshLibrary { // This sample only has one type of mesh, Grid, but in a real game you might have // multiple types of objects managing vertex arrays (animated objects, objects loaded from // files, etc). This class could easily be modified to work with some basic Mesh class // in that case. private ArrayList<Grid[]> mMeshes = new ArrayList<Grid[]>(); public int addMesh(Grid[] lods) { int index = mMeshes.size(); mMeshes.add(lods); return index; } public Grid[] getMesh(int index) { Grid[] mesh = null; if (index >= 0 && index < mMeshes.size()) { mesh = mMeshes.get(index); } return mesh; } public void generateHardwareBuffers(GL10 gl) { final int count = mMeshes.size(); for (int x = 0; x < count; x++) { Grid[] lods = mMeshes.get(x); assert lods != null; for (int y = 0; y < lods.length; y++) { Grid lod = lods[y]; if (lod != null) { lod.invalidateHardwareBuffers(); lod.generateHardwareBuffers(gl); } } } } public void freeHardwareBuffers(GL10 gl) { final int count = mMeshes.size(); for (int x = 0; x < count; x++) { Grid[] lods = mMeshes.get(x); assert lods != null; for (int y = 0; y < lods.length; y++) { Grid lod = lods[y]; if (lod != null) { lod.releaseHardwareBuffers(gl); } } } } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; // This is a thin interface for a renderer implemented in C++ using the NDK. public class NativeRenderer { private Vector3 mCameraPosition = new Vector3(); private Vector3 mLookAtPosition = new Vector3(); private boolean mCameraDirty = false; static { System.loadLibrary("heightmapprofiler"); } public NativeRenderer() { nativeReset(); } public void setCamera(Vector3 camera, Vector3 lookat) { mCameraPosition = camera; mLookAtPosition = lookat; mCameraDirty = true; } public void registerTile(int textures[], LandTile tile, boolean isSkybox) { final Grid[] lods = tile.getLods(); final Vector3 position = tile.getPosition(); final Vector3 center = tile.getCenterPoint(); final int index = nativeAddTile(textures[0], lods.length, tile.getMaxLodDistance(), position.x, position.y, position.z, center.x, center.y, center.z); if (index >= 0) { for (int x = 0; x < lods.length; x++) { nativeAddLod(index, lods[x].getVertexBuffer(), lods[x].getTextureBuffer(), lods[x].getIndexBuffer(), lods[x].getColorBuffer(), lods[x].getIndexCount(), lods[x].getFixedPoint()); } if (isSkybox) { nativeSetSkybox(index); } for( int i = 1; i < textures.length; ++i ) { nativeAddTextureLod( index, i, textures[i]); } } } public void registerSkybox(int texture, Grid mesh, Vector3 position, Vector3 centerPoint) { } public void draw(boolean useTexture, boolean useColor) { nativeRender(mCameraPosition.x, mCameraPosition.y, mCameraPosition.z, mLookAtPosition.x, mLookAtPosition.y, mLookAtPosition.z, useTexture, useColor, mCameraDirty); mCameraDirty = false; } private static native void nativeReset(); private static native int nativeAddTile(int texture, int lodCount, float maxLodDistance, float x, float y, float z, float centerX, float centerY, float centerZ); private static native void nativeAddLod(int index, int vertexBuffer, int textureBuffer, int indexBuffer, int colorBuffer, int indexCount, boolean useFixedPoint); private static native void nativeSetSkybox(int index); private static native void nativeRender(float cameraX, float cameraY, float cameraZ, float lookAtX, float lookAtY, float lookAtZ, boolean useTexture, boolean useColor, boolean cameraDirty); private static native void nativeAddTextureLod(int tileIndex, int lod, int textureName); }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; import android.opengl.GLSurfaceView; import com.android.heightmapprofiler.SimpleGLRenderer; import com.android.heightmapprofiler.R; import android.app.Activity; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.KeyEvent; import android.view.MotionEvent; // The main entry point for the actual landscape rendering test. // This class pulls options from the preferences set in the MainMenu // activity and builds the landscape accordingly. public class HeightMapTest extends Activity { private GLSurfaceView mGLSurfaceView; private SimpleGLRenderer mSimpleRenderer; private Game mGame; private Thread mGameThread; private float mLastScreenX; private float mLastScreenY; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGLSurfaceView = new GLSurfaceView(this); mGLSurfaceView.setEGLConfigChooser(true); mSimpleRenderer = new SimpleGLRenderer(this); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); final boolean runGame = prefs.getBoolean("runsim", true); final boolean bigWorld = prefs.getBoolean("bigworld", true); final boolean skybox = prefs.getBoolean("skybox", true); final boolean texture = prefs.getBoolean("texture", true); final boolean vertexColors = prefs.getBoolean("colors", true); final boolean useTextureLods = prefs.getBoolean("lodTexture", true); final boolean textureMips = prefs.getBoolean("textureMips", true); final boolean useColorTextureLods = prefs.getBoolean("lodTextureColored", false ); final int maxTextureSize = Integer.parseInt(prefs.getString("maxTextureSize", "512")); final String textureFilter = prefs.getString("textureFiltering", "bilinear"); final boolean useLods = prefs.getBoolean("lod", true); final int complexity = Integer.parseInt(prefs.getString("complexity", "24")); final boolean useFixedPoint = prefs.getBoolean("fixed", false); final boolean useVbos = prefs.getBoolean("vbo", true); final boolean useNdk = prefs.getBoolean("ndk", false); BitmapDrawable heightMapDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.heightmap); Bitmap heightmap = heightMapDrawable.getBitmap(); Bitmap lightmap = null; if (vertexColors != false) { BitmapDrawable lightMapDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.lightmap); lightmap = lightMapDrawable.getBitmap(); } LandTileMap tileMap = null; if (bigWorld) { final int tilesX = 4; final int tilesY = 4; tileMap = new LandTileMap(tilesX, tilesY, heightmap, lightmap, vertexColors, texture, useLods, complexity, useFixedPoint); } else { tileMap = new LandTileMap(1, 1, heightmap, lightmap, vertexColors, texture, useLods, complexity, useFixedPoint); } if (skybox) { BitmapDrawable skyboxDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.skybox); Bitmap skyboxBitmap = skyboxDrawable.getBitmap(); tileMap.setupSkybox(skyboxBitmap, useFixedPoint); } if (useNdk) { NativeRenderer renderer = new NativeRenderer(); tileMap.setNativeRenderer(renderer); mSimpleRenderer.setNativeRenderer(renderer); } ProfileRecorder.sSingleton.resetAll(); mSimpleRenderer.setUseHardwareBuffers(useVbos); if (texture) { mSimpleRenderer.setTiles(tileMap, R.drawable.road_texture, R.drawable.skybox_texture); mSimpleRenderer.setUseTextureLods( useTextureLods, textureMips ); mSimpleRenderer.setColorTextureLods( useColorTextureLods ); mSimpleRenderer.setMaxTextureSize(maxTextureSize); if (textureFilter == "nearest") { mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_NEAREST_NEIGHBOR); } else if (textureFilter == "trilinear") { mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_TRILINEAR); } else { mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_BILINEAR); } } else { mSimpleRenderer.setTiles(tileMap, 0, 0); } mGLSurfaceView.setRenderer(mSimpleRenderer); setContentView(mGLSurfaceView); if (runGame) { mGame = new Game(mSimpleRenderer, tileMap); mGameThread = new Thread(mGame); mGameThread.start(); } } @Override protected void onPause() { super.onPause(); mGLSurfaceView.onPause(); if (mGame != null) { mGame.pause(); } } @Override protected void onResume() { super.onResume(); mGLSurfaceView.onResume(); if (mGame != null) { mGame.resume(); } } @Override public boolean onTrackballEvent(MotionEvent event) { if (mGame != null) { mGame.rotate(event.getRawX(), -event.getRawY()); } return true; } @Override public boolean onTouchEvent(MotionEvent event) { if (mGame != null) { if (event.getAction() == MotionEvent.ACTION_DOWN) { mGame.move(1.0f); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { float xDelta = event.getX() - mLastScreenX; float yDelta = event.getY() - mLastScreenY; mGame.move(1.0f); // Scale the values we got down to make control usable. // A real game would probably figure out scale factors based // on the size of the screen rather than hard-coded constants // like this. mGame.rotate(xDelta * 0.01f, -yDelta * 0.005f); } } mLastScreenX = event.getX(); mLastScreenY = event.getY(); try { Thread.sleep(16); } catch (InterruptedException e) { // TODO Auto-generated catch block } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mGame != null) { final float speed = 1.0f; switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: mGame.rotate(0.0f, -speed); return true; case KeyEvent.KEYCODE_DPAD_LEFT: mGame.rotate(-speed, 0.0f); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: mGame.rotate(speed, 0.0f); return true; case KeyEvent.KEYCODE_DPAD_UP: mGame.rotate(0.0f, speed); return true; } } return super.onKeyDown(keyCode, event); } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; import java.io.IOException; import java.io.InputStream; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.opengl.GLSurfaceView; import android.opengl.GLU; import android.opengl.GLUtils; import android.util.Log; /** * An OpenGL ES renderer based on the GLSurfaceView rendering framework. This * class is responsible for drawing a list of renderables to the screen every * frame. It also manages loading of textures and (when VBOs are used) the * allocation of vertex buffer objects. */ public class SimpleGLRenderer implements GLSurfaceView.Renderer { // Texture filtering modes. public final static int FILTER_NEAREST_NEIGHBOR = 0; public final static int FILTER_BILINEAR = 1; public final static int FILTER_TRILINEAR = 2; // Specifies the format our textures should be converted to upon load. private static BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options(); // Pre-allocated arrays to use at runtime so that allocation during the // test can be avoided. private int[] mTextureNameWorkspace; // A reference to the application context. private Context mContext; private LandTileMap mTiles; private int mTextureResource; private int mTextureResource2; private int mTextureId2; private Vector3 mCameraPosition = new Vector3(); private Vector3 mLookAtPosition = new Vector3(); private Object mCameraLock = new Object(); private boolean mCameraDirty; private NativeRenderer mNativeRenderer; // Determines the use of vertex buffer objects. private boolean mUseHardwareBuffers; private boolean mUseTextureLods = false; private boolean mUseHardwareMips = false; boolean mColorTextureLods = false; private int mTextureFilter = FILTER_BILINEAR; private int mMaxTextureSize = 0; public SimpleGLRenderer(Context context) { // Pre-allocate and store these objects so we can use them at runtime // without allocating memory mid-frame. mTextureNameWorkspace = new int[1]; // Set our bitmaps to 16-bit, 565 format. sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565; mContext = context; mUseHardwareBuffers = true; } public void setTiles(LandTileMap tiles, int textureResource, int textureResource2) { mTextureResource = textureResource; mTextureResource2 = textureResource2; mTiles = tiles; } /** Draws the landscape. */ public void onDrawFrame(GL10 gl) { ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_FRAME); ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_FRAME); if (mTiles != null) { // Clear the screen. Note that a real application probably would only clear the depth buffer // (or maybe not even that). if (mNativeRenderer == null) { gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); } // If the camera has moved since the last frame, rebuild our projection matrix. if (mCameraDirty){ synchronized (mCameraLock) { if (mNativeRenderer != null) { mNativeRenderer.setCamera(mCameraPosition, mLookAtPosition); } else { gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, mCameraPosition.x, mCameraPosition.y, mCameraPosition.z, mLookAtPosition.x, mLookAtPosition.y, mLookAtPosition.z, 0.0f, 1.0f, 0.0f); } mCameraDirty = false; } } ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_DRAW); // Draw the landscape. mTiles.draw(gl, mCameraPosition); ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_DRAW); } ProfileRecorder.sSingleton.endFrame(); } /* Called when the size of the window changes. */ public void onSurfaceChanged(GL10 gl, int width, int height) { gl.glViewport(0, 0, width, height); /* * Set our projection matrix. This doesn't have to be done each time we * draw, but usually a new projection needs to be set when the viewport * is resized. */ float ratio = (float)width / height; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); GLU.gluPerspective(gl, 60.0f, ratio, 2.0f, 3000.0f); mCameraDirty = true; } public void setCameraPosition(float x, float y, float z) { synchronized (mCameraLock) { mCameraPosition.set(x, y, z); mCameraDirty = true; } } public void setCameraLookAtPosition(float x, float y, float z) { synchronized (mCameraLock) { mLookAtPosition.set(x, y, z); mCameraDirty = true; } } public void setUseHardwareBuffers(boolean vbos) { mUseHardwareBuffers = vbos; } /** * Called to turn on Levels of Detail option for rendering textures * * @param mUseTextureLods */ public void setUseTextureLods(boolean useTextureLods, boolean useHardwareMips) { mUseTextureLods = useTextureLods; mUseHardwareMips = useHardwareMips; } /** * Turns on/off color the LOD bitmap textures based on their distance from view. * This feature is useful since it helps visualize the LOD being used while viewing the scene. * * @param colorTextureLods */ public void setColorTextureLods(boolean colorTextureLods) { this.mColorTextureLods = colorTextureLods; } public void setNativeRenderer(NativeRenderer render) { mNativeRenderer = render; } public void setMaxTextureSize(int maxTextureSize) { mMaxTextureSize = maxTextureSize; } public void setTextureFilter(int filter) { mTextureFilter = filter; } /** * Called whenever the surface is created. This happens at startup, and * may be called again at runtime if the device context is lost (the screen * goes to sleep, etc). This function must fill the contents of vram with * texture data and (when using VBOs) hardware vertex arrays. */ public void onSurfaceCreated(GL10 gl, EGLConfig config) { int[] textureNames = null; /* * Some one-time OpenGL initialization can be made here probably based * on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(0.5f, 0.5f, 0.5f, 1); gl.glDisable(GL10.GL_DITHER); gl.glDisable(GL10.GL_CULL_FACE); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); // set up some fog. gl.glEnable(GL10.GL_FOG); gl.glFogf(GL10.GL_FOG_MODE, GL10.GL_LINEAR); float fogColor[] = { 0.5f, 0.5f, 0.5f, 1.0f }; gl.glFogfv(GL10.GL_FOG_COLOR, fogColor, 0); gl.glFogf(GL10.GL_FOG_DENSITY, 0.15f); gl.glFogf(GL10.GL_FOG_START, 800.0f); gl.glFogf(GL10.GL_FOG_END, 2048.0f); gl.glHint(GL10.GL_FOG_HINT, GL10.GL_FASTEST); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // load textures and buffers here if (mUseHardwareBuffers && mTiles != null) { mTiles.generateHardwareBuffers(gl); } if (mTextureResource != 0) { textureNames = loadBitmap( mContext, gl, mTextureResource, mUseTextureLods, mUseHardwareMips ); } if (mTextureResource2 != 0) { mTextureId2 = loadBitmap(mContext, gl, mTextureResource2); } mTiles.setTextures(textureNames, mTextureId2); } /** * Loads a bitmap into OpenGL and sets up the common parameters for * 2D texture maps. */ protected int loadBitmap(Context context, GL10 gl, int resourceId) { int textureName = -1; InputStream is = context.getResources().openRawResource(resourceId); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions); } finally { try { is.close(); } catch (IOException e) { // Ignore. } } if (mMaxTextureSize > 0 && Math.max(bitmap.getWidth(), bitmap.getHeight()) != mMaxTextureSize) { // we're assuming all our textures are square. sue me. Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, mMaxTextureSize, mMaxTextureSize, false ); bitmap.recycle(); bitmap = tempBitmap; } textureName = loadBitmapIntoOpenGL(context, gl, bitmap, false); bitmap.recycle(); return textureName; } /** * Loads a bitmap into OpenGL and sets up the common parameters for * 2D texture maps. * * @param context * @param resourceId * @param numLevelsOfDetail number of detail textures to generate * * @return a array of OpenGL texture names corresponding to the different levels of detail textures */ protected int[] loadBitmap(Context context, GL10 gl, int resourceId, boolean generateMips, boolean useHardwareMips ) { InputStream is = context.getResources().openRawResource(resourceId); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions); } finally { try { is.close(); } catch (IOException e) { // Ignore. } } if (mMaxTextureSize > 0 && Math.max(bitmap.getWidth(), bitmap.getHeight()) != mMaxTextureSize) { // we're assuming all our textures are square. sue me. Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, mMaxTextureSize, mMaxTextureSize, false ); bitmap.recycle(); bitmap = tempBitmap; } final int minSide = Math.min(bitmap.getWidth(), bitmap.getHeight()); int numLevelsOfDetail = 1; if (generateMips) { for (int side = minSide / 2; side > 0; side /= 2) { numLevelsOfDetail++; } } int textureNames[]; if (generateMips && !useHardwareMips) { textureNames = new int[numLevelsOfDetail]; } else { textureNames = new int[1]; } textureNames[0] = loadBitmapIntoOpenGL(context, gl, bitmap, useHardwareMips); // Scale down base bitmap by powers of two to create lower resolution textures for( int i = 1; i < numLevelsOfDetail; ++i ) { int scale = (int)Math.pow(2, i); int dstWidth = bitmap.getWidth() / scale; int dstHeight = bitmap.getHeight() / scale; Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, dstWidth, dstHeight, false ); // Set each LOD level to a different color to help visualization if( mColorTextureLods ) { int color = 0; switch( (int)(i % 4) ) { case 1: color = Color.RED; break; case 2: color = Color.YELLOW; break; case 3: color = Color.BLUE; break; } tempBitmap.eraseColor( color ); } if (!useHardwareMips) { textureNames[i] = loadBitmapIntoOpenGL( context, gl, tempBitmap, false); } else { addHardwareMipmap(gl, textureNames[0], tempBitmap, i ); } tempBitmap.recycle(); } bitmap.recycle(); return textureNames; } protected void addHardwareMipmap(GL10 gl, int textureName, Bitmap bitmap, int level) { gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, level, bitmap, 0); } /** * Loads a bitmap into OpenGL and sets up the common parameters for * 2D texture maps. * * @return OpenGL texture entry id */ protected int loadBitmapIntoOpenGL(Context context, GL10 gl, Bitmap bitmap, boolean useMipmaps) { int textureName = -1; if (context != null && gl != null) { gl.glGenTextures(1, mTextureNameWorkspace, 0); textureName = mTextureNameWorkspace[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName); if (useMipmaps) { if (mTextureFilter == FILTER_TRILINEAR) { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_LINEAR); } else { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_NEAREST); } } else { if (mTextureFilter == FILTER_NEAREST_NEIGHBOR) { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); } else { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); } } if (mTextureFilter == FILTER_NEAREST_NEIGHBOR) { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST); } else { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); } gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); int error = gl.glGetError(); if (error != GL10.GL_NO_ERROR) { Log.e("SimpleGLRenderer", "Texture Load GLError: " + error); } } return textureName; } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; /** * A 2D rectangular mesh. Can be drawn textured or untextured. * This version is modified from the original Grid.java (found in * the SpriteText package in the APIDemos Android sample) to support hardware * vertex buffers. */ class Grid { private FloatBuffer mFloatVertexBuffer; private FloatBuffer mFloatTexCoordBuffer; private FloatBuffer mFloatColorBuffer; private IntBuffer mFixedVertexBuffer; private IntBuffer mFixedTexCoordBuffer; private IntBuffer mFixedColorBuffer; private CharBuffer mIndexBuffer; private Buffer mVertexBuffer; private Buffer mTexCoordBuffer; private Buffer mColorBuffer; private int mCoordinateSize; private int mCoordinateType; private int mW; private int mH; private int mIndexCount; private boolean mUseHardwareBuffers; private int mVertBufferIndex; private int mIndexBufferIndex; private int mTextureCoordBufferIndex; private int mColorBufferIndex; public Grid(int vertsAcross, int vertsDown, boolean useFixedPoint) { if (vertsAcross < 0 || vertsAcross >= 65536) { throw new IllegalArgumentException("vertsAcross"); } if (vertsDown < 0 || vertsDown >= 65536) { throw new IllegalArgumentException("vertsDown"); } if (vertsAcross * vertsDown >= 65536) { throw new IllegalArgumentException("vertsAcross * vertsDown >= 65536"); } mUseHardwareBuffers = false; mW = vertsAcross; mH = vertsDown; int size = vertsAcross * vertsDown; final int FLOAT_SIZE = 4; final int FIXED_SIZE = 4; final int CHAR_SIZE = 2; if (useFixedPoint) { mFixedVertexBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 3) .order(ByteOrder.nativeOrder()).asIntBuffer(); mFixedTexCoordBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 2) .order(ByteOrder.nativeOrder()).asIntBuffer(); mFixedColorBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 4) .order(ByteOrder.nativeOrder()).asIntBuffer(); mVertexBuffer = mFixedVertexBuffer; mTexCoordBuffer = mFixedTexCoordBuffer; mColorBuffer = mFixedColorBuffer; mCoordinateSize = FIXED_SIZE; mCoordinateType = GL10.GL_FIXED; } else { mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mFloatColorBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 4) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mVertexBuffer = mFloatVertexBuffer; mTexCoordBuffer = mFloatTexCoordBuffer; mColorBuffer = mFloatColorBuffer; mCoordinateSize = FLOAT_SIZE; mCoordinateType = GL10.GL_FLOAT; } int quadW = mW - 1; int quadH = mH - 1; int quadCount = quadW * quadH; int indexCount = quadCount * 6; mIndexCount = indexCount; mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount) .order(ByteOrder.nativeOrder()).asCharBuffer(); /* * Initialize triangle list mesh. * * [0]-----[ 1] ... * | / | * | / | * | / | * [w]-----[w+1] ... * | | * */ { int i = 0; for (int y = 0; y < quadH; y++) { for (int x = 0; x < quadW; x++) { char a = (char) (y * mW + x); char b = (char) (y * mW + x + 1); char c = (char) ((y + 1) * mW + x); char d = (char) ((y + 1) * mW + x + 1); mIndexBuffer.put(i++, a); mIndexBuffer.put(i++, b); mIndexBuffer.put(i++, c); mIndexBuffer.put(i++, b); mIndexBuffer.put(i++, c); mIndexBuffer.put(i++, d); } } } mVertBufferIndex = 0; } void set(int i, int j, float x, float y, float z, float u, float v, float[] color) { if (i < 0 || i >= mW) { throw new IllegalArgumentException("i"); } if (j < 0 || j >= mH) { throw new IllegalArgumentException("j"); } final int index = mW * j + i; final int posIndex = index * 3; final int texIndex = index * 2; final int colorIndex = index * 4; if (mCoordinateType == GL10.GL_FLOAT) { mFloatVertexBuffer.put(posIndex, x); mFloatVertexBuffer.put(posIndex + 1, y); mFloatVertexBuffer.put(posIndex + 2, z); mFloatTexCoordBuffer.put(texIndex, u); mFloatTexCoordBuffer.put(texIndex + 1, v); if (color != null) { mFloatColorBuffer.put(colorIndex, color[0]); mFloatColorBuffer.put(colorIndex + 1, color[1]); mFloatColorBuffer.put(colorIndex + 2, color[2]); mFloatColorBuffer.put(colorIndex + 3, color[3]); } } else { mFixedVertexBuffer.put(posIndex, (int)(x * (1 << 16))); mFixedVertexBuffer.put(posIndex + 1, (int)(y * (1 << 16))); mFixedVertexBuffer.put(posIndex + 2, (int)(z * (1 << 16))); mFixedTexCoordBuffer.put(texIndex, (int)(u * (1 << 16))); mFixedTexCoordBuffer.put(texIndex + 1, (int)(v * (1 << 16))); if (color != null) { mFixedColorBuffer.put(colorIndex, (int)(color[0] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 1, (int)(color[1] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 2, (int)(color[2] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 3, (int)(color[3] * (1 << 16))); } } } public static void beginDrawing(GL10 gl, boolean useTexture, boolean useColor) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); if (useTexture) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } if (useColor) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); } else { gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } } public void draw(GL10 gl, boolean useTexture, boolean useColor) { if (!mUseHardwareBuffers) { gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer); if (useTexture) { gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer); } if (useColor) { gl.glColorPointer(4, mCoordinateType, 0, mColorBuffer); } gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } else { GL11 gl11 = (GL11)gl; // draw using hardware buffers gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex); gl11.glVertexPointer(3, mCoordinateType, 0, 0); if (useTexture) { gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex); gl11.glTexCoordPointer(2, mCoordinateType, 0, 0); } if (useColor) { gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex); gl11.glColorPointer(4, mCoordinateType, 0, 0); } gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex); gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount, GL11.GL_UNSIGNED_SHORT, 0); gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); } } public static void endDrawing(GL10 gl) { gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public boolean usingHardwareBuffers() { return mUseHardwareBuffers; } /** * When the OpenGL ES device is lost, GL handles become invalidated. * In that case, we just want to "forget" the old handles (without * explicitly deleting them) and make new ones. */ public void invalidateHardwareBuffers() { mVertBufferIndex = 0; mIndexBufferIndex = 0; mTextureCoordBufferIndex = 0; mColorBufferIndex = 0; mUseHardwareBuffers = false; } /** * Deletes the hardware buffers allocated by this object (if any). */ public void releaseHardwareBuffers(GL10 gl) { if (mUseHardwareBuffers) { if (gl instanceof GL11) { GL11 gl11 = (GL11)gl; int[] buffer = new int[1]; buffer[0] = mVertBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mTextureCoordBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mColorBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mIndexBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); } invalidateHardwareBuffers(); } } /** * Allocates hardware buffers on the graphics card and fills them with * data if a buffer has not already been previously allocated. Note that * this function uses the GL_OES_vertex_buffer_object extension, which is * not guaranteed to be supported on every device. * @param gl A pointer to the OpenGL ES context. */ public void generateHardwareBuffers(GL10 gl) { if (!mUseHardwareBuffers) { if (gl instanceof GL11) { GL11 gl11 = (GL11)gl; int[] buffer = new int[1]; // Allocate and fill the vertex buffer. gl11.glGenBuffers(1, buffer, 0); mVertBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex); final int vertexSize = mVertexBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize, mVertexBuffer, GL11.GL_STATIC_DRAW); // Allocate and fill the texture coordinate buffer. gl11.glGenBuffers(1, buffer, 0); mTextureCoordBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex); final int texCoordSize = mTexCoordBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize, mTexCoordBuffer, GL11.GL_STATIC_DRAW); // Allocate and fill the color buffer. gl11.glGenBuffers(1, buffer, 0); mColorBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex); final int colorSize = mColorBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, colorSize, mColorBuffer, GL11.GL_STATIC_DRAW); // Unbind the array buffer. gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); // Allocate and fill the index buffer. gl11.glGenBuffers(1, buffer, 0); mIndexBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex); // A char is 2 bytes. final int indexSize = mIndexBuffer.capacity() * 2; gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize, mIndexBuffer, GL11.GL_STATIC_DRAW); // Unbind the element array buffer. gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); mUseHardwareBuffers = true; assert mVertBufferIndex != 0; assert mTextureCoordBufferIndex != 0; assert mIndexBufferIndex != 0; assert gl11.glGetError() == 0; } } } // These functions exposed to patch Grid info into native code. public final int getVertexBuffer() { return mVertBufferIndex; } public final int getTextureBuffer() { return mTextureCoordBufferIndex; } public final int getIndexBuffer() { return mIndexBufferIndex; } public final int getColorBuffer() { return mColorBufferIndex; } public final int getIndexCount() { return mIndexCount; } public boolean getFixedPoint() { return (mCoordinateType == GL10.GL_FIXED); } public long getVertexCount() { return mW * mH; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import org.apache.http.impl.client.DefaultHttpClient; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import java.security.MessageDigest; import android.util.Log; import android.util.Xml; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class DownloaderActivity extends Activity { /** * Checks if data has been downloaded. If so, returns true. If not, * starts an activity to download the data and returns false. If this * function returns false the caller should immediately return from its * onCreate method. The calling activity will later be restarted * (using a copy of its original intent) once the data download completes. * @param activity The calling activity. * @param customText A text string that is displayed in the downloader UI. * @param fileConfigUrl The URL of the download configuration URL. * @param configVersion The version of the configuration file. * @param dataPath The directory on the device where we want to store the * data. * @param userAgent The user agent string to use when fetching URLs. * @return true if the data has already been downloaded successfully, or * false if the data needs to be downloaded. */ public static boolean ensureDownloaded(Activity activity, String customText, String fileConfigUrl, String configVersion, String dataPath, String userAgent) { File dest = new File(dataPath); if (dest.exists()) { // Check version if (versionMatches(dest, configVersion)) { Log.i(LOG_TAG, "Versions match, no need to download."); return true; } } Intent intent = PreconditionActivityHelper.createPreconditionIntent( activity, DownloaderActivity.class); intent.putExtra(EXTRA_CUSTOM_TEXT, customText); intent.putExtra(EXTRA_FILE_CONFIG_URL, fileConfigUrl); intent.putExtra(EXTRA_CONFIG_VERSION, configVersion); intent.putExtra(EXTRA_DATA_PATH, dataPath); intent.putExtra(EXTRA_USER_AGENT, userAgent); PreconditionActivityHelper.startPreconditionActivityAndFinish( activity, intent); return false; } /** * Delete a directory and all its descendants. * @param directory The directory to delete * @return true if the directory was deleted successfully. */ public static boolean deleteData(String directory) { return deleteTree(new File(directory), true); } private static boolean deleteTree(File base, boolean deleteBase) { boolean result = true; if (base.isDirectory()) { for (File child : base.listFiles()) { result &= deleteTree(child, true); } } if (deleteBase) { result &= base.delete(); } return result; } private static boolean versionMatches(File dest, String expectedVersion) { Config config = getLocalConfig(dest, LOCAL_CONFIG_FILE); if (config != null) { return config.version.equals(expectedVersion); } return false; } private static Config getLocalConfig(File destPath, String configFilename) { File configPath = new File(destPath, configFilename); FileInputStream is; try { is = new FileInputStream(configPath); } catch (FileNotFoundException e) { return null; } try { Config config = ConfigHandler.parse(is); return config; } catch (Exception e) { Log.e(LOG_TAG, "Unable to read local config file", e); return null; } finally { quietClose(is); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.downloader); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.downloader_title); ((TextView) findViewById(R.id.customText)).setText( intent.getStringExtra(EXTRA_CUSTOM_TEXT)); mProgress = (TextView) findViewById(R.id.progress); mTimeRemaining = (TextView) findViewById(R.id.time_remaining); Button button = (Button) findViewById(R.id.cancel); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if (mDownloadThread != null) { mSuppressErrorMessages = true; mDownloadThread.interrupt(); } } }); startDownloadThread(); } private void startDownloadThread() { mSuppressErrorMessages = false; mProgress.setText(""); mTimeRemaining.setText(""); mDownloadThread = new Thread(new Downloader(), "Downloader"); mDownloadThread.setPriority(Thread.NORM_PRIORITY - 1); mDownloadThread.start(); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); mSuppressErrorMessages = true; mDownloadThread.interrupt(); try { mDownloadThread.join(); } catch (InterruptedException e) { // Don't care. } } private void onDownloadSucceeded() { Log.i(LOG_TAG, "Download succeeded"); PreconditionActivityHelper.startOriginalActivityAndFinish(this); } private void onDownloadFailed(String reason) { Log.e(LOG_TAG, "Download stopped: " + reason); String shortReason; int index = reason.indexOf('\n'); if (index >= 0) { shortReason = reason.substring(0, index); } else { shortReason = reason; } AlertDialog alert = new Builder(this).create(); alert.setTitle(R.string.download_activity_download_stopped); if (!mSuppressErrorMessages) { alert.setMessage(shortReason); } alert.setButton(getString(R.string.download_activity_retry), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startDownloadThread(); } }); alert.setButton2(getString(R.string.download_activity_quit), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); try { alert.show(); } catch (WindowManager.BadTokenException e) { // Happens when the Back button is used to exit the activity. // ignore. } } private void onReportProgress(int progress) { mProgress.setText(mPercentFormat.format(progress / 10000.0)); long now = SystemClock.elapsedRealtime(); if (mStartTime == 0) { mStartTime = now; } long delta = now - mStartTime; String timeRemaining = getString(R.string.download_activity_time_remaining_unknown); if ((delta > 3 * MS_PER_SECOND) && (progress > 100)) { long totalTime = 10000 * delta / progress; long timeLeft = Math.max(0L, totalTime - delta); if (timeLeft > MS_PER_DAY) { timeRemaining = Long.toString( (timeLeft + MS_PER_DAY - 1) / MS_PER_DAY) + " " + getString(R.string.download_activity_time_remaining_days); } else if (timeLeft > MS_PER_HOUR) { timeRemaining = Long.toString( (timeLeft + MS_PER_HOUR - 1) / MS_PER_HOUR) + " " + getString(R.string.download_activity_time_remaining_hours); } else if (timeLeft > MS_PER_MINUTE) { timeRemaining = Long.toString( (timeLeft + MS_PER_MINUTE - 1) / MS_PER_MINUTE) + " " + getString(R.string.download_activity_time_remaining_minutes); } else { timeRemaining = Long.toString( (timeLeft + MS_PER_SECOND - 1) / MS_PER_SECOND) + " " + getString(R.string.download_activity_time_remaining_seconds); } } mTimeRemaining.setText(timeRemaining); } private void onReportVerifying() { mProgress.setText(getString(R.string.download_activity_verifying)); mTimeRemaining.setText(""); } private static void quietClose(InputStream is) { try { if (is != null) { is.close(); } } catch (IOException e) { // Don't care. } } private static void quietClose(OutputStream os) { try { if (os != null) { os.close(); } } catch (IOException e) { // Don't care. } } private static class Config { long getSize() { long result = 0; for(File file : mFiles) { result += file.getSize(); } return result; } static class File { public File(String src, String dest, String md5, long size) { if (src != null) { this.mParts.add(new Part(src, md5, size)); } this.dest = dest; } static class Part { Part(String src, String md5, long size) { this.src = src; this.md5 = md5; this.size = size; } String src; String md5; long size; } ArrayList<Part> mParts = new ArrayList<Part>(); String dest; long getSize() { long result = 0; for(Part part : mParts) { if (part.size > 0) { result += part.size; } } return result; } } String version; ArrayList<File> mFiles = new ArrayList<File>(); } /** * <config version=""> * <file src="http:..." dest ="b.x" /> * <file dest="b.x"> * <part src="http:..." /> * ... * ... * </config> * */ private static class ConfigHandler extends DefaultHandler { public static Config parse(InputStream is) throws SAXException, UnsupportedEncodingException, IOException { ConfigHandler handler = new ConfigHandler(); Xml.parse(is, Xml.findEncodingByName("UTF-8"), handler); return handler.mConfig; } private ConfigHandler() { mConfig = new Config(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("config")) { mConfig.version = getRequiredString(attributes, "version"); } else if (localName.equals("file")) { String src = attributes.getValue("", "src"); String dest = getRequiredString(attributes, "dest"); String md5 = attributes.getValue("", "md5"); long size = getLong(attributes, "size", -1); mConfig.mFiles.add(new Config.File(src, dest, md5, size)); } else if (localName.equals("part")) { String src = getRequiredString(attributes, "src"); String md5 = attributes.getValue("", "md5"); long size = getLong(attributes, "size", -1); int length = mConfig.mFiles.size(); if (length > 0) { mConfig.mFiles.get(length-1).mParts.add( new Config.File.Part(src, md5, size)); } } } private static String getRequiredString(Attributes attributes, String localName) throws SAXException { String result = attributes.getValue("", localName); if (result == null) { throw new SAXException("Expected attribute " + localName); } return result; } private static long getLong(Attributes attributes, String localName, long defaultValue) { String value = attributes.getValue("", localName); if (value == null) { return defaultValue; } else { return Long.parseLong(value); } } public Config mConfig; } private class DownloaderException extends Exception { public DownloaderException(String reason) { super(reason); } } private class Downloader implements Runnable { public void run() { Intent intent = getIntent(); mFileConfigUrl = intent.getStringExtra(EXTRA_FILE_CONFIG_URL); mConfigVersion = intent.getStringExtra(EXTRA_CONFIG_VERSION); mDataPath = intent.getStringExtra(EXTRA_DATA_PATH); mUserAgent = intent.getStringExtra(EXTRA_USER_AGENT); mDataDir = new File(mDataPath); try { // Download files. mHttpClient = new DefaultHttpClient(); Config config = getConfig(); filter(config); persistantDownload(config); verify(config); cleanup(); reportSuccess(); } catch (Exception e) { reportFailure(e.toString() + "\n" + Log.getStackTraceString(e)); } } private void persistantDownload(Config config) throws ClientProtocolException, DownloaderException, IOException { while(true) { try { download(config); break; } catch(java.net.SocketException e) { if (mSuppressErrorMessages) { throw e; } } catch(java.net.SocketTimeoutException e) { if (mSuppressErrorMessages) { throw e; } } Log.i(LOG_TAG, "Network connectivity issue, retrying."); } } private void filter(Config config) throws IOException, DownloaderException { File filteredFile = new File(mDataDir, LOCAL_FILTERED_FILE); if (filteredFile.exists()) { return; } File localConfigFile = new File(mDataDir, LOCAL_CONFIG_FILE_TEMP); HashSet<String> keepSet = new HashSet<String>(); keepSet.add(localConfigFile.getCanonicalPath()); HashMap<String, Config.File> fileMap = new HashMap<String, Config.File>(); for(Config.File file : config.mFiles) { String canonicalPath = new File(mDataDir, file.dest).getCanonicalPath(); fileMap.put(canonicalPath, file); } recursiveFilter(mDataDir, fileMap, keepSet, false); touch(filteredFile); } private void touch(File file) throws FileNotFoundException { FileOutputStream os = new FileOutputStream(file); quietClose(os); } private boolean recursiveFilter(File base, HashMap<String, Config.File> fileMap, HashSet<String> keepSet, boolean filterBase) throws IOException, DownloaderException { boolean result = true; if (base.isDirectory()) { for (File child : base.listFiles()) { result &= recursiveFilter(child, fileMap, keepSet, true); } } if (filterBase) { if (base.isDirectory()) { if (base.listFiles().length == 0) { result &= base.delete(); } } else { if (!shouldKeepFile(base, fileMap, keepSet)) { result &= base.delete(); } } } return result; } private boolean shouldKeepFile(File file, HashMap<String, Config.File> fileMap, HashSet<String> keepSet) throws IOException, DownloaderException { String canonicalPath = file.getCanonicalPath(); if (keepSet.contains(canonicalPath)) { return true; } Config.File configFile = fileMap.get(canonicalPath); if (configFile == null) { return false; } return verifyFile(configFile, false); } private void reportSuccess() { mHandler.sendMessage( Message.obtain(mHandler, MSG_DOWNLOAD_SUCCEEDED)); } private void reportFailure(String reason) { mHandler.sendMessage( Message.obtain(mHandler, MSG_DOWNLOAD_FAILED, reason)); } private void reportProgress(int progress) { mHandler.sendMessage( Message.obtain(mHandler, MSG_REPORT_PROGRESS, progress, 0)); } private void reportVerifying() { mHandler.sendMessage( Message.obtain(mHandler, MSG_REPORT_VERIFYING)); } private Config getConfig() throws DownloaderException, ClientProtocolException, IOException, SAXException { Config config = null; if (mDataDir.exists()) { config = getLocalConfig(mDataDir, LOCAL_CONFIG_FILE_TEMP); if ((config == null) || !mConfigVersion.equals(config.version)) { if (config == null) { Log.i(LOG_TAG, "Couldn't find local config."); } else { Log.i(LOG_TAG, "Local version out of sync. Wanted " + mConfigVersion + " but have " + config.version); } config = null; } } else { Log.i(LOG_TAG, "Creating directory " + mDataPath); mDataDir.mkdirs(); mDataDir.mkdir(); if (!mDataDir.exists()) { throw new DownloaderException( "Could not create the directory " + mDataPath); } } if (config == null) { File localConfig = download(mFileConfigUrl, LOCAL_CONFIG_FILE_TEMP); InputStream is = new FileInputStream(localConfig); try { config = ConfigHandler.parse(is); } finally { quietClose(is); } if (! config.version.equals(mConfigVersion)) { throw new DownloaderException( "Configuration file version mismatch. Expected " + mConfigVersion + " received " + config.version); } } return config; } private void noisyDelete(File file) throws IOException { if (! file.delete() ) { throw new IOException("could not delete " + file); } } private void download(Config config) throws DownloaderException, ClientProtocolException, IOException { mDownloadedSize = 0; getSizes(config); Log.i(LOG_TAG, "Total bytes to download: " + mTotalExpectedSize); for(Config.File file : config.mFiles) { downloadFile(file); } } private void downloadFile(Config.File file) throws DownloaderException, FileNotFoundException, IOException, ClientProtocolException { boolean append = false; File dest = new File(mDataDir, file.dest); long bytesToSkip = 0; if (dest.exists() && dest.isFile()) { append = true; bytesToSkip = dest.length(); mDownloadedSize += bytesToSkip; } FileOutputStream os = null; long offsetOfCurrentPart = 0; try { for(Config.File.Part part : file.mParts) { // The part.size==0 check below allows us to download // zero-length files. if ((part.size > bytesToSkip) || (part.size == 0)) { MessageDigest digest = null; if (part.md5 != null) { digest = createDigest(); if (bytesToSkip > 0) { FileInputStream is = openInput(file.dest); try { is.skip(offsetOfCurrentPart); readIntoDigest(is, bytesToSkip, digest); } finally { quietClose(is); } } } if (os == null) { os = openOutput(file.dest, append); } downloadPart(part.src, os, bytesToSkip, part.size, digest); if (digest != null) { String hash = getHash(digest); if (!hash.equalsIgnoreCase(part.md5)) { Log.e(LOG_TAG, "web MD5 checksums don't match. " + part.src + "\nExpected " + part.md5 + "\n got " + hash); quietClose(os); dest.delete(); throw new DownloaderException( "Received bad data from web server"); } else { Log.i(LOG_TAG, "web MD5 checksum matches."); } } } bytesToSkip -= Math.min(bytesToSkip, part.size); offsetOfCurrentPart += part.size; } } finally { quietClose(os); } } private void cleanup() throws IOException { File filtered = new File(mDataDir, LOCAL_FILTERED_FILE); noisyDelete(filtered); File tempConfig = new File(mDataDir, LOCAL_CONFIG_FILE_TEMP); File realConfig = new File(mDataDir, LOCAL_CONFIG_FILE); tempConfig.renameTo(realConfig); } private void verify(Config config) throws DownloaderException, ClientProtocolException, IOException { Log.i(LOG_TAG, "Verifying..."); String failFiles = null; for(Config.File file : config.mFiles) { if (! verifyFile(file, true) ) { if (failFiles == null) { failFiles = file.dest; } else { failFiles += " " + file.dest; } } } if (failFiles != null) { throw new DownloaderException( "Possible bad SD-Card. MD5 sum incorrect for file(s) " + failFiles); } } private boolean verifyFile(Config.File file, boolean deleteInvalid) throws FileNotFoundException, DownloaderException, IOException { Log.i(LOG_TAG, "verifying " + file.dest); reportVerifying(); File dest = new File(mDataDir, file.dest); if (! dest.exists()) { Log.e(LOG_TAG, "File does not exist: " + dest.toString()); return false; } long fileSize = file.getSize(); long destLength = dest.length(); if (fileSize != destLength) { Log.e(LOG_TAG, "Length doesn't match. Expected " + fileSize + " got " + destLength); if (deleteInvalid) { dest.delete(); return false; } } FileInputStream is = new FileInputStream(dest); try { for(Config.File.Part part : file.mParts) { if (part.md5 == null) { continue; } MessageDigest digest = createDigest(); readIntoDigest(is, part.size, digest); String hash = getHash(digest); if (!hash.equalsIgnoreCase(part.md5)) { Log.e(LOG_TAG, "MD5 checksums don't match. " + part.src + " Expected " + part.md5 + " got " + hash); if (deleteInvalid) { quietClose(is); dest.delete(); } return false; } } } finally { quietClose(is); } return true; } private void readIntoDigest(FileInputStream is, long bytesToRead, MessageDigest digest) throws IOException { while(bytesToRead > 0) { int chunkSize = (int) Math.min(mFileIOBuffer.length, bytesToRead); int bytesRead = is.read(mFileIOBuffer, 0, chunkSize); if (bytesRead < 0) { break; } updateDigest(digest, bytesRead); bytesToRead -= bytesRead; } } private MessageDigest createDigest() throws DownloaderException { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new DownloaderException("Couldn't create MD5 digest"); } return digest; } private void updateDigest(MessageDigest digest, int bytesRead) { if (bytesRead == mFileIOBuffer.length) { digest.update(mFileIOBuffer); } else { // Work around an awkward API: Create a // new buffer with just the valid bytes byte[] temp = new byte[bytesRead]; System.arraycopy(mFileIOBuffer, 0, temp, 0, bytesRead); digest.update(temp); } } private String getHash(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for(byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString(); } /** * Ensure we have sizes for all the items. * @param config * @throws ClientProtocolException * @throws IOException * @throws DownloaderException */ private void getSizes(Config config) throws ClientProtocolException, IOException, DownloaderException { for (Config.File file : config.mFiles) { for(Config.File.Part part : file.mParts) { if (part.size < 0) { part.size = getSize(part.src); } } } mTotalExpectedSize = config.getSize(); } private long getSize(String url) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Head " + url); HttpHead httpGet = new HttpHead(url); HttpResponse response = mHttpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException("Unexpected Http status code " + response.getStatusLine().getStatusCode()); } Header[] clHeaders = response.getHeaders("Content-Length"); if (clHeaders.length > 0) { Header header = clHeaders[0]; return Long.parseLong(header.getValue()); } return -1; } private String normalizeUrl(String url) throws MalformedURLException { return (new URL(new URL(mFileConfigUrl), url)).toString(); } private InputStream get(String url, long startOffset, long expectedLength) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Get " + url); mHttpGet = new HttpGet(url); int expectedStatusCode = HttpStatus.SC_OK; if (startOffset > 0) { String range = "bytes=" + startOffset + "-"; if (expectedLength >= 0) { range += expectedLength-1; } Log.i(LOG_TAG, "requesting byte range " + range); mHttpGet.addHeader("Range", range); expectedStatusCode = HttpStatus.SC_PARTIAL_CONTENT; } HttpResponse response = mHttpClient.execute(mHttpGet); long bytesToSkip = 0; int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != expectedStatusCode) { if ((statusCode == HttpStatus.SC_OK) && (expectedStatusCode == HttpStatus.SC_PARTIAL_CONTENT)) { Log.i(LOG_TAG, "Byte range request ignored"); bytesToSkip = startOffset; } else { throw new IOException("Unexpected Http status code " + statusCode + " expected " + expectedStatusCode); } } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); if (bytesToSkip > 0) { is.skip(bytesToSkip); } return is; } private File download(String src, String dest) throws DownloaderException, ClientProtocolException, IOException { File destFile = new File(mDataDir, dest); FileOutputStream os = openOutput(dest, false); try { downloadPart(src, os, 0, -1, null); } finally { os.close(); } return destFile; } private void downloadPart(String src, FileOutputStream os, long startOffset, long expectedLength, MessageDigest digest) throws ClientProtocolException, IOException, DownloaderException { boolean lengthIsKnown = expectedLength >= 0; if (startOffset < 0) { throw new IllegalArgumentException("Negative startOffset:" + startOffset); } if (lengthIsKnown && (startOffset > expectedLength)) { throw new IllegalArgumentException( "startOffset > expectedLength" + startOffset + " " + expectedLength); } InputStream is = get(src, startOffset, expectedLength); try { long bytesRead = downloadStream(is, os, digest); if (lengthIsKnown) { long expectedBytesRead = expectedLength - startOffset; if (expectedBytesRead != bytesRead) { Log.e(LOG_TAG, "Bad file transfer from server: " + src + " Expected " + expectedBytesRead + " Received " + bytesRead); throw new DownloaderException( "Incorrect number of bytes received from server"); } } } finally { is.close(); mHttpGet = null; } } private FileOutputStream openOutput(String dest, boolean append) throws FileNotFoundException, DownloaderException { File destFile = new File(mDataDir, dest); File parent = destFile.getParentFile(); if (! parent.exists()) { parent.mkdirs(); } if (! parent.exists()) { throw new DownloaderException("Could not create directory " + parent.toString()); } FileOutputStream os = new FileOutputStream(destFile, append); return os; } private FileInputStream openInput(String src) throws FileNotFoundException, DownloaderException { File srcFile = new File(mDataDir, src); File parent = srcFile.getParentFile(); if (! parent.exists()) { parent.mkdirs(); } if (! parent.exists()) { throw new DownloaderException("Could not create directory " + parent.toString()); } return new FileInputStream(srcFile); } private long downloadStream(InputStream is, FileOutputStream os, MessageDigest digest) throws DownloaderException, IOException { long totalBytesRead = 0; while(true){ if (Thread.interrupted()) { Log.i(LOG_TAG, "downloader thread interrupted."); mHttpGet.abort(); throw new DownloaderException("Thread interrupted"); } int bytesRead = is.read(mFileIOBuffer); if (bytesRead < 0) { break; } if (digest != null) { updateDigest(digest, bytesRead); } totalBytesRead += bytesRead; os.write(mFileIOBuffer, 0, bytesRead); mDownloadedSize += bytesRead; int progress = (int) (Math.min(mTotalExpectedSize, mDownloadedSize * 10000 / Math.max(1, mTotalExpectedSize))); if (progress != mReportedProgress) { mReportedProgress = progress; reportProgress(progress); } } return totalBytesRead; } private DefaultHttpClient mHttpClient; private HttpGet mHttpGet; private String mFileConfigUrl; private String mConfigVersion; private String mDataPath; private File mDataDir; private String mUserAgent; private long mTotalExpectedSize; private long mDownloadedSize; private int mReportedProgress; private final static int CHUNK_SIZE = 32 * 1024; byte[] mFileIOBuffer = new byte[CHUNK_SIZE]; } private final static String LOG_TAG = "Downloader"; private TextView mProgress; private TextView mTimeRemaining; private final DecimalFormat mPercentFormat = new DecimalFormat("0.00 %"); private long mStartTime; private Thread mDownloadThread; private boolean mSuppressErrorMessages; private final static long MS_PER_SECOND = 1000; private final static long MS_PER_MINUTE = 60 * 1000; private final static long MS_PER_HOUR = 60 * 60 * 1000; private final static long MS_PER_DAY = 24 * 60 * 60 * 1000; private final static String LOCAL_CONFIG_FILE = ".downloadConfig"; private final static String LOCAL_CONFIG_FILE_TEMP = ".downloadConfig_temp"; private final static String LOCAL_FILTERED_FILE = ".downloadConfig_filtered"; private final static String EXTRA_CUSTOM_TEXT = "DownloaderActivity_custom_text"; private final static String EXTRA_FILE_CONFIG_URL = "DownloaderActivity_config_url"; private final static String EXTRA_CONFIG_VERSION = "DownloaderActivity_config_version"; private final static String EXTRA_DATA_PATH = "DownloaderActivity_data_path"; private final static String EXTRA_USER_AGENT = "DownloaderActivity_user_agent"; private final static int MSG_DOWNLOAD_SUCCEEDED = 0; private final static int MSG_DOWNLOAD_FAILED = 1; private final static int MSG_REPORT_PROGRESS = 2; private final static int MSG_REPORT_VERIFYING = 3; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_DOWNLOAD_SUCCEEDED: onDownloadSucceeded(); break; case MSG_DOWNLOAD_FAILED: onDownloadFailed((String) msg.obj); break; case MSG_REPORT_PROGRESS: onReportProgress(msg.arg1); break; case MSG_REPORT_VERIFYING: onReportVerifying(); break; default: throw new IllegalArgumentException("Unknown message id " + msg.what); } } }; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class DownloaderTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (! DownloaderActivity.ensureDownloaded(this, getString(R.string.app_name), FILE_CONFIG_URL, CONFIG_VERSION, DATA_PATH, USER_AGENT)) { return; } setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = true; int id = item.getItemId(); if (id == R.id.menu_main_download_again) { downloadAgain(); } else { handled = false; } if (!handled) { handled = super.onOptionsItemSelected(item); } return handled; } private void downloadAgain() { DownloaderActivity.deleteData(DATA_PATH); startActivity(getIntent()); finish(); } /** * Fill this in with your own web server. */ private final static String FILE_CONFIG_URL = "http://example.com/download.config"; private final static String CONFIG_VERSION = "1.0"; private final static String DATA_PATH = "/sdcard/data/downloadTest"; private final static String USER_AGENT = "MyApp Downloader"; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.content.Intent; /** * Usage: * * Intent intent = PreconditionActivityHelper.createPreconditionIntent( * activity, WaitActivity.class); * // Optionally add extras to pass arguments to the intent * intent.putExtra(Utils.EXTRA_ACCOUNT, account); * PreconditionActivityHelper.startPreconditionActivityAndFinish(this, intent); * * // And in the wait activity: * PreconditionActivityHelper.startOriginalActivityAndFinish(this); * */ public class PreconditionActivityHelper { /** * Create a precondition activity intent. * @param activity the original activity * @param preconditionActivityClazz the precondition activity's class * @return an intent which will launch the precondition activity. */ public static Intent createPreconditionIntent(Activity activity, Class preconditionActivityClazz) { Intent newIntent = new Intent(); newIntent.setClass(activity, preconditionActivityClazz); newIntent.putExtra(EXTRA_WRAPPED_INTENT, activity.getIntent()); return newIntent; } /** * Start the precondition activity using a given intent, which should * have been created by calling createPreconditionIntent. * @param activity * @param intent */ public static void startPreconditionActivityAndFinish(Activity activity, Intent intent) { activity.startActivity(intent); activity.finish(); } /** * Start the original activity, and finish the precondition activity. * @param preconditionActivity */ public static void startOriginalActivityAndFinish( Activity preconditionActivity) { preconditionActivity.startActivity( (Intent) preconditionActivity.getIntent() .getParcelableExtra(EXTRA_WRAPPED_INTENT)); preconditionActivity.finish(); } static private final String EXTRA_WRAPPED_INTENT = "PreconditionActivityHelper_wrappedIntent"; }
Java
package com.google.android.webviewdemo; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; /** * Demonstrates how to embed a WebView in your activity. Also demonstrates how * to have javascript in the WebView call into the activity, and how the activity * can invoke javascript. * <p> * In this example, clicking on the android in the WebView will result in a call into * the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code * will turn around and invoke javascript using the {@link WebView#loadUrl(String)} * method. * <p> * Obviously all of this could have been accomplished without calling into the activity * and then back into javascript, but this code is intended to show how to set up the * code paths for this sort of communication. * */ public class WebViewDemo extends Activity { private static final String LOG_TAG = "WebViewDemo"; private WebView mWebView; private Handler mHandler = new Handler(); @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = mWebView.getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); mWebView.setWebChromeClient(new MyWebChromeClient()); mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo"); mWebView.loadUrl("file:///android_asset/demo.html"); } final class DemoJavaScriptInterface { DemoJavaScriptInterface() { } /** * This is not called on the UI thread. Post a runnable to invoke * loadUrl on the UI thread. */ public void clickOnAndroid() { mHandler.post(new Runnable() { public void run() { mWebView.loadUrl("javascript:wave()"); } }); } } /** * Provides a hook for calling "alert" from javascript. Useful for * debugging your javascript. */ final class MyWebChromeClient extends WebChromeClient { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.d(LOG_TAG, message); result.confirm(); return true; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL10; import android.graphics.Paint; public class NumericSprite { public NumericSprite() { mText = ""; mLabelMaker = null; } public void initialize(GL10 gl, Paint paint) { int height = roundUpPower2((int) paint.getFontSpacing()); final float interDigitGaps = 9 * 1.0f; int width = roundUpPower2((int) (interDigitGaps + paint.measureText(sStrike))); mLabelMaker = new LabelMaker(true, width, height); mLabelMaker.initialize(gl); mLabelMaker.beginAdding(gl); for (int i = 0; i < 10; i++) { String digit = sStrike.substring(i, i+1); mLabelId[i] = mLabelMaker.add(gl, digit, paint); mWidth[i] = (int) Math.ceil(mLabelMaker.getWidth(i)); } mLabelMaker.endAdding(gl); } public void shutdown(GL10 gl) { mLabelMaker.shutdown(gl); mLabelMaker = null; } /** * Find the smallest power of two >= the input value. * (Doesn't work for negative numbers.) */ private int roundUpPower2(int x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >>16); return x + 1; } public void setValue(int value) { mText = format(value); } public void draw(GL10 gl, float x, float y, float viewWidth, float viewHeight) { int length = mText.length(); mLabelMaker.beginDrawing(gl, viewWidth, viewHeight); for(int i = 0; i < length; i++) { char c = mText.charAt(i); int digit = c - '0'; mLabelMaker.draw(gl, x, y, mLabelId[digit]); x += mWidth[digit]; } mLabelMaker.endDrawing(gl); } public float width() { float width = 0.0f; int length = mText.length(); for(int i = 0; i < length; i++) { char c = mText.charAt(i); width += mWidth[c - '0']; } return width; } private String format(int value) { return Integer.toString(value); } private LabelMaker mLabelMaker; private String mText; private int[] mWidth = new int[10]; private int[] mLabelId = new int[10]; private final static String sStrike = "0123456789"; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.opengl.Matrix; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * A matrix stack, similar to OpenGL ES's internal matrix stack. */ public class MatrixStack { public MatrixStack() { commonInit(DEFAULT_MAX_DEPTH); } public MatrixStack(int maxDepth) { commonInit(maxDepth); } private void commonInit(int maxDepth) { mMatrix = new float[maxDepth * MATRIX_SIZE]; mTemp = new float[MATRIX_SIZE * 2]; glLoadIdentity(); } public void glFrustumf(float left, float right, float bottom, float top, float near, float far) { Matrix.frustumM(mMatrix, mTop, left, right, bottom, top, near, far); } public void glFrustumx(int left, int right, int bottom, int top, int near, int far) { glFrustumf(fixedToFloat(left),fixedToFloat(right), fixedToFloat(bottom), fixedToFloat(top), fixedToFloat(near), fixedToFloat(far)); } public void glLoadIdentity() { Matrix.setIdentityM(mMatrix, mTop); } public void glLoadMatrixf(float[] m, int offset) { System.arraycopy(m, offset, mMatrix, mTop, MATRIX_SIZE); } public void glLoadMatrixf(FloatBuffer m) { m.get(mMatrix, mTop, MATRIX_SIZE); } public void glLoadMatrixx(int[] m, int offset) { for(int i = 0; i < MATRIX_SIZE; i++) { mMatrix[mTop + i] = fixedToFloat(m[offset + i]); } } public void glLoadMatrixx(IntBuffer m) { for(int i = 0; i < MATRIX_SIZE; i++) { mMatrix[mTop + i] = fixedToFloat(m.get()); } } public void glMultMatrixf(float[] m, int offset) { System.arraycopy(mMatrix, mTop, mTemp, 0, MATRIX_SIZE); Matrix.multiplyMM(mMatrix, mTop, mTemp, 0, m, offset); } public void glMultMatrixf(FloatBuffer m) { m.get(mTemp, MATRIX_SIZE, MATRIX_SIZE); glMultMatrixf(mTemp, MATRIX_SIZE); } public void glMultMatrixx(int[] m, int offset) { for(int i = 0; i < MATRIX_SIZE; i++) { mTemp[MATRIX_SIZE + i] = fixedToFloat(m[offset + i]); } glMultMatrixf(mTemp, MATRIX_SIZE); } public void glMultMatrixx(IntBuffer m) { for(int i = 0; i < MATRIX_SIZE; i++) { mTemp[MATRIX_SIZE + i] = fixedToFloat(m.get()); } glMultMatrixf(mTemp, MATRIX_SIZE); } public void glOrthof(float left, float right, float bottom, float top, float near, float far) { Matrix.orthoM(mMatrix, mTop, left, right, bottom, top, near, far); } public void glOrthox(int left, int right, int bottom, int top, int near, int far) { glOrthof(fixedToFloat(left), fixedToFloat(right), fixedToFloat(bottom), fixedToFloat(top), fixedToFloat(near), fixedToFloat(far)); } public void glPopMatrix() { preflight_adjust(-1); adjust(-1); } public void glPushMatrix() { preflight_adjust(1); System.arraycopy(mMatrix, mTop, mMatrix, mTop + MATRIX_SIZE, MATRIX_SIZE); adjust(1); } public void glRotatef(float angle, float x, float y, float z) { Matrix.setRotateM(mTemp, 0, angle, x, y, z); System.arraycopy(mMatrix, mTop, mTemp, MATRIX_SIZE, MATRIX_SIZE); Matrix.multiplyMM(mMatrix, mTop, mTemp, MATRIX_SIZE, mTemp, 0); } public void glRotatex(int angle, int x, int y, int z) { glRotatef(angle, fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void glScalef(float x, float y, float z) { Matrix.scaleM(mMatrix, mTop, x, y, z); } public void glScalex(int x, int y, int z) { glScalef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void glTranslatef(float x, float y, float z) { Matrix.translateM(mMatrix, mTop, x, y, z); } public void glTranslatex(int x, int y, int z) { glTranslatef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void getMatrix(float[] dest, int offset) { System.arraycopy(mMatrix, mTop, dest, offset, MATRIX_SIZE); } private float fixedToFloat(int x) { return x * (1.0f / 65536.0f); } private void preflight_adjust(int dir) { int newTop = mTop + dir * MATRIX_SIZE; if (newTop < 0) { throw new IllegalArgumentException("stack underflow"); } if (newTop + MATRIX_SIZE > mMatrix.length) { throw new IllegalArgumentException("stack overflow"); } } private void adjust(int dir) { mTop += dir * MATRIX_SIZE; } private final static int DEFAULT_MAX_DEPTH = 32; private final static int MATRIX_SIZE = 16; private float[] mMatrix; private int mTop; private float[] mTemp; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Paint; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.SystemClock; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; public class SpriteTextRenderer implements GLView.Renderer{ public SpriteTextRenderer(Context context) { mContext = context; mTriangle = new Triangle(); mProjector = new Projector(); mLabelPaint = new Paint(); mLabelPaint.setTextSize(32); mLabelPaint.setAntiAlias(true); mLabelPaint.setARGB(0xff, 0x00, 0x00, 0x00); } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void surfaceCreated(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); /* * Some one-time OpenGL initialization can be made here * probably based on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(.5f, .5f, .5f, 1); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = mContext.getResources() .openRawResource(R.drawable.tex); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); if (mLabels != null) { mLabels.shutdown(gl); } else { mLabels = new LabelMaker(true, 256, 64); } mLabels.initialize(gl); mLabels.beginAdding(gl); mLabelA = mLabels.add(gl, "A", mLabelPaint); mLabelB = mLabels.add(gl, "B", mLabelPaint); mLabelC = mLabels.add(gl, "C", mLabelPaint); mLabelMsPF = mLabels.add(gl, "ms/f", mLabelPaint); mLabels.endAdding(gl); if (mNumericSprite != null) { mNumericSprite.shutdown(gl); } else { mNumericSprite = new NumericSprite(); } mNumericSprite.initialize(gl, mLabelPaint); } public void drawFrame(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); /* * Usually, the first thing one might want to do is to clear * the screen. The most efficient way of doing this is to use * glClear(). */ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); /* * Now we're ready to draw some 3D objects */ gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0.0f, 0.0f, -2.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glActiveTexture(GL10.GL_TEXTURE0); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); gl.glRotatef(angle, 0, 0, 1.0f); gl.glScalef(2.0f, 2.0f, 2.0f); mTriangle.draw(gl); mProjector.getCurrentModelView(gl); mLabels.beginDrawing(gl, mWidth, mHeight); drawLabel(gl, 0, mLabelA); drawLabel(gl, 1, mLabelB); drawLabel(gl, 2, mLabelC); float msPFX = mWidth - mLabels.getWidth(mLabelMsPF) - 1; mLabels.draw(gl, msPFX, 0, mLabelMsPF); mLabels.endDrawing(gl); drawMsPF(gl, msPFX); } private void drawMsPF(GL10 gl, float rightMargin) { long time = SystemClock.uptimeMillis(); if (mStartTime == 0) { mStartTime = time; } if (mFrames++ == SAMPLE_PERIOD_FRAMES) { mFrames = 0; long delta = time - mStartTime; mStartTime = time; mMsPerFrame = (int) (delta * SAMPLE_FACTOR); } if (mMsPerFrame > 0) { mNumericSprite.setValue(mMsPerFrame); float numWidth = mNumericSprite.width(); float x = rightMargin - numWidth; mNumericSprite.draw(gl, x, 0, mWidth, mHeight); } } private void drawLabel(GL10 gl, int triangleVertex, int labelId) { float x = mTriangle.getX(triangleVertex); float y = mTriangle.getY(triangleVertex); mScratch[0] = x; mScratch[1] = y; mScratch[2] = 0.0f; mScratch[3] = 1.0f; mProjector.project(mScratch, 0, mScratch, 4); float sx = mScratch[4]; float sy = mScratch[5]; float height = mLabels.getHeight(labelId); float width = mLabels.getWidth(labelId); float tx = sx - width * 0.5f; float ty = sy - height * 0.5f; mLabels.draw(gl, tx, ty, labelId); } public void sizeChanged(GL10 gl, int w, int h) { mWidth = w; mHeight = h; gl.glViewport(0, 0, w, h); mProjector.setCurrentView(0, 0, w, h); /* * Set our projection matrix. This doesn't have to be done * each time we draw, but usually a new projection needs to * be set when the viewport is resized. */ float ratio = (float) w / h; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10); mProjector.getCurrentProjection(gl); } private int mWidth; private int mHeight; private Context mContext; private Triangle mTriangle; private int mTextureID; private int mFrames; private int mMsPerFrame; private final static int SAMPLE_PERIOD_FRAMES = 12; private final static float SAMPLE_FACTOR = 1.0f / SAMPLE_PERIOD_FRAMES; private long mStartTime; private LabelMaker mLabels; private Paint mLabelPaint; private int mLabelA; private int mLabelB; private int mLabelC; private int mLabelMsPF; private Projector mProjector; private NumericSprite mNumericSprite; private float[] mScratch = new float[8]; } class Triangle { public Triangle() { // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(sCoords[i*3+j]); } } for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 2; j++) { mTexBuffer.put(sCoords[i*3+j] * 2.0f + 0.5f); } } for(int i = 0; i < VERTS; i++) { mIndexBuffer.put((short) i); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } public float getX(int vertex) { return sCoords[3*vertex]; } public float getY(int vertex) { return sCoords[3*vertex+1]; } private final static int VERTS = 3; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; // A unit-sided equalateral triangle centered on the origin. private final static float[] sCoords = { // X, Y, Z -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL10; class MatrixGrabber { public MatrixGrabber() { mModelView = new float[16]; mProjection = new float[16]; } /** * Record the current modelView and projection matrix state. * Has the side effect of setting the current matrix state to GL_MODELVIEW * @param gl */ public void getCurrentState(GL10 gl) { getCurrentProjection(gl); getCurrentModelView(gl); } /** * Record the current modelView matrix state. Has the side effect of * setting the current matrix state to GL_MODELVIEW * @param gl */ public void getCurrentModelView(GL10 gl) { getMatrix(gl, GL10.GL_MODELVIEW, mModelView); } /** * Record the current projection matrix state. Has the side effect of * setting the current matrix state to GL_PROJECTION * @param gl */ public void getCurrentProjection(GL10 gl) { getMatrix(gl, GL10.GL_PROJECTION, mProjection); } private void getMatrix(GL10 gl, int mode, float[] mat) { MatrixTrackingGL gl2 = (MatrixTrackingGL) gl; gl2.glMatrixMode(mode); gl2.getMatrix(mat, 0); } public float[] mModelView; public float[] mProjection; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; import android.opengl.GLUtils; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; /** * An OpenGL text label maker. * * * OpenGL labels are implemented by creating a Bitmap, drawing all the labels * into the Bitmap, converting the Bitmap into an Alpha texture, and creating a * mesh for each label * * The benefits of this approach are that the labels are drawn using the high * quality anti-aliased font rasterizer, full character set support, and all the * text labels are stored on a single texture, which makes it faster to use. * * The drawbacks are that you can only have as many labels as will fit onto one * texture, and you have to recreate the whole texture if any label text * changes. * */ public class LabelMaker { /** * Create a label maker * or maximum compatibility with various OpenGL ES implementations, * the strike width and height must be powers of two, * We want the strike width to be at least as wide as the widest window. * * @param fullColor true if we want a full color backing store (4444), * otherwise we generate a grey L8 backing store. * @param strikeWidth width of strike * @param strikeHeight height of strike */ public LabelMaker(boolean fullColor, int strikeWidth, int strikeHeight) { mFullColor = fullColor; mStrikeWidth = strikeWidth; mStrikeHeight = strikeHeight; mTexelWidth = (float) (1.0 / mStrikeWidth); mTexelHeight = (float) (1.0 / mStrikeHeight); mClearPaint = new Paint(); mClearPaint.setARGB(0, 0, 0, 0); mClearPaint.setStyle(Style.FILL); mState = STATE_NEW; } /** * Call to initialize the class. * Call whenever the surface has been created. * * @param gl */ public void initialize(GL10 gl) { mState = STATE_INITIALIZED; int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); // Use Nearest for performance. gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); } /** * Call when the surface has been destroyed */ public void shutdown(GL10 gl) { if ( gl != null) { if (mState > STATE_NEW) { int[] textures = new int[1]; textures[0] = mTextureID; gl.glDeleteTextures(1, textures, 0); mState = STATE_NEW; } } } /** * Call before adding labels. Clears out any existing labels. * * @param gl */ public void beginAdding(GL10 gl) { checkState(STATE_INITIALIZED, STATE_ADDING); mLabels.clear(); mU = 0; mV = 0; mLineHeight = 0; Bitmap.Config config = mFullColor ? Bitmap.Config.ARGB_4444 : Bitmap.Config.ALPHA_8; mBitmap = Bitmap.createBitmap(mStrikeWidth, mStrikeHeight, config); mCanvas = new Canvas(mBitmap); mBitmap.eraseColor(0); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, String text, Paint textPaint) { return add(gl, null, text, textPaint); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable background, String text, Paint textPaint) { return add(gl, background, text, textPaint, 0, 0); } /** * Call to add a label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable drawable, int minWidth, int minHeight) { return add(gl, drawable, null, null, minWidth, minHeight); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable background, String text, Paint textPaint, int minWidth, int minHeight) { checkState(STATE_ADDING, STATE_ADDING); boolean drawBackground = background != null; boolean drawText = (text != null) && (textPaint != null); Rect padding = new Rect(); if (drawBackground) { background.getPadding(padding); minWidth = Math.max(minWidth, background.getMinimumWidth()); minHeight = Math.max(minHeight, background.getMinimumHeight()); } int ascent = 0; int descent = 0; int measuredTextWidth = 0; if (drawText) { // Paint.ascent is negative, so negate it. ascent = (int) Math.ceil(-textPaint.ascent()); descent = (int) Math.ceil(textPaint.descent()); measuredTextWidth = (int) Math.ceil(textPaint.measureText(text)); } int textHeight = ascent + descent; int textWidth = Math.min(mStrikeWidth,measuredTextWidth); int padHeight = padding.top + padding.bottom; int padWidth = padding.left + padding.right; int height = Math.max(minHeight, textHeight + padHeight); int width = Math.max(minWidth, textWidth + padWidth); int effectiveTextHeight = height - padHeight; int effectiveTextWidth = width - padWidth; int centerOffsetHeight = (effectiveTextHeight - textHeight) / 2; int centerOffsetWidth = (effectiveTextWidth - textWidth) / 2; // Make changes to the local variables, only commit them // to the member variables after we've decided not to throw // any exceptions. int u = mU; int v = mV; int lineHeight = mLineHeight; if (width > mStrikeWidth) { width = mStrikeWidth; } // Is there room for this string on the current line? if (u + width > mStrikeWidth) { // No room, go to the next line: u = 0; v += lineHeight; lineHeight = 0; } lineHeight = Math.max(lineHeight, height); if (v + lineHeight > mStrikeHeight) { throw new IllegalArgumentException("Out of texture space."); } int u2 = u + width; int vBase = v + ascent; int v2 = v + height; if (drawBackground) { background.setBounds(u, v, u + width, v + height); background.draw(mCanvas); } if (drawText) { mCanvas.drawText(text, u + padding.left + centerOffsetWidth, vBase + padding.top + centerOffsetHeight, textPaint); } Grid grid = new Grid(2, 2); // Grid.set arguments: i, j, x, y, z, u, v float texU = u * mTexelWidth; float texU2 = u2 * mTexelWidth; float texV = 1.0f - v * mTexelHeight; float texV2 = 1.0f - v2 * mTexelHeight; grid.set(0, 0, 0.0f, 0.0f, 0.0f, texU , texV2); grid.set(1, 0, width, 0.0f, 0.0f, texU2, texV2); grid.set(0, 1, 0.0f, height, 0.0f, texU , texV ); grid.set(1, 1, width, height, 0.0f, texU2, texV ); // We know there's enough space, so update the member variables mU = u + width; mV = v; mLineHeight = lineHeight; mLabels.add(new Label(grid, width, height, ascent, u, v + height, width, -height)); return mLabels.size() - 1; } /** * Call to end adding labels. Must be called before drawing starts. * * @param gl */ public void endAdding(GL10 gl) { checkState(STATE_ADDING, STATE_INITIALIZED); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0); // Reclaim storage used by bitmap and canvas. mBitmap.recycle(); mBitmap = null; mCanvas = null; } /** * Get the width in pixels of a given label. * * @param labelID * @return the width in pixels */ public float getWidth(int labelID) { return mLabels.get(labelID).width; } /** * Get the height in pixels of a given label. * * @param labelID * @return the height in pixels */ public float getHeight(int labelID) { return mLabels.get(labelID).height; } /** * Get the baseline of a given label. That's how many pixels from the top of * the label to the text baseline. (This is equivalent to the negative of * the label's paint's ascent.) * * @param labelID * @return the baseline in pixels. */ public float getBaseline(int labelID) { return mLabels.get(labelID).baseline; } /** * Begin drawing labels. Sets the OpenGL state for rapid drawing. * * @param gl * @param viewWidth * @param viewHeight */ public void beginDrawing(GL10 gl, float viewWidth, float viewHeight) { checkState(STATE_INITIALIZED, STATE_DRAWING); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glShadeModel(GL10.GL_FLAT); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glPushMatrix(); gl.glLoadIdentity(); gl.glOrthof(0.0f, viewWidth, 0.0f, viewHeight, 0.0f, 1.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glPushMatrix(); gl.glLoadIdentity(); // Magic offsets to promote consistent rasterization. gl.glTranslatef(0.375f, 0.375f, 0.0f); } /** * Draw a given label at a given x,y position, expressed in pixels, with the * lower-left-hand-corner of the view being (0,0). * * @param gl * @param x * @param y * @param labelID */ public void draw(GL10 gl, float x, float y, int labelID) { checkState(STATE_DRAWING, STATE_DRAWING); gl.glPushMatrix(); float snappedX = (float) Math.floor(x); float snappedY = (float) Math.floor(y); gl.glTranslatef(snappedX, snappedY, 0.0f); Label label = mLabels.get(labelID); gl.glEnable(GL10.GL_TEXTURE_2D); ((GL11)gl).glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, label.mCrop, 0); ((GL11Ext)gl).glDrawTexiOES((int) snappedX, (int) snappedY, 0, (int) label.width, (int) label.height); gl.glPopMatrix(); } /** * Ends the drawing and restores the OpenGL state. * * @param gl */ public void endDrawing(GL10 gl) { checkState(STATE_DRAWING, STATE_INITIALIZED); gl.glDisable(GL10.GL_BLEND); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glPopMatrix(); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glPopMatrix(); } private void checkState(int oldState, int newState) { if (mState != oldState) { throw new IllegalArgumentException("Can't call this method now."); } mState = newState; } private static class Label { public Label(Grid grid, float width, float height, float baseLine, int cropU, int cropV, int cropW, int cropH) { this.grid = grid; this.width = width; this.height = height; this.baseline = baseLine; int[] crop = new int[4]; crop[0] = cropU; crop[1] = cropV; crop[2] = cropW; crop[3] = cropH; mCrop = crop; } public Grid grid; public float width; public float height; public float baseline; public int[] mCrop; } private int mStrikeWidth; private int mStrikeHeight; private boolean mFullColor; private Bitmap mBitmap; private Canvas mCanvas; private Paint mClearPaint; private int mTextureID; private float mTexelWidth; // Convert texel to U private float mTexelHeight; // Convert texel to V private int mU; private int mV; private int mLineHeight; private ArrayList<Label> mLabels = new ArrayList<Label>(); private static final int STATE_NEW = 0; private static final int STATE_INITIALIZED = 1; private static final int STATE_ADDING = 2; private static final int STATE_DRAWING = 3; private int mState; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.opengles.spritetext; import android.opengl.Matrix; import javax.microedition.khronos.opengles.GL10; /** * A utility that projects * */ class Projector { public Projector() { mMVP = new float[16]; mV = new float[4]; mGrabber = new MatrixGrabber(); } public void setCurrentView(int x, int y, int width, int height) { mX = x; mY = y; mViewWidth = width; mViewHeight = height; } public void project(float[] obj, int objOffset, float[] win, int winOffset) { if (!mMVPComputed) { Matrix.multiplyMM(mMVP, 0, mGrabber.mProjection, 0, mGrabber.mModelView, 0); mMVPComputed = true; } Matrix.multiplyMV(mV, 0, mMVP, 0, obj, objOffset); float rw = 1.0f / mV[3]; win[winOffset] = mX + mViewWidth * (mV[0] * rw + 1.0f) * 0.5f; win[winOffset + 1] = mY + mViewHeight * (mV[1] * rw + 1.0f) * 0.5f; win[winOffset + 2] = (mV[2] * rw + 1.0f) * 0.5f; } /** * Get the current projection matrix. Has the side-effect of * setting current matrix mode to GL_PROJECTION * @param gl */ public void getCurrentProjection(GL10 gl) { mGrabber.getCurrentProjection(gl); mMVPComputed = false; } /** * Get the current model view matrix. Has the side-effect of * setting current matrix mode to GL_MODELVIEW * @param gl */ public void getCurrentModelView(GL10 gl) { mGrabber.getCurrentModelView(gl); mMVPComputed = false; } private MatrixGrabber mGrabber; private boolean mMVPComputed; private float[] mMVP; private float[] mV; private int mX; private int mY; private int mViewWidth; private int mViewHeight; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ class GLView extends SurfaceView implements SurfaceHolder.Callback { GLView(Context context) { super(context); init(); } public GLView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { Runnable r; while ((r = getEvent()) != null) { r.run(); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { /* draw a frame here */ mRenderer.drawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ mEglHelper.swap(); } } /* * clean-up everything... */ mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { synchronized(this) { mEventQueue.add(r); } } private Runnable getEvent() { synchronized(this) { if (mEventQueue.size() > 0) { return mEventQueue.remove(0); } } return null; } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.util.Log; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL10Ext; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; /** * Allows retrieving the current matrix even if the current OpenGL ES * driver does not support retrieving the current matrix. * * Note: the actual matrix may differ from the retrieved matrix, due * to differences in the way the math is implemented by GLMatrixWrapper * as compared to the way the math is implemented by the OpenGL ES * driver. */ class MatrixTrackingGL implements GL, GL10, GL10Ext, GL11, GL11Ext { private GL10 mgl; private GL10Ext mgl10Ext; private GL11 mgl11; private GL11Ext mgl11Ext; private int mMatrixMode; private MatrixStack mCurrent; private MatrixStack mModelView; private MatrixStack mTexture; private MatrixStack mProjection; private final static boolean _check = false; ByteBuffer mByteBuffer; FloatBuffer mFloatBuffer; float[] mCheckA; float[] mCheckB; public MatrixTrackingGL(GL gl) { mgl = (GL10) gl; if (gl instanceof GL10Ext) { mgl10Ext = (GL10Ext) gl; } if (gl instanceof GL11) { mgl11 = (GL11) gl; } if (gl instanceof GL11Ext) { mgl11Ext = (GL11Ext) gl; } mModelView = new MatrixStack(); mProjection = new MatrixStack(); mTexture = new MatrixStack(); mCurrent = mModelView; mMatrixMode = GL10.GL_MODELVIEW; } // --------------------------------------------------------------------- // GL10 methods: public void glActiveTexture(int texture) { mgl.glActiveTexture(texture); } public void glAlphaFunc(int func, float ref) { mgl.glAlphaFunc(func, ref); } public void glAlphaFuncx(int func, int ref) { mgl.glAlphaFuncx(func, ref); } public void glBindTexture(int target, int texture) { mgl.glBindTexture(target, texture); } public void glBlendFunc(int sfactor, int dfactor) { mgl.glBlendFunc(sfactor, dfactor); } public void glClear(int mask) { mgl.glClear(mask); } public void glClearColor(float red, float green, float blue, float alpha) { mgl.glClearColor(red, green, blue, alpha); } public void glClearColorx(int red, int green, int blue, int alpha) { mgl.glClearColorx(red, green, blue, alpha); } public void glClearDepthf(float depth) { mgl.glClearDepthf(depth); } public void glClearDepthx(int depth) { mgl.glClearDepthx(depth); } public void glClearStencil(int s) { mgl.glClearStencil(s); } public void glClientActiveTexture(int texture) { mgl.glClientActiveTexture(texture); } public void glColor4f(float red, float green, float blue, float alpha) { mgl.glColor4f(red, green, blue, alpha); } public void glColor4x(int red, int green, int blue, int alpha) { mgl.glColor4x(red, green, blue, alpha); } public void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) { mgl.glColorMask(red, green, blue, alpha); } public void glColorPointer(int size, int type, int stride, Buffer pointer) { mgl.glColorPointer(size, type, stride, pointer); } public void glCompressedTexImage2D(int target, int level, int internalformat, int width, int height, int border, int imageSize, Buffer data) { mgl.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } public void glCompressedTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int imageSize, Buffer data) { mgl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); } public void glCopyTexImage2D(int target, int level, int internalformat, int x, int y, int width, int height, int border) { mgl.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); } public void glCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { mgl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } public void glCullFace(int mode) { mgl.glCullFace(mode); } public void glDeleteTextures(int n, int[] textures, int offset) { mgl.glDeleteTextures(n, textures, offset); } public void glDeleteTextures(int n, IntBuffer textures) { mgl.glDeleteTextures(n, textures); } public void glDepthFunc(int func) { mgl.glDepthFunc(func); } public void glDepthMask(boolean flag) { mgl.glDepthMask(flag); } public void glDepthRangef(float near, float far) { mgl.glDepthRangef(near, far); } public void glDepthRangex(int near, int far) { mgl.glDepthRangex(near, far); } public void glDisable(int cap) { mgl.glDisable(cap); } public void glDisableClientState(int array) { mgl.glDisableClientState(array); } public void glDrawArrays(int mode, int first, int count) { mgl.glDrawArrays(mode, first, count); } public void glDrawElements(int mode, int count, int type, Buffer indices) { mgl.glDrawElements(mode, count, type, indices); } public void glEnable(int cap) { mgl.glEnable(cap); } public void glEnableClientState(int array) { mgl.glEnableClientState(array); } public void glFinish() { mgl.glFinish(); } public void glFlush() { mgl.glFlush(); } public void glFogf(int pname, float param) { mgl.glFogf(pname, param); } public void glFogfv(int pname, float[] params, int offset) { mgl.glFogfv(pname, params, offset); } public void glFogfv(int pname, FloatBuffer params) { mgl.glFogfv(pname, params); } public void glFogx(int pname, int param) { mgl.glFogx(pname, param); } public void glFogxv(int pname, int[] params, int offset) { mgl.glFogxv(pname, params, offset); } public void glFogxv(int pname, IntBuffer params) { mgl.glFogxv(pname, params); } public void glFrontFace(int mode) { mgl.glFrontFace(mode); } public void glFrustumf(float left, float right, float bottom, float top, float near, float far) { mCurrent.glFrustumf(left, right, bottom, top, near, far); mgl.glFrustumf(left, right, bottom, top, near, far); if ( _check) check(); } public void glFrustumx(int left, int right, int bottom, int top, int near, int far) { mCurrent.glFrustumx(left, right, bottom, top, near, far); mgl.glFrustumx(left, right, bottom, top, near, far); if ( _check) check(); } public void glGenTextures(int n, int[] textures, int offset) { mgl.glGenTextures(n, textures, offset); } public void glGenTextures(int n, IntBuffer textures) { mgl.glGenTextures(n, textures); } public int glGetError() { int result = mgl.glGetError(); return result; } public void glGetIntegerv(int pname, int[] params, int offset) { mgl.glGetIntegerv(pname, params, offset); } public void glGetIntegerv(int pname, IntBuffer params) { mgl.glGetIntegerv(pname, params); } public String glGetString(int name) { String result = mgl.glGetString(name); return result; } public void glHint(int target, int mode) { mgl.glHint(target, mode); } public void glLightModelf(int pname, float param) { mgl.glLightModelf(pname, param); } public void glLightModelfv(int pname, float[] params, int offset) { mgl.glLightModelfv(pname, params, offset); } public void glLightModelfv(int pname, FloatBuffer params) { mgl.glLightModelfv(pname, params); } public void glLightModelx(int pname, int param) { mgl.glLightModelx(pname, param); } public void glLightModelxv(int pname, int[] params, int offset) { mgl.glLightModelxv(pname, params, offset); } public void glLightModelxv(int pname, IntBuffer params) { mgl.glLightModelxv(pname, params); } public void glLightf(int light, int pname, float param) { mgl.glLightf(light, pname, param); } public void glLightfv(int light, int pname, float[] params, int offset) { mgl.glLightfv(light, pname, params, offset); } public void glLightfv(int light, int pname, FloatBuffer params) { mgl.glLightfv(light, pname, params); } public void glLightx(int light, int pname, int param) { mgl.glLightx(light, pname, param); } public void glLightxv(int light, int pname, int[] params, int offset) { mgl.glLightxv(light, pname, params, offset); } public void glLightxv(int light, int pname, IntBuffer params) { mgl.glLightxv(light, pname, params); } public void glLineWidth(float width) { mgl.glLineWidth(width); } public void glLineWidthx(int width) { mgl.glLineWidthx(width); } public void glLoadIdentity() { mCurrent.glLoadIdentity(); mgl.glLoadIdentity(); if ( _check) check(); } public void glLoadMatrixf(float[] m, int offset) { mCurrent.glLoadMatrixf(m, offset); mgl.glLoadMatrixf(m, offset); if ( _check) check(); } public void glLoadMatrixf(FloatBuffer m) { int position = m.position(); mCurrent.glLoadMatrixf(m); m.position(position); mgl.glLoadMatrixf(m); if ( _check) check(); } public void glLoadMatrixx(int[] m, int offset) { mCurrent.glLoadMatrixx(m, offset); mgl.glLoadMatrixx(m, offset); if ( _check) check(); } public void glLoadMatrixx(IntBuffer m) { int position = m.position(); mCurrent.glLoadMatrixx(m); m.position(position); mgl.glLoadMatrixx(m); if ( _check) check(); } public void glLogicOp(int opcode) { mgl.glLogicOp(opcode); } public void glMaterialf(int face, int pname, float param) { mgl.glMaterialf(face, pname, param); } public void glMaterialfv(int face, int pname, float[] params, int offset) { mgl.glMaterialfv(face, pname, params, offset); } public void glMaterialfv(int face, int pname, FloatBuffer params) { mgl.glMaterialfv(face, pname, params); } public void glMaterialx(int face, int pname, int param) { mgl.glMaterialx(face, pname, param); } public void glMaterialxv(int face, int pname, int[] params, int offset) { mgl.glMaterialxv(face, pname, params, offset); } public void glMaterialxv(int face, int pname, IntBuffer params) { mgl.glMaterialxv(face, pname, params); } public void glMatrixMode(int mode) { switch (mode) { case GL10.GL_MODELVIEW: mCurrent = mModelView; break; case GL10.GL_TEXTURE: mCurrent = mTexture; break; case GL10.GL_PROJECTION: mCurrent = mProjection; break; default: throw new IllegalArgumentException("Unknown matrix mode: " + mode); } mgl.glMatrixMode(mode); mMatrixMode = mode; if ( _check) check(); } public void glMultMatrixf(float[] m, int offset) { mCurrent.glMultMatrixf(m, offset); mgl.glMultMatrixf(m, offset); if ( _check) check(); } public void glMultMatrixf(FloatBuffer m) { int position = m.position(); mCurrent.glMultMatrixf(m); m.position(position); mgl.glMultMatrixf(m); if ( _check) check(); } public void glMultMatrixx(int[] m, int offset) { mCurrent.glMultMatrixx(m, offset); mgl.glMultMatrixx(m, offset); if ( _check) check(); } public void glMultMatrixx(IntBuffer m) { int position = m.position(); mCurrent.glMultMatrixx(m); m.position(position); mgl.glMultMatrixx(m); if ( _check) check(); } public void glMultiTexCoord4f(int target, float s, float t, float r, float q) { mgl.glMultiTexCoord4f(target, s, t, r, q); } public void glMultiTexCoord4x(int target, int s, int t, int r, int q) { mgl.glMultiTexCoord4x(target, s, t, r, q); } public void glNormal3f(float nx, float ny, float nz) { mgl.glNormal3f(nx, ny, nz); } public void glNormal3x(int nx, int ny, int nz) { mgl.glNormal3x(nx, ny, nz); } public void glNormalPointer(int type, int stride, Buffer pointer) { mgl.glNormalPointer(type, stride, pointer); } public void glOrthof(float left, float right, float bottom, float top, float near, float far) { mCurrent.glOrthof(left, right, bottom, top, near, far); mgl.glOrthof(left, right, bottom, top, near, far); if ( _check) check(); } public void glOrthox(int left, int right, int bottom, int top, int near, int far) { mCurrent.glOrthox(left, right, bottom, top, near, far); mgl.glOrthox(left, right, bottom, top, near, far); if ( _check) check(); } public void glPixelStorei(int pname, int param) { mgl.glPixelStorei(pname, param); } public void glPointSize(float size) { mgl.glPointSize(size); } public void glPointSizex(int size) { mgl.glPointSizex(size); } public void glPolygonOffset(float factor, float units) { mgl.glPolygonOffset(factor, units); } public void glPolygonOffsetx(int factor, int units) { mgl.glPolygonOffsetx(factor, units); } public void glPopMatrix() { mCurrent.glPopMatrix(); mgl.glPopMatrix(); if ( _check) check(); } public void glPushMatrix() { mCurrent.glPushMatrix(); mgl.glPushMatrix(); if ( _check) check(); } public void glReadPixels(int x, int y, int width, int height, int format, int type, Buffer pixels) { mgl.glReadPixels(x, y, width, height, format, type, pixels); } public void glRotatef(float angle, float x, float y, float z) { mCurrent.glRotatef(angle, x, y, z); mgl.glRotatef(angle, x, y, z); if ( _check) check(); } public void glRotatex(int angle, int x, int y, int z) { mCurrent.glRotatex(angle, x, y, z); mgl.glRotatex(angle, x, y, z); if ( _check) check(); } public void glSampleCoverage(float value, boolean invert) { mgl.glSampleCoverage(value, invert); } public void glSampleCoveragex(int value, boolean invert) { mgl.glSampleCoveragex(value, invert); } public void glScalef(float x, float y, float z) { mCurrent.glScalef(x, y, z); mgl.glScalef(x, y, z); if ( _check) check(); } public void glScalex(int x, int y, int z) { mCurrent.glScalex(x, y, z); mgl.glScalex(x, y, z); if ( _check) check(); } public void glScissor(int x, int y, int width, int height) { mgl.glScissor(x, y, width, height); } public void glShadeModel(int mode) { mgl.glShadeModel(mode); } public void glStencilFunc(int func, int ref, int mask) { mgl.glStencilFunc(func, ref, mask); } public void glStencilMask(int mask) { mgl.glStencilMask(mask); } public void glStencilOp(int fail, int zfail, int zpass) { mgl.glStencilOp(fail, zfail, zpass); } public void glTexCoordPointer(int size, int type, int stride, Buffer pointer) { mgl.glTexCoordPointer(size, type, stride, pointer); } public void glTexEnvf(int target, int pname, float param) { mgl.glTexEnvf(target, pname, param); } public void glTexEnvfv(int target, int pname, float[] params, int offset) { mgl.glTexEnvfv(target, pname, params, offset); } public void glTexEnvfv(int target, int pname, FloatBuffer params) { mgl.glTexEnvfv(target, pname, params); } public void glTexEnvx(int target, int pname, int param) { mgl.glTexEnvx(target, pname, param); } public void glTexEnvxv(int target, int pname, int[] params, int offset) { mgl.glTexEnvxv(target, pname, params, offset); } public void glTexEnvxv(int target, int pname, IntBuffer params) { mgl.glTexEnvxv(target, pname, params); } public void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, Buffer pixels) { mgl.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } public void glTexParameterf(int target, int pname, float param) { mgl.glTexParameterf(target, pname, param); } public void glTexParameterx(int target, int pname, int param) { mgl.glTexParameterx(target, pname, param); } public void glTexParameteriv(int target, int pname, int[] params, int offset) { mgl11.glTexParameteriv(target, pname, params, offset); } public void glTexParameteriv(int target, int pname, IntBuffer params) { mgl11.glTexParameteriv(target, pname, params); } public void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, Buffer pixels) { mgl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } public void glTranslatef(float x, float y, float z) { mCurrent.glTranslatef(x, y, z); mgl.glTranslatef(x, y, z); if ( _check) check(); } public void glTranslatex(int x, int y, int z) { mCurrent.glTranslatex(x, y, z); mgl.glTranslatex(x, y, z); if ( _check) check(); } public void glVertexPointer(int size, int type, int stride, Buffer pointer) { mgl.glVertexPointer(size, type, stride, pointer); } public void glViewport(int x, int y, int width, int height) { mgl.glViewport(x, y, width, height); } public void glClipPlanef(int plane, float[] equation, int offset) { mgl11.glClipPlanef(plane, equation, offset); } public void glClipPlanef(int plane, FloatBuffer equation) { mgl11.glClipPlanef(plane, equation); } public void glClipPlanex(int plane, int[] equation, int offset) { mgl11.glClipPlanex(plane, equation, offset); } public void glClipPlanex(int plane, IntBuffer equation) { mgl11.glClipPlanex(plane, equation); } // Draw Texture Extension public void glDrawTexfOES(float x, float y, float z, float width, float height) { mgl11Ext.glDrawTexfOES(x, y, z, width, height); } public void glDrawTexfvOES(float[] coords, int offset) { mgl11Ext.glDrawTexfvOES(coords, offset); } public void glDrawTexfvOES(FloatBuffer coords) { mgl11Ext.glDrawTexfvOES(coords); } public void glDrawTexiOES(int x, int y, int z, int width, int height) { mgl11Ext.glDrawTexiOES(x, y, z, width, height); } public void glDrawTexivOES(int[] coords, int offset) { mgl11Ext.glDrawTexivOES(coords, offset); } public void glDrawTexivOES(IntBuffer coords) { mgl11Ext.glDrawTexivOES(coords); } public void glDrawTexsOES(short x, short y, short z, short width, short height) { mgl11Ext.glDrawTexsOES(x, y, z, width, height); } public void glDrawTexsvOES(short[] coords, int offset) { mgl11Ext.glDrawTexsvOES(coords, offset); } public void glDrawTexsvOES(ShortBuffer coords) { mgl11Ext.glDrawTexsvOES(coords); } public void glDrawTexxOES(int x, int y, int z, int width, int height) { mgl11Ext.glDrawTexxOES(x, y, z, width, height); } public void glDrawTexxvOES(int[] coords, int offset) { mgl11Ext.glDrawTexxvOES(coords, offset); } public void glDrawTexxvOES(IntBuffer coords) { mgl11Ext.glDrawTexxvOES(coords); } public int glQueryMatrixxOES(int[] mantissa, int mantissaOffset, int[] exponent, int exponentOffset) { return mgl10Ext.glQueryMatrixxOES(mantissa, mantissaOffset, exponent, exponentOffset); } public int glQueryMatrixxOES(IntBuffer mantissa, IntBuffer exponent) { return mgl10Ext.glQueryMatrixxOES(mantissa, exponent); } // Unsupported GL11 methods public void glBindBuffer(int target, int buffer) { throw new UnsupportedOperationException(); } public void glBufferData(int target, int size, Buffer data, int usage) { throw new UnsupportedOperationException(); } public void glBufferSubData(int target, int offset, int size, Buffer data) { throw new UnsupportedOperationException(); } public void glColor4ub(byte red, byte green, byte blue, byte alpha) { throw new UnsupportedOperationException(); } public void glDeleteBuffers(int n, int[] buffers, int offset) { throw new UnsupportedOperationException(); } public void glDeleteBuffers(int n, IntBuffer buffers) { throw new UnsupportedOperationException(); } public void glGenBuffers(int n, int[] buffers, int offset) { throw new UnsupportedOperationException(); } public void glGenBuffers(int n, IntBuffer buffers) { throw new UnsupportedOperationException(); } public void glGetBooleanv(int pname, boolean[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetBooleanv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetBufferParameteriv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetBufferParameteriv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetClipPlanef(int pname, float[] eqn, int offset) { throw new UnsupportedOperationException(); } public void glGetClipPlanef(int pname, FloatBuffer eqn) { throw new UnsupportedOperationException(); } public void glGetClipPlanex(int pname, int[] eqn, int offset) { throw new UnsupportedOperationException(); } public void glGetClipPlanex(int pname, IntBuffer eqn) { throw new UnsupportedOperationException(); } public void glGetFixedv(int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetFixedv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetFloatv(int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetFloatv(int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetLightfv(int light, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetLightfv(int light, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetLightxv(int light, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetLightxv(int light, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetMaterialfv(int face, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetMaterialfv(int face, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetMaterialxv(int face, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetMaterialxv(int face, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexEnviv(int env, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexEnviv(int env, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexEnvxv(int env, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexEnvxv(int env, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameterfv(int target, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameterfv(int target, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameteriv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameteriv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameterxv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameterxv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public boolean glIsBuffer(int buffer) { throw new UnsupportedOperationException(); } public boolean glIsEnabled(int cap) { throw new UnsupportedOperationException(); } public boolean glIsTexture(int texture) { throw new UnsupportedOperationException(); } public void glPointParameterf(int pname, float param) { throw new UnsupportedOperationException(); } public void glPointParameterfv(int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glPointParameterfv(int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glPointParameterx(int pname, int param) { throw new UnsupportedOperationException(); } public void glPointParameterxv(int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glPointParameterxv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glPointSizePointerOES(int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glTexEnvi(int target, int pname, int param) { throw new UnsupportedOperationException(); } public void glTexEnviv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexEnviv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glTexParameterfv(int target, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexParameterfv(int target, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glTexParameteri(int target, int pname, int param) { throw new UnsupportedOperationException(); } public void glTexParameterxv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexParameterxv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glColorPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glDrawElements(int mode, int count, int type, int offset) { throw new UnsupportedOperationException(); } public void glGetPointerv(int pname, Buffer[] params) { throw new UnsupportedOperationException(); } public void glNormalPointer(int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glTexCoordPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glVertexPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glCurrentPaletteMatrixOES(int matrixpaletteindex) { throw new UnsupportedOperationException(); } public void glLoadPaletteFromModelViewMatrixOES() { throw new UnsupportedOperationException(); } public void glMatrixIndexPointerOES(int size, int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glMatrixIndexPointerOES(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glWeightPointerOES(int size, int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glWeightPointerOES(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } /** * Get the current matrix */ public void getMatrix(float[] m, int offset) { mCurrent.getMatrix(m, offset); } /** * Get the current matrix mode */ public int getMatrixMode() { return mMatrixMode; } private void check() { int oesMode; switch (mMatrixMode) { case GL_MODELVIEW: oesMode = GL11.GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES; break; case GL_PROJECTION: oesMode = GL11.GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES; break; case GL_TEXTURE: oesMode = GL11.GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES; break; default: throw new IllegalArgumentException("Unknown matrix mode"); } if ( mByteBuffer == null) { mCheckA = new float[16]; mCheckB = new float[16]; mByteBuffer = ByteBuffer.allocateDirect(64); mByteBuffer.order(ByteOrder.nativeOrder()); mFloatBuffer = mByteBuffer.asFloatBuffer(); } mgl.glGetIntegerv(oesMode, mByteBuffer.asIntBuffer()); for(int i = 0; i < 16; i++) { mCheckB[i] = mFloatBuffer.get(i); } mCurrent.getMatrix(mCheckA, 0); boolean fail = false; for(int i = 0; i < 16; i++) { if (mCheckA[i] != mCheckB[i]) { Log.d("GLMatWrap", "i:" + i + " a:" + mCheckA[i] + " a:" + mCheckB[i]); fail = true; } } if (fail) { throw new IllegalArgumentException("Matrix math difference."); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL; import android.app.Activity; import android.os.Bundle; public class SpriteTextActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGLView = (GLView) findViewById(R.id.glview); mGLView.setGLWrapper(new GLView.GLWrapper() { public GL wrap(GL gl) { return new MatrixTrackingGL(gl); }}); mGLView.setRenderer(new SpriteTextRenderer(this)); mGLView.requestFocus(); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private GLView mGLView; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import java.nio.CharBuffer; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; /** * A 2D rectangular mesh. Can be drawn textured or untextured. * */ class Grid { public Grid(int w, int h) { if (w < 0 || w >= 65536) { throw new IllegalArgumentException("w"); } if (h < 0 || h >= 65536) { throw new IllegalArgumentException("h"); } if (w * h >= 65536) { throw new IllegalArgumentException("w * h >= 65536"); } mW = w; mH = h; int size = w * h; mVertexArray = new float[size * 3]; mVertexBuffer = FloatBuffer.wrap(mVertexArray); mTexCoordArray = new float[size * 2]; mTexCoordBuffer = FloatBuffer.wrap(mTexCoordArray); int quadW = mW - 1; int quadH = mH - 1; int quadCount = quadW * quadH; int indexCount = quadCount * 6; mIndexCount = indexCount; char[] indexArray = new char[indexCount]; /* * Initialize triangle list mesh. * * [0]-----[ 1] ... * | / | * | / | * | / | * [w]-----[w+1] ... * | | * */ { int i = 0; for (int y = 0; y < quadH; y++) { for (int x = 0; x < quadW; x++) { char a = (char) (y * mW + x); char b = (char) (y * mW + x + 1); char c = (char) ((y + 1) * mW + x); char d = (char) ((y + 1) * mW + x + 1); indexArray[i++] = a; indexArray[i++] = b; indexArray[i++] = c; indexArray[i++] = b; indexArray[i++] = c; indexArray[i++] = d; } } } mIndexBuffer = CharBuffer.wrap(indexArray); } void set(int i, int j, float x, float y, float z, float u, float v) { if (i < 0 || i >= mW) { throw new IllegalArgumentException("i"); } if (j < 0 || j >= mH) { throw new IllegalArgumentException("j"); } int index = mW * j + i; int posIndex = index * 3; mVertexArray[posIndex] = x; mVertexArray[posIndex + 1] = y; mVertexArray[posIndex + 2] = z; int texIndex = index * 2; mTexCoordArray[texIndex] = u; mTexCoordArray[texIndex + 1] = v; } public void draw(GL10 gl, boolean useTexture) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer); if (useTexture) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexCoordBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } private FloatBuffer mVertexBuffer; private float[] mVertexArray; private FloatBuffer mTexCoordBuffer; private float[] mTexCoordArray; private CharBuffer mIndexBuffer; private int mW; private int mH; private int mIndexCount; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import javax.microedition.khronos.opengles.GL; import android.app.Activity; import android.opengl.GLDebugHelper; import android.os.Bundle; public class TriangleActivity extends Activity { /** Set to true to enable checking of the OpenGL error code after every OpenGL call. Set to * false for faster code. * */ private final static boolean DEBUG_CHECK_GL_ERROR = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGLView = (GLView) findViewById(R.id.glview); if (DEBUG_CHECK_GL_ERROR) { mGLView.setGLWrapper(new GLView.GLWrapper() { public GL wrap(GL gl) { return GLDebugHelper.wrap(gl, GLDebugHelper.CONFIG_CHECK_GL_ERROR, null); }}); } mGLView.setRenderer(new TriangleRenderer(this)); mGLView.requestFocus(); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private GLView mGLView; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.SystemClock; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; public class TriangleRenderer implements GLView.Renderer{ public TriangleRenderer(Context context) { mContext = context; mTriangle = new Triangle(); } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void surfaceCreated(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); /* * Some one-time OpenGL initialization can be made here * probably based on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(.5f, .5f, .5f, 1); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = mContext.getResources() .openRawResource(R.drawable.tex); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); } public void drawFrame(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); /* * Usually, the first thing one might want to do is to clear * the screen. The most efficient way of doing this is to use * glClear(). */ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); /* * Now we're ready to draw some 3D objects */ gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glActiveTexture(GL10.GL_TEXTURE0); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); gl.glRotatef(angle, 0, 0, 1.0f); mTriangle.draw(gl); } public void sizeChanged(GL10 gl, int w, int h) { gl.glViewport(0, 0, w, h); /* * Set our projection matrix. This doesn't have to be done * each time we draw, but usually a new projection needs to * be set when the viewport is resized. */ float ratio = (float) w / h; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); } private Context mContext; private Triangle mTriangle; private int mTextureID; } class Triangle { public Triangle() { // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); // A unit-sided equalateral triangle centered on the origin. float[] coords = { // X, Y, Z -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(coords[i*3+j] * 2.0f); } } for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 2; j++) { mTexBuffer.put(coords[i*3+j] * 2.0f + 0.5f); } } for(int i = 0; i < VERTS; i++) { mIndexBuffer.put((short) i); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } private final static int VERTS = 3; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ class GLView extends SurfaceView implements SurfaceHolder.Callback { GLView(Context context) { super(context); init(); } public GLView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { Runnable r; while ((r = getEvent()) != null) { r.run(); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { /* draw a frame here */ mRenderer.drawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ mEglHelper.swap(); } } /* * clean-up everything... */ mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { synchronized(this) { mEventQueue.add(r); } } private Runnable getEvent() { synchronized(this) { if (mEventQueue.size() > 0) { return mEventQueue.remove(0); } } return null; } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
Java
package com.google.clickin2dabeat; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; /** * Checks for updates to the game. */ public class UpdateChecker { public String marketId; @SuppressWarnings("finally") public int getLatestVersionCode() { int version = 0; try { URLConnection cn; URL url = new URL( "http://apps-for-android.googlecode.com/svn/trunk/CLiCkin2DaBeaT/AndroidManifest.xml"); cn = url.openConnection(); cn.connect(); InputStream stream = cn.getInputStream(); DocumentBuilder docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document manifestDoc = docBuild.parse(stream); NodeList manifestNodeList = manifestDoc.getElementsByTagName("manifest"); String versionStr = manifestNodeList.item(0).getAttributes().getNamedItem("android:versionCode") .getNodeValue(); version = Integer.parseInt(versionStr); NodeList clcNodeList = manifestDoc.getElementsByTagName("clc"); marketId = clcNodeList.item(0).getAttributes().getNamedItem("marketId").getNodeValue(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { return version; } } public void checkForNewerVersion(int currentVersion) { int latestVersion = getLatestVersionCode(); if (latestVersion > currentVersion) { } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.graphics.Color; /** * Contains information about the when the beat should be displayed, where it * should be displayed, and what color it should be. */ public class Target { public double time; public int x; public int y; public int color; public Target(double timeToHit, int xpos, int ypos, String hexColor) { time = timeToHit; x = xpos; y = ypos; if (hexColor.length() == 6) { int r = Integer.parseInt(hexColor.substring(0, 2), 16); int g = Integer.parseInt(hexColor.substring(2, 4), 16); int b = Integer.parseInt(hexColor.substring(4, 6), 16); color = Color.rgb(r, g, b); } else { int colorChoice = ((int) (Math.random() * 100)) % 4; if (colorChoice == 0) { color = Color.RED; } else if (colorChoice == 1) { color = Color.GREEN; } else if (colorChoice == 2) { color = Color.BLUE; } else { color = Color.YELLOW; } } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; public class DownloadC2BFile extends Activity { String dataSource; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); dataSource = this.getIntent().getData().toString(); (new Thread(new loader())).start(); } public void runMem() { startApp("com.google.clickin2dabeat", "C2B"); finish(); } private void startApp(String packageName, String className) { try { int flags = Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY; Context myContext = createPackageContext(packageName, flags); Class<?> appClass = myContext.getClassLoader().loadClass(packageName + "." + className); Intent intent = new Intent(myContext, appClass); startActivity(intent); } catch (NameNotFoundException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public class loader implements Runnable { public void run() { Unzipper.unzip(dataSource); runMem(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * Creates a skeleton C2B file when an appropriate media object is opened. */ public class CreateC2BFile extends Activity { private String dataSource; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); dataSource = this.getIntent().getData().toString(); setContentView(R.layout.c2b_creator_form); Button create = ((Button) findViewById(R.id.CreateButton)); create.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { String title = ((EditText) findViewById(R.id.TitleEditText)).getText().toString(); String author = ((EditText) findViewById(R.id.AuthorEditText)).getText().toString(); if (!title.equals("") && !author.equals("")) { createC2BSkeleton(title, author, dataSource); finish(); } } }); Button cancel = ((Button) findViewById(R.id.CancelButton)); cancel.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { finish(); } }); } private void createC2BSkeleton(String title, String author, String media) { String c2bDirStr = "/sdcard/c2b/"; String sanitizedTitle = title.replaceAll("'", " "); String sanitizedAuthor = author.replaceAll("'", " "); String filename = sanitizedTitle.replaceAll("[^a-zA-Z0-9,\\s]", ""); filename = c2bDirStr + filename + ".c2b"; String contents = "<c2b title='" + title + "' level='1' author='" + author + "' media='" + media + "'></c2b>"; File c2bDir = new File(c2bDirStr); boolean directoryExists = c2bDir.isDirectory(); if (!directoryExists) { c2bDir.mkdir(); } try { FileWriter writer = new FileWriter(filename); writer.write(contents); writer.close(); Toast.makeText(CreateC2BFile.this, getString(R.string.STAGE_CREATED), 5000).show(); } catch (IOException e) { Toast.makeText(CreateC2BFile.this, getString(R.string.NEED_SD_CARD), 30000).show(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import java.util.ArrayList; /** * Adjusts the times for the beat targets using a linear least-squares fit. */ public class BeatTimingsAdjuster { private double[] adjustedBeatTimes; public void setRawBeatTimes(ArrayList<Integer> rawBeatTimes) { double[] beatTimes = new double[rawBeatTimes.size()]; for (int i = 0; i < beatTimes.length; i++) { beatTimes[i] = rawBeatTimes.get(i); } adjustedBeatTimes = new double[beatTimes.length]; double[] beatNumbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; double n = beatNumbers.length; // Some things can be computed once and never computed again double[] beatNumbersXNumbers = multiplyArrays(beatNumbers, beatNumbers); double sumOfBeatNumbersXNumbers = sum(beatNumbersXNumbers); double sumOfBeatNumbers = sum(beatNumbers); // The divisor is: // (n * sum(beatNumbersXNumbers) - (sum(beatNumbers) * sum(beatNumbers))) // Since these are all constants, they can be computed first for better // efficiency. double divisor = (n * sum(beatNumbersXNumbers) - (sum(beatNumbers) * sum(beatNumbers))); // Not enough data to adjust for the first 5 beats for (int i = 0; (i < beatTimes.length) && (i < 5); i++) { adjustedBeatTimes[i] = beatTimes[i]; } // Adjust time for beat i by using timings for beats i-5 through i+5 double[] beatWindow = new double[beatNumbers.length]; for (int i = 0; i < beatTimes.length - 10; i++) { System.arraycopy(beatTimes, i, beatWindow, 0, beatNumbers.length); double[] beatNumbersXTimes = multiplyArrays(beatNumbers, beatWindow); double a = (sum(beatTimes) * sumOfBeatNumbersXNumbers - sumOfBeatNumbers * sum(beatNumbersXTimes)) / divisor; double b = (n * sum(beatNumbersXTimes) - sumOfBeatNumbers * sum(beatTimes)) / divisor; adjustedBeatTimes[i + 5] = a + b * beatNumbers[5]; } if (beatTimes.length - 10 < 0) { return; } // Not enough data to adjust for the last 5 beats for (int i = beatTimes.length - 10; i < beatTimes.length; i++) { adjustedBeatTimes[i] = beatTimes[i]; } } public ArrayList<Target> adjustBeatTargets(ArrayList<Target> rawTargets) { ArrayList<Target> adjustedTargets = new ArrayList<Target>(); int j = 0; double threshold = 200; for (int i = 0; i < rawTargets.size(); i++) { Target t = rawTargets.get(i); while ((j < adjustedBeatTimes.length) && (adjustedBeatTimes[j] < t.time)) { j++; } double prevTime = 0; if (j > 0) { prevTime = adjustedBeatTimes[j - 1]; } double postTime = -1; if (j < adjustedBeatTimes.length) { postTime = adjustedBeatTimes[j]; } if ((Math.abs(t.time - prevTime) < Math.abs(t.time - postTime)) && Math.abs(t.time - prevTime) < threshold) { t.time = prevTime; } else if ((Math.abs(t.time - prevTime) > Math.abs(t.time - postTime)) && Math.abs(t.time - postTime) < threshold) { t.time = postTime; } adjustedTargets.add(t); } return adjustedTargets; } private double sum(double[] numbers) { double sum = 0; for (int i = 0; i < numbers.length; i++) { sum = sum + numbers[i]; } return sum; } private double[] multiplyArrays(double[] numberSetA, double[] numberSetB) { double[] sqArray = new double[numberSetA.length]; for (int i = 0; i < numberSetA.length; i++) { sqArray[i] = numberSetA[i] * numberSetB[i]; } return sqArray; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnErrorListener; import android.media.MediaPlayer.OnPreparedListener; import android.net.Uri; import android.os.Bundle; import android.widget.FrameLayout; import android.widget.Toast; import android.widget.VideoView; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; /** * A rhythm/music game for Android that can use any video as the background. */ public class C2B extends Activity { public static final int GAME_MODE = 0; public static final int TWOPASS_MODE = 1; public static final int ONEPASS_MODE = 2; public int mode; public boolean wasEditMode; private boolean forceEditMode; private VideoView background; private GameView foreground; private FrameLayout layout; private String c2bFileName; private String[] filenames; private String marketId; // These are parsed in from the C2B file private String title; private String author; private String level; private String media; private Uri videoUri; public ArrayList<Target> targets; public ArrayList<Integer> beatTimes; private BeatTimingsAdjuster timingAdjuster; private boolean busyProcessing; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); UpdateChecker checker = new UpdateChecker(); int latestVersion = checker.getLatestVersionCode(); String packageName = C2B.class.getPackage().getName(); int currentVersion = 0; try { currentVersion = getPackageManager().getPackageInfo(packageName, 0).versionCode; } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (latestVersion > currentVersion){ marketId = checker.marketId; displayUpdateMessage(); } else { resetGame(); } } private void resetGame() { targets = new ArrayList<Target>(); mode = GAME_MODE; forceEditMode = false; wasEditMode = false; busyProcessing = false; c2bFileName = ""; title = ""; author = ""; level = ""; media = ""; background = null; foreground = null; layout = null; background = new VideoView(this); foreground = new GameView(this); layout = new FrameLayout(this); layout.addView(background); layout.setPadding(30, 0, 0, 0); // Is there a better way to do layout? beatTimes = null; timingAdjuster = null; background.setOnPreparedListener(new OnPreparedListener() { public void onPrepared(MediaPlayer mp) { background.start(); } }); background.setOnErrorListener(new OnErrorListener() { public boolean onError(MediaPlayer arg0, int arg1, int arg2) { background.setVideoURI(videoUri); return true; } }); background.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { if (mode == ONEPASS_MODE) { Toast waitMessage = Toast.makeText(C2B.this, getString(R.string.PROCESSING), 5000); waitMessage.show(); (new Thread(new BeatsWriter())).start(); } else if (mode == TWOPASS_MODE) { mode = ONEPASS_MODE; (new Thread(new BeatsTimingAdjuster())).start(); displayCreateLevelInfo(); return; } displayStats(); } }); layout.addView(foreground); setContentView(layout); setVolumeControlStream(AudioManager.STREAM_MUSIC); displayStartupMessage(); } private void writeC2BFile(String filename) { String contents = "<c2b title='" + title + "' level='" + level + "' author='" + author + "' media='" + media + "'>"; ArrayList<Target> targets = foreground.recordedTargets; if (timingAdjuster != null) { targets = timingAdjuster.adjustBeatTargets(foreground.recordedTargets); } for (int i = 0; i < targets.size(); i++) { Target t = targets.get(i); contents = contents + "<beat time='" + Double.toString(t.time) + "' "; contents = contents + "x='" + Integer.toString(t.x) + "' "; contents = contents + "y='" + Integer.toString(t.y) + "' "; contents = contents + "color='" + Integer.toHexString(t.color) + "'/>"; } contents = contents + "</c2b>"; try { FileWriter writer = new FileWriter(filename); writer.write(contents); writer.close(); } catch (IOException e) { // TODO(clchen): Do better error handling here e.printStackTrace(); } } private void loadC2B(String fileUriString) { try { FileInputStream fis = new FileInputStream(fileUriString); DocumentBuilder docBuild; docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document c2b = docBuild.parse(fis); runC2B(c2b); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void runC2B(Document c2b) { Node root = c2b.getElementsByTagName("c2b").item(0); title = root.getAttributes().getNamedItem("title").getNodeValue(); author = root.getAttributes().getNamedItem("author").getNodeValue(); level = root.getAttributes().getNamedItem("level").getNodeValue(); media = root.getAttributes().getNamedItem("media").getNodeValue(); NodeList beats = c2b.getElementsByTagName("beat"); targets = new ArrayList<Target>(); for (int i = 0; i < beats.getLength(); i++) { NamedNodeMap attribs = beats.item(i).getAttributes(); double time = Double.parseDouble(attribs.getNamedItem("time").getNodeValue()); int x = Integer.parseInt(attribs.getNamedItem("x").getNodeValue()); int y = Integer.parseInt(attribs.getNamedItem("y").getNodeValue()); String colorStr = attribs.getNamedItem("color").getNodeValue(); targets.add(new Target(time, x, y, colorStr)); } if ((beats.getLength() == 0) || forceEditMode) { displayCreateLevelAlert(); } else { videoUri = Uri.parse(media); background.setVideoURI(videoUri); } } private void displayCreateLevelAlert() { mode = ONEPASS_MODE; Builder createLevelAlert = new Builder(this); String titleText = getString(R.string.NO_BEATS) + " \"" + title + "\""; createLevelAlert.setTitle(titleText); String[] choices = new String[2]; choices[0] = getString(R.string.ONE_PASS); choices[1] = getString(R.string.TWO_PASS); createLevelAlert.setSingleChoiceItems(choices, 0, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which == 0) { mode = ONEPASS_MODE; } else { mode = TWOPASS_MODE; } } }); createLevelAlert.setPositiveButton("Ok", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayCreateLevelAlert(); return; } wasEditMode = true; if (mode == TWOPASS_MODE) { beatTimes = new ArrayList<Integer>(); timingAdjuster = new BeatTimingsAdjuster(); } displayCreateLevelInfo(); } }); createLevelAlert.setNegativeButton("Cancel", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayCreateLevelAlert(); return; } displayC2BFiles(); } }); createLevelAlert.setCancelable(false); createLevelAlert.show(); } private void displayC2BFiles() { Builder c2bFilesAlert = new Builder(this); String titleText = getString(R.string.CHOOSE_STAGE); c2bFilesAlert.setTitle(titleText); File c2bDir = new File("/sdcard/c2b/"); filenames = c2bDir.list(new FilenameFilter() { public boolean accept(File dir, String filename) { return filename.endsWith(".c2b"); } }); if (filenames == null) { displayNoFilesMessage(); return; } if (filenames.length == 0) { displayNoFilesMessage(); return; } c2bFilesAlert.setSingleChoiceItems(filenames, -1, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { c2bFileName = "/sdcard/c2b/" + filenames[which]; } }); c2bFilesAlert.setPositiveButton("Go!", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { loadC2B(c2bFileName); dialog.dismiss(); } }); /* c2bFilesAlert.setNeutralButton("Set new beats", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); displaySetNewBeatsConfirmation(); } }); */ final Activity self = this; c2bFilesAlert.setNeutralButton(getString(R.string.MOAR_STAGES), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"); i.setComponent(comp); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat/files"); i.setData(uri); self.startActivity(i); finish(); } }); c2bFilesAlert.setNegativeButton(getString(R.string.QUIT), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); c2bFilesAlert.setCancelable(false); c2bFilesAlert.show(); } /* private void displaySetNewBeatsConfirmation() { Builder setNewBeatsConfirmation = new Builder(this); String titleText = getString(R.string.EDIT_CONFIRMATION); setNewBeatsConfirmation.setTitle(titleText); String message = getString(R.string.EDIT_WARNING); setNewBeatsConfirmation.setMessage(message); setNewBeatsConfirmation.setPositiveButton("Continue", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { forceEditMode = true; loadC2B(c2bFileName); dialog.dismiss(); } }); setNewBeatsConfirmation.setNegativeButton("Cancel", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { displayC2BFiles(); dialog.dismiss(); } }); setNewBeatsConfirmation.setCancelable(false); setNewBeatsConfirmation.show(); } */ private void displayCreateLevelInfo() { Builder createLevelInfoAlert = new Builder(this); String titleText = getString(R.string.BEAT_SETTING_INFO); createLevelInfoAlert.setTitle(titleText); String message = ""; if (mode == TWOPASS_MODE) { message = getString(R.string.TWO_PASS_INFO); } else { message = getString(R.string.ONE_PASS_INFO); } createLevelInfoAlert.setMessage(message); createLevelInfoAlert.setPositiveButton("Start", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); videoUri = Uri.parse(media); background.setVideoURI(videoUri); } }); createLevelInfoAlert.setCancelable(false); createLevelInfoAlert.show(); } private void displayStats() { Builder statsAlert = new Builder(this); String titleText = ""; if (!wasEditMode) { titleText = "Game Over"; } else { titleText = "Stage created!"; } statsAlert.setTitle(titleText); int longestCombo = foreground.longestCombo; if (foreground.comboCount > longestCombo) { longestCombo = foreground.comboCount; } String message = ""; if (!wasEditMode) { message = "Longest combo: " + Integer.toString(longestCombo); } else { message = "Beats recorded!"; } statsAlert.setMessage(message); statsAlert.setPositiveButton("Play", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayStats(); return; } resetGame(); } }); statsAlert.setNegativeButton("Quit", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayStats(); return; } finish(); } }); statsAlert.setCancelable(false); statsAlert.show(); } private void displayNoFilesMessage() { Builder noFilesMessage = new Builder(this); String titleText = getString(R.string.NO_STAGES_FOUND); noFilesMessage.setTitle(titleText); String message = getString(R.string.NO_STAGES_INFO); noFilesMessage.setMessage(message); noFilesMessage.setPositiveButton(getString(R.string.SHUT_UP), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { loadHardCodedRickroll(); } }); final Activity self = this; noFilesMessage.setNeutralButton(getString(R.string.ILL_GET_STAGES), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"); i.setComponent(comp); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat/files"); i.setData(uri); self.startActivity(i); finish(); } }); noFilesMessage.setNegativeButton(getString(R.string.QUIT), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); noFilesMessage.setCancelable(false); noFilesMessage.show(); } private void loadHardCodedRickroll() { try { Resources res = getResources(); InputStream fis = res.openRawResource(R.raw.rickroll); DocumentBuilder docBuild; docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document c2b = docBuild.parse(fis); runC2B(c2b); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void displayStartupMessage() { Builder startupMessage = new Builder(this); String titleText = getString(R.string.WELCOME); startupMessage.setTitle(titleText); String message = getString(R.string.BETA_MESSAGE); startupMessage.setMessage(message); startupMessage.setPositiveButton(getString(R.string.START_GAME), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { displayC2BFiles(); } }); final Activity self = this; startupMessage.setNeutralButton(getString(R.string.VISIT_WEBSITE), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"); i.setComponent(comp); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat"); i.setData(uri); self.startActivity(i); finish(); } }); startupMessage.setNegativeButton(getString(R.string.QUIT), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); startupMessage.setCancelable(false); startupMessage.show(); } private void displayUpdateMessage() { Builder updateMessage = new Builder(this); String titleText = getString(R.string.UPDATE_AVAILABLE); updateMessage.setTitle(titleText); String message = getString(R.string.UPDATE_MESSAGE); updateMessage.setMessage(message); updateMessage.setPositiveButton("Yes", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Uri marketUri = Uri.parse("market://details?id=" + marketId); Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri); startActivity(marketIntent); finish(); } }); final Activity self = this; updateMessage.setNegativeButton("No", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { resetGame(); } }); updateMessage.setCancelable(false); updateMessage.show(); } public int getCurrentTime() { try { return background.getCurrentPosition(); } catch (IllegalStateException e) { // This will be thrown if the player is exiting mid-game and the video // view is going away at the same time as the foreground is trying to get // the position. This error can be safely ignored without doing anything. e.printStackTrace(); return 0; } } // Do beats processing in another thread to avoid hogging the UI thread and // generating a "not responding" error public class BeatsWriter implements Runnable { public void run() { writeC2BFile(c2bFileName); busyProcessing = false; } } public class BeatsTimingAdjuster implements Runnable { public void run() { timingAdjuster.setRawBeatTimes(beatTimes); busyProcessing = false; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.media.AudioManager; import android.media.SoundPool; import android.os.Vibrator; import android.view.MotionEvent; import android.view.View; import java.util.ArrayList; /** * Draws the beat targets and takes user input. * This view is used as the foreground; the background is the video * being played. */ public class GameView extends View { private static final long[] VIBE_PATTERN = {0, 1, 40, 41}; private static final int INTERVAL = 10; // in ms private static final int PRE_THRESHOLD = 1000; // in ms private static final int POST_THRESHOLD = 500; // in ms private static final int TOLERANCE = 100; // in ms private static final int POINTS_FOR_PERFECT = 100; private static final double PENALTY_FACTOR = .25; private static final double COMBO_FACTOR = .1; private static final float TARGET_RADIUS = 50; public static final String LAST_RATING_OK = "(^_')"; public static final String LAST_RATING_PERFECT = "(^_^)/"; public static final String LAST_RATING_MISS = "(X_X)"; private C2B parent; private Vibrator vibe; private SoundPool snd; private int hitOkSfx; private int hitPerfectSfx; private int missSfx; public int comboCount; public int longestCombo; public String lastRating; Paint innerPaint; Paint borderPaint; Paint haloPaint; private ArrayList<Target> drawnTargets; private int lastTarget; public ArrayList<Target> recordedTargets; private int score; public GameView(Context context) { super(context); parent = (C2B) context; lastTarget = 0; score = 0; comboCount = 0; longestCombo = 0; lastRating = ""; drawnTargets = new ArrayList<Target>(); recordedTargets = new ArrayList<Target>(); vibe = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); snd = new SoundPool(10, AudioManager.STREAM_SYSTEM, 0); missSfx = snd.load(context, R.raw.miss, 0); hitOkSfx = snd.load(context, R.raw.ok, 0); hitPerfectSfx = snd.load(context, R.raw.perfect, 0); innerPaint = new Paint(); innerPaint.setColor(Color.argb(127, 0, 0, 0)); innerPaint.setStyle(Paint.Style.FILL); borderPaint = new Paint(); borderPaint.setStyle(Paint.Style.STROKE); borderPaint.setAntiAlias(true); borderPaint.setStrokeWidth(2); haloPaint = new Paint(); haloPaint.setStyle(Paint.Style.STROKE); haloPaint.setAntiAlias(true); haloPaint.setStrokeWidth(4); Thread monitorThread = (new Thread(new Monitor())); monitorThread.setPriority(Thread.MIN_PRIORITY); monitorThread.start(); } private void updateTargets() { int i = lastTarget; int currentTime = parent.getCurrentTime(); // Add any targets that are within the pre-threshold to the list of // drawnTargets boolean cont = true; while (cont && (i < parent.targets.size())) { if (parent.targets.get(i).time < currentTime + PRE_THRESHOLD) { drawnTargets.add(parent.targets.get(i)); i++; } else { cont = false; } } lastTarget = i; // Move any expired targets out of drawn targets for (int j = 0; j < drawnTargets.size(); j++) { Target t = drawnTargets.get(j); if (t == null) { // Do nothing - this is a concurrency issue where // the target is already gone, so just ignore it } else if (t.time + POST_THRESHOLD < currentTime) { try { drawnTargets.remove(j); } catch (IndexOutOfBoundsException e){ // Do nothing here, j is already gone } if (longestCombo < comboCount) { longestCombo = comboCount; } comboCount = 0; lastRating = LAST_RATING_MISS; } } } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { int currentTime = parent.getCurrentTime(); float x = event.getX(); float y = event.getY(); boolean hadHit = false; if (parent.mode == C2B.ONEPASS_MODE) { // Record this point as a target hadHit = true; snd.play(hitPerfectSfx, 1, 1, 0, 0, 1); Target targ = new Target(currentTime, (int) x, (int) y, ""); recordedTargets.add(targ); } else if (parent.mode == C2B.TWOPASS_MODE) { hadHit = true; parent.beatTimes.add(currentTime); } else { // Play the game normally for (int i = 0; i < drawnTargets.size(); i++) { if (hitTarget(x, y, drawnTargets.get(i))) { Target t = drawnTargets.get(i); int points; double timeDiff = Math.abs(currentTime - t.time); if (timeDiff < TOLERANCE) { points = POINTS_FOR_PERFECT; snd.play(hitPerfectSfx, 1, 1, 0, 0, 1); lastRating = LAST_RATING_PERFECT; } else { points = (int) (POINTS_FOR_PERFECT - (timeDiff * PENALTY_FACTOR)); points = points + (int) (points * (comboCount * COMBO_FACTOR)); snd.play(hitOkSfx, 1, 1, 0, 0, 1); lastRating = LAST_RATING_OK; } if (points > 0) { score = score + points; hadHit = true; } drawnTargets.remove(i); break; } } } if (hadHit) { comboCount++; } else { if (longestCombo < comboCount) { longestCombo = comboCount; } comboCount = 0; snd.play(missSfx, 1, 1, 0, 0, 1); lastRating = LAST_RATING_MISS; } vibe.vibrate(VIBE_PATTERN, -1); } return true; } private boolean hitTarget(float x, float y, Target t) { if (t == null) { return false; } // Use the pythagorean theorem to solve this. float xSquared = (t.x - x) * (t.x - x); float ySquared = (t.y - y) * (t.y - y); if ((xSquared + ySquared) < (TARGET_RADIUS * TARGET_RADIUS)) { return true; } return false; } @Override public void onDraw(Canvas canvas) { if (parent.mode != C2B.GAME_MODE) { return; } int currentTime = parent.getCurrentTime(); // Draw the circles for (int i = 0; i < drawnTargets.size(); i++) { Target t = drawnTargets.get(i); if (t == null) { break; } // Insides should be semi-transparent canvas.drawCircle(t.x, t.y, TARGET_RADIUS, innerPaint); // Set colors for the target borderPaint.setColor(t.color); haloPaint.setColor(t.color); // Perfect timing == hitting the halo inside the borders canvas.drawCircle(t.x, t.y, TARGET_RADIUS - 5, borderPaint); canvas.drawCircle(t.x, t.y, TARGET_RADIUS, borderPaint); // Draw timing halos - may need to change the formula here float percentageOff = ((float) (t.time - currentTime)) / PRE_THRESHOLD; int haloSize = (int) (TARGET_RADIUS + (percentageOff * TARGET_RADIUS)); canvas.drawCircle(t.x, t.y, haloSize, haloPaint); } // Score and Combo info String scoreText = "Score: " + Integer.toString(score); int x = getWidth() - 100; // Fudge factor for making it on the top right // corner int y = 30; Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.RED); paint.setTextAlign(Paint.Align.CENTER); paint.setTextSize(24); paint.setTypeface(Typeface.DEFAULT_BOLD); y -= paint.ascent() / 2; canvas.drawText(scoreText, x, y, paint); x = getWidth() / 2; canvas.drawText(lastRating, x, y, paint); String comboText = "Combo: " + Integer.toString(comboCount); x = 60; canvas.drawText(comboText, x, y, paint); } private class Monitor implements Runnable { public void run() { while (true) { try { Thread.sleep(INTERVAL); } catch (InterruptedException e) { // This should not be interrupted. If it is, just dump the stack // trace. e.printStackTrace(); } updateTargets(); postInvalidate(); } } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.zip.ZipFile; public class Unzipper { public static String download(String fileUrl) { URLConnection cn; try { fileUrl = (new URL(new URL(fileUrl), fileUrl)).toString(); URL url = new URL(fileUrl); cn = url.openConnection(); cn.connect(); InputStream stream = cn.getInputStream(); File outputDir = new File("/sdcard/c2b/"); outputDir.mkdirs(); String filename = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); filename = filename.substring(0, filename.indexOf("c2b.zip") + 7); File outputFile = new File("/sdcard/c2b/", filename); outputFile.createNewFile(); FileOutputStream out = new FileOutputStream(outputFile); byte buf[] = new byte[16384]; do { int numread = stream.read(buf); if (numread <= 0) { break; } else { out.write(buf, 0, numread); } } while (true); stream.close(); out.close(); return "/sdcard/c2b/" + filename; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } } public static void unzip(String fileUrl) { try { String filename = download(fileUrl); ZipFile zip = new ZipFile(filename); Enumeration<? extends ZipEntry> zippedFiles = zip.entries(); while (zippedFiles.hasMoreElements()) { ZipEntry entry = zippedFiles.nextElement(); InputStream is = zip.getInputStream(entry); String name = entry.getName(); File outputFile = new File("/sdcard/c2b/" + name); String outputPath = outputFile.getCanonicalPath(); name = outputPath.substring(outputPath.lastIndexOf("/") + 1); outputPath = outputPath.substring(0, outputPath.lastIndexOf("/")); File outputDir = new File(outputPath); outputDir.mkdirs(); outputFile = new File(outputPath, name); outputFile.createNewFile(); FileOutputStream out = new FileOutputStream(outputFile); byte buf[] = new byte[16384]; do { int numread = is.read(buf); if (numread <= 0) { break; } else { out.write(buf, 0, numread); } } while (true); is.close(); out.close(); } File theZipFile = new File(filename); theZipFile.delete(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import javax.microedition.khronos.opengles.GL10; public class Sphere extends Shape { public Sphere(boolean emitTextureCoordinates, boolean emitNormals, boolean emitColors) { super(GL10.GL_TRIANGLES, GL10.GL_UNSIGNED_SHORT, emitTextureCoordinates, emitNormals, emitColors); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TimeZone; /** * A class representing a city, with an associated position, time zone name, * and raw offset from UTC. */ public class City implements Comparable<City> { private static Map<String,City> cities = new HashMap<String,City>(); private static City[] citiesByRawOffset; private String name; private String timeZoneID; private TimeZone timeZone = null; private int rawOffset; private float latitude, longitude; private float x, y, z; /** * Loads the city database. The cities must be stored in order by raw * offset from UTC. */ public static void loadCities(InputStream is) throws IOException { DataInputStream dis = new DataInputStream(is); int numCities = dis.readInt(); citiesByRawOffset = new City[numCities]; byte[] buf = new byte[24]; for (int i = 0; i < numCities; i++) { String name = dis.readUTF(); String tzid = dis.readUTF(); dis.read(buf); // The code below is a faster version of: // int rawOffset = dis.readInt(); // float latitude = dis.readFloat(); // float longitude = dis.readFloat(); // float cx = dis.readFloat(); // float cy = dis.readFloat(); // float cz = dis.readFloat(); int rawOffset = (buf[ 0] << 24) | ((buf[ 1] & 0xff) << 16) | ((buf[ 2] & 0xff) << 8) | (buf[ 3] & 0xff); int ilat = (buf[ 4] << 24) | ((buf[ 5] & 0xff) << 16) | ((buf[ 6] & 0xff) << 8) | (buf[ 7] & 0xff); int ilon = (buf[ 8] << 24) | ((buf[ 9] & 0xff) << 16) | ((buf[10] & 0xff) << 8) | (buf[11] & 0xff); int icx = (buf[12] << 24) | ((buf[13] & 0xff) << 16) | ((buf[14] & 0xff) << 8) | (buf[15] & 0xff); int icy = (buf[16] << 24) | ((buf[17] & 0xff) << 16) | ((buf[18] & 0xff) << 8) | (buf[19] & 0xff); int icz = (buf[20] << 24) | ((buf[21] & 0xff) << 16) | ((buf[22] & 0xff) << 8) | (buf[23] & 0xff); float latitude = Float.intBitsToFloat(ilat); float longitude = Float.intBitsToFloat(ilon); float cx = Float.intBitsToFloat(icx); float cy = Float.intBitsToFloat(icy); float cz = Float.intBitsToFloat(icz); City city = new City(name, tzid, rawOffset, latitude, longitude, cx, cy, cz); cities.put(name, city); citiesByRawOffset[i] = city; } } /** * Returns the cities, ordered by name. */ public static City[] getCitiesByName() { City[] ocities = cities.values().toArray(new City[0]); Arrays.sort(ocities); return ocities; } /** * Returns the cities, ordered by offset, accounting for summer/daylight * savings time. This requires reading the entire time zone database * behind the scenes. */ public static City[] getCitiesByOffset() { City[] ocities = cities.values().toArray(new City[0]); Arrays.sort(ocities, new Comparator<City>() { public int compare(City c1, City c2) { long now = System.currentTimeMillis(); TimeZone tz1 = c1.getTimeZone(); TimeZone tz2 = c2.getTimeZone(); int off1 = tz1.getOffset(now); int off2 = tz2.getOffset(now); if (off1 == off2) { float dlat = c2.getLatitude() - c1.getLatitude(); if (dlat < 0.0f) return -1; if (dlat > 0.0f) return 1; return 0; } return off1 - off2; } }); return ocities; } /** * Returns the cities, ordered by offset, accounting for summer/daylight * savings time. This does not require reading the time zone database * since the cities are pre-sorted. */ public static City[] getCitiesByRawOffset() { return citiesByRawOffset; } /** * Returns an Iterator over all cities, in raw offset order. */ public static Iterator<City> iterator() { return cities.values().iterator(); } /** * Returns the total number of cities. */ public static int numCities() { return cities.size(); } /** * Constructs a city with the given name, time zone name, raw offset, * latitude, longitude, and 3D (X, Y, Z) coordinate. */ public City(String name, String timeZoneID, int rawOffset, float latitude, float longitude, float x, float y, float z) { this.name = name; this.timeZoneID = timeZoneID; this.rawOffset = rawOffset; this.latitude = latitude; this.longitude = longitude; this.x = x; this.y = y; this.z = z; } public String getName() { return name; } public TimeZone getTimeZone() { if (timeZone == null) { timeZone = TimeZone.getTimeZone(timeZoneID); } return timeZone; } public float getLongitude() { return longitude; } public float getLatitude() { return latitude; } public float getX() { return x; } public float getY() { return y; } public float getZ() { return z; } public float getRawOffset() { return rawOffset / 3600000.0f; } public int getRawOffsetMillis() { return rawOffset; } /** * Returns this city's offset from UTC, taking summer/daylight savigns * time into account. */ public float getOffset() { long now = System.currentTimeMillis(); if (timeZone == null) { timeZone = TimeZone.getTimeZone(timeZoneID); } return timeZone.getOffset(now) / 3600000.0f; } /** * Compares this city to another by name. */ public int compareTo(City o) { return name.compareTo(o.name); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.text.DateFormat; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.text.format.DateUtils; //import android.text.format.DateFormat; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Interpolator; /** * A class that draws an analog clock face with information about the current * time in a given city. */ public class Clock { static final int MILLISECONDS_PER_MINUTE = 60 * 1000; static final int MILLISECONDS_PER_HOUR = 60 * 60 * 1000; private City mCity = null; private long mCitySwitchTime; private long mTime; private float mColorRed = 1.0f; private float mColorGreen = 1.0f; private float mColorBlue = 1.0f; private long mOldOffset; private Interpolator mClockHandInterpolator = new AccelerateDecelerateInterpolator(); public Clock() { // Empty constructor } /** * Adds a line to the given Path. The line extends from * radius r0 to radius r1 about the center point (cx, cy), * at an angle given by pos. * * @param path the Path to draw to * @param radius the radius of the outer rim of the clock * @param pos the angle, with 0 and 1 at 12:00 * @param cx the X coordinate of the clock center * @param cy the Y coordinate of the clock center * @param r0 the starting radius for the line * @param r1 the ending radius for the line */ private static void drawLine(Path path, float radius, float pos, float cx, float cy, float r0, float r1) { float theta = pos * Shape.TWO_PI - Shape.PI_OVER_TWO; float dx = (float) Math.cos(theta); float dy = (float) Math.sin(theta); float p0x = cx + dx * r0; float p0y = cy + dy * r0; float p1x = cx + dx * r1; float p1y = cy + dy * r1; float ox = (p1y - p0y); float oy = -(p1x - p0x); float norm = (radius / 2.0f) / (float) Math.sqrt(ox * ox + oy * oy); ox *= norm; oy *= norm; path.moveTo(p0x - ox, p0y - oy); path.lineTo(p1x - ox, p1y - oy); path.lineTo(p1x + ox, p1y + oy); path.lineTo(p0x + ox, p0y + oy); path.close(); } /** * Adds a vertical arrow to the given Path. * * @param path the Path to draw to */ private static void drawVArrow(Path path, float cx, float cy, float width, float height) { path.moveTo(cx - width / 2.0f, cy); path.lineTo(cx, cy + height); path.lineTo(cx + width / 2.0f, cy); path.close(); } /** * Adds a horizontal arrow to the given Path. * * @param path the Path to draw to */ private static void drawHArrow(Path path, float cx, float cy, float width, float height) { path.moveTo(cx, cy - height / 2.0f); path.lineTo(cx + width, cy); path.lineTo(cx, cy + height / 2.0f); path.close(); } /** * Returns an offset in milliseconds to be subtracted from the current time * in order to obtain an smooth interpolation between the previously * displayed time and the current time. */ private long getOffset(float lerp) { long doffset = (long) (mCity.getOffset() * (float) MILLISECONDS_PER_HOUR - mOldOffset); int sign; if (doffset < 0) { doffset = -doffset; sign = -1; } else { sign = 1; } while (doffset > 12L * MILLISECONDS_PER_HOUR) { doffset -= 12L * MILLISECONDS_PER_HOUR; } if (doffset > 6L * MILLISECONDS_PER_HOUR) { doffset = 12L * MILLISECONDS_PER_HOUR - doffset; sign = -sign; } // Interpolate doffset towards 0 doffset = (long)((1.0f - lerp)*doffset); // Keep the same seconds count long dh = doffset / (MILLISECONDS_PER_HOUR); doffset -= dh * MILLISECONDS_PER_HOUR; long dm = doffset / MILLISECONDS_PER_MINUTE; doffset = sign * (60 * dh + dm) * MILLISECONDS_PER_MINUTE; return doffset; } /** * Set the city to be displayed. setCity(null) resets things so the clock * hand animation won't occur next time. */ public void setCity(City city) { if (mCity != city) { if (mCity != null) { mOldOffset = (long) (mCity.getOffset() * (float) MILLISECONDS_PER_HOUR); } else if (city != null) { mOldOffset = (long) (city.getOffset() * (float) MILLISECONDS_PER_HOUR); } else { mOldOffset = 0L; // this will never be used } this.mCitySwitchTime = System.currentTimeMillis(); this.mCity = city; } } public void setTime(long time) { this.mTime = time; } /** * Draws the clock face. * * @param canvas the Canvas to draw to * @param cx the X coordinate of the clock center * @param cy the Y coordinate of the clock center * @param radius the radius of the clock face * @param alpha the translucency of the clock face * @param textAlpha the translucency of the text * @param showCityName if true, display the city name * @param showTime if true, display the time digitally * @param showUpArrow if true, display an up arrow * @param showDownArrow if true, display a down arrow * @param showLeftRightArrows if true, display left and right arrows * @param prefixChars number of characters of the city name to draw in bold */ public void drawClock(Canvas canvas, float cx, float cy, float radius, float alpha, float textAlpha, boolean showCityName, boolean showTime, boolean showUpArrow, boolean showDownArrow, boolean showLeftRightArrows, int prefixChars) { Paint paint = new Paint(); paint.setAntiAlias(true); int iradius = (int)radius; TimeZone tz = mCity.getTimeZone(); // Compute an interpolated time to animate between the previously // displayed time and the current time float lerp = Math.min(1.0f, (System.currentTimeMillis() - mCitySwitchTime) / 500.0f); lerp = mClockHandInterpolator.getInterpolation(lerp); long doffset = lerp < 1.0f ? getOffset(lerp) : 0L; // Determine the interpolated time for the given time zone Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(mTime - doffset); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); int milli = cal.get(Calendar.MILLISECOND); float offset = tz.getRawOffset() / (float) MILLISECONDS_PER_HOUR; float daylightOffset = tz.inDaylightTime(new Date(mTime)) ? tz.getDSTSavings() / (float) MILLISECONDS_PER_HOUR : 0.0f; float absOffset = offset < 0 ? -offset : offset; int offsetH = (int) absOffset; int offsetM = (int) (60.0f * (absOffset - offsetH)); hour %= 12; // Get the city name and digital time strings String cityName = mCity.getName(); cal.setTimeInMillis(mTime); //java.text.DateFormat mTimeFormat = android.text.format.DateFormat.getTimeFormat(this.getApplicationContext()); DateFormat mTimeFormat = DateFormat.getTimeInstance(); String time = mTimeFormat.format(cal.getTimeInMillis()) + " " + DateUtils.getDayOfWeekString(cal.get(Calendar.DAY_OF_WEEK), DateUtils.LENGTH_SHORT) + " " + " (UTC" + (offset >= 0 ? "+" : "-") + offsetH + (offsetM == 0 ? "" : ":" + offsetM) + (daylightOffset == 0 ? "" : "+" + daylightOffset) + ")"; float th = paint.getTextSize(); float tw; // Set the text color paint.setARGB((int) (textAlpha * 255.0f), (int) (mColorRed * 255.0f), (int) (mColorGreen * 255.0f), (int) (mColorBlue * 255.0f)); tw = paint.measureText(cityName); if (showCityName) { // Increment prefixChars to include any spaces for (int i = 0; i < prefixChars; i++) { if (cityName.charAt(i) == ' ') { ++prefixChars; } } // Draw the city name canvas.drawText(cityName, cx - tw / 2, cy - radius - th, paint); // Overstrike the first 'prefixChars' characters canvas.drawText(cityName.substring(0, prefixChars), cx - tw / 2 + 1, cy - radius - th, paint); } tw = paint.measureText(time); if (showTime) { canvas.drawText(time, cx - tw / 2, cy + radius + th + 5, paint); } paint.setARGB((int)(alpha * 255.0f), (int)(mColorRed * 255.0f), (int)(mColorGreen * 255.0f), (int)(mColorBlue * 255.0f)); paint.setStyle(Paint.Style.FILL); canvas.drawOval(new RectF(cx - 2, cy - 2, cx + 2, cy + 2), paint); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(radius * 0.12f); canvas.drawOval(new RectF(cx - iradius, cy - iradius, cx + iradius, cy + iradius), paint); float r0 = radius * 0.1f; float r1 = radius * 0.4f; float r2 = radius * 0.6f; float r3 = radius * 0.65f; float r4 = radius * 0.7f; float r5 = radius * 0.9f; Path path = new Path(); float ss = second + milli / 1000.0f; float mm = minute + ss / 60.0f; float hh = hour + mm / 60.0f; // Tics for the hours for (int i = 0; i < 12; i++) { drawLine(path, radius * 0.12f, i / 12.0f, cx, cy, r4, r5); } // Hour hand drawLine(path, radius * 0.12f, hh / 12.0f, cx, cy, r0, r1); // Minute hand drawLine(path, radius * 0.12f, mm / 60.0f, cx, cy, r0, r2); // Second hand drawLine(path, radius * 0.036f, ss / 60.0f, cx, cy, r0, r3); if (showUpArrow) { drawVArrow(path, cx + radius * 1.13f, cy - radius, radius * 0.15f, -radius * 0.1f); } if (showDownArrow) { drawVArrow(path, cx + radius * 1.13f, cy + radius, radius * 0.15f, radius * 0.1f); } if (showLeftRightArrows) { drawHArrow(path, cx - radius * 1.3f, cy, -radius * 0.1f, radius * 0.15f); drawHArrow(path, cx + radius * 1.3f, cy, radius * 0.1f, radius * 0.15f); } paint.setStyle(Paint.Style.FILL); canvas.drawPath(path, paint); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import javax.microedition.khronos.opengles.GL10; /** * A class representing a set of GL_POINT objects. GlobalTime uses this class * to draw city lights on the night side of the earth. */ public class PointCloud extends Shape { /** * Constructs a PointCloud with a point at each of the given vertex * (x, y, z) positions. * @param vertices an array of (x, y, z) positions given in fixed-point. */ public PointCloud(int[] vertices) { this(vertices, 0, vertices.length); } /** * Constructs a PointCloud with a point at each of the given vertex * (x, y, z) positions. * @param vertices an array of (x, y, z) positions given in fixed-point. * @param off the starting offset of the vertices array * @param len the number of elements of the vertices array to use */ public PointCloud(int[] vertices, int off, int len) { super(GL10.GL_POINTS, GL10.GL_UNSIGNED_SHORT, false, false, false); int numPoints = len / 3; short[] indices = new short[numPoints]; for (int i = 0; i < numPoints; i++) { indices[i] = (short)i; } allocateBuffers(vertices, null, null, null, indices); this.mNumIndices = mIndexBuffer.capacity(); } @Override public int getNumTriangles() { return mNumIndices * 2; } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.opengles.GL10; /** * An abstract superclass for various three-dimensional objects to be drawn * using OpenGL ES. Each subclass is responsible for setting up NIO buffers * containing vertices, texture coordinates, colors, normals, and indices. * The {@link #draw(GL10)} method draws the object to the given OpenGL context. */ public abstract class Shape { public static final int INT_BYTES = 4; public static final int SHORT_BYTES = 2; public static final float DEGREES_TO_RADIANS = (float) Math.PI / 180.0f; public static final float PI = (float) Math.PI; public static final float TWO_PI = (float) (2.0 * Math.PI); public static final float PI_OVER_TWO = (float) (Math.PI / 2.0); protected int mPrimitive; protected int mIndexDatatype; protected boolean mEmitTextureCoordinates; protected boolean mEmitNormals; protected boolean mEmitColors; protected IntBuffer mVertexBuffer; protected IntBuffer mTexcoordBuffer; protected IntBuffer mColorBuffer; protected IntBuffer mNormalBuffer; protected Buffer mIndexBuffer; protected int mNumIndices = -1; /** * Constructs a Shape. * * @param primitive a GL primitive type understood by glDrawElements, * such as GL10.GL_TRIANGLES * @param indexDatatype the GL datatype for the index buffer, such as * GL10.GL_UNSIGNED_SHORT * @param emitTextureCoordinates true to enable use of the texture * coordinate buffer * @param emitNormals true to enable use of the normal buffer * @param emitColors true to enable use of the color buffer */ protected Shape(int primitive, int indexDatatype, boolean emitTextureCoordinates, boolean emitNormals, boolean emitColors) { mPrimitive = primitive; mIndexDatatype = indexDatatype; mEmitTextureCoordinates = emitTextureCoordinates; mEmitNormals = emitNormals; mEmitColors = emitColors; } /** * Converts the given floating-point value to fixed-point. */ public static int toFixed(float x) { return (int) (x * 65536.0); } /** * Converts the given fixed-point value to floating-point. */ public static float toFloat(int x) { return (float) (x / 65536.0); } /** * Computes the cross-product of two vectors p and q and places * the result in out. */ public static void cross(float[] p, float[] q, float[] out) { out[0] = p[1] * q[2] - p[2] * q[1]; out[1] = p[2] * q[0] - p[0] * q[2]; out[2] = p[0] * q[1] - p[1] * q[0]; } /** * Returns the length of a vector, given as three floats. */ public static float length(float vx, float vy, float vz) { return (float) Math.sqrt(vx * vx + vy * vy + vz * vz); } /** * Returns the length of a vector, given as an array of three floats. */ public static float length(float[] v) { return length(v[0], v[1], v[2]); } /** * Normalizes the given vector of three floats to have length == 1.0. * Vectors with length zero are unaffected. */ public static void normalize(float[] v) { float length = length(v); if (length != 0.0f) { float norm = 1.0f / length; v[0] *= norm; v[1] *= norm; v[2] *= norm; } } /** * Returns the number of triangles associated with this shape. */ public int getNumTriangles() { if (mPrimitive == GL10.GL_TRIANGLES) { return mIndexBuffer.capacity() / 3; } else if (mPrimitive == GL10.GL_TRIANGLE_STRIP) { return mIndexBuffer.capacity() - 2; } return 0; } /** * Copies the given data into the instance * variables mVertexBuffer, mTexcoordBuffer, mNormalBuffer, mColorBuffer, * and mIndexBuffer. * * @param vertices an array of fixed-point vertex coordinates * @param texcoords an array of fixed-point texture coordinates * @param normals an array of fixed-point normal vector coordinates * @param colors an array of fixed-point color channel values * @param indices an array of short indices */ public void allocateBuffers(int[] vertices, int[] texcoords, int[] normals, int[] colors, short[] indices) { allocate(vertices, texcoords, normals, colors); ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * SHORT_BYTES); ibb.order(ByteOrder.nativeOrder()); ShortBuffer shortIndexBuffer = ibb.asShortBuffer(); shortIndexBuffer.put(indices); shortIndexBuffer.position(0); this.mIndexBuffer = shortIndexBuffer; } /** * Copies the given data into the instance * variables mVertexBuffer, mTexcoordBuffer, mNormalBuffer, mColorBuffer, * and mIndexBuffer. * * @param vertices an array of fixed-point vertex coordinates * @param texcoords an array of fixed-point texture coordinates * @param normals an array of fixed-point normal vector coordinates * @param colors an array of fixed-point color channel values * @param indices an array of int indices */ public void allocateBuffers(int[] vertices, int[] texcoords, int[] normals, int[] colors, int[] indices) { allocate(vertices, texcoords, normals, colors); ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * INT_BYTES); ibb.order(ByteOrder.nativeOrder()); IntBuffer intIndexBuffer = ibb.asIntBuffer(); intIndexBuffer.put(indices); intIndexBuffer.position(0); this.mIndexBuffer = intIndexBuffer; } /** * Allocate the vertex, texture coordinate, normal, and color buffer. */ private void allocate(int[] vertices, int[] texcoords, int[] normals, int[] colors) { ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * INT_BYTES); vbb.order(ByteOrder.nativeOrder()); mVertexBuffer = vbb.asIntBuffer(); mVertexBuffer.put(vertices); mVertexBuffer.position(0); if ((texcoords != null) && mEmitTextureCoordinates) { ByteBuffer tbb = ByteBuffer.allocateDirect(texcoords.length * INT_BYTES); tbb.order(ByteOrder.nativeOrder()); mTexcoordBuffer = tbb.asIntBuffer(); mTexcoordBuffer.put(texcoords); mTexcoordBuffer.position(0); } if ((normals != null) && mEmitNormals) { ByteBuffer nbb = ByteBuffer.allocateDirect(normals.length * INT_BYTES); nbb.order(ByteOrder.nativeOrder()); mNormalBuffer = nbb.asIntBuffer(); mNormalBuffer.put(normals); mNormalBuffer.position(0); } if ((colors != null) && mEmitColors) { ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * INT_BYTES); cbb.order(ByteOrder.nativeOrder()); mColorBuffer = cbb.asIntBuffer(); mColorBuffer.put(colors); mColorBuffer.position(0); } } /** * Draws the shape to the given OpenGL ES 1.0 context. Texture coordinates, * normals, and colors are emitted according the the preferences set for * this shape. */ public void draw(GL10 gl) { gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); if (mEmitTextureCoordinates) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL10.GL_FIXED, 0, mTexcoordBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } if (mEmitNormals) { gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); gl.glNormalPointer(GL10.GL_FIXED, 0, mNormalBuffer); } else { gl.glDisableClientState(GL10.GL_NORMAL_ARRAY); } if (mEmitColors) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glColorPointer(4, GL10.GL_FIXED, 0, mColorBuffer); } else { gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } gl.glDrawElements(mPrimitive, mNumIndices > 0 ? mNumIndices : mIndexBuffer.capacity(), mIndexDatatype, mIndexBuffer); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import javax.microedition.khronos.opengles.GL10; /** * A class that draws a ring with a given center and inner and outer radii. * The inner and outer rings each have a color and the remaining pixels are * colored by interpolation. GlobalTime uses this class to simulate an * "atmosphere" around the earth. */ public class Annulus extends Shape { /** * Constructs an annulus. * * @param centerX the X coordinate of the center point * @param centerY the Y coordinate of the center point * @param Z the fixed Z for the entire ring * @param innerRadius the inner radius * @param outerRadius the outer radius * @param rInner the red channel of the color of the inner ring * @param gInner the green channel of the color of the inner ring * @param bInner the blue channel of the color of the inner ring * @param aInner the alpha channel of the color of the inner ring * @param rOuter the red channel of the color of the outer ring * @param gOuter the green channel of the color of the outer ring * @param bOuter the blue channel of the color of the outer ring * @param aOuter the alpha channel of the color of the outer ring * @param sectors the number of sectors used to approximate curvature */ public Annulus(float centerX, float centerY, float Z, float innerRadius, float outerRadius, float rInner, float gInner, float bInner, float aInner, float rOuter, float gOuter, float bOuter, float aOuter, int sectors) { super(GL10.GL_TRIANGLES, GL10.GL_UNSIGNED_SHORT, false, false, true); int radii = sectors + 1; int[] vertices = new int[2 * 3 * radii]; int[] colors = new int[2 * 4 * radii]; short[] indices = new short[2 * 3 * radii]; int vidx = 0; int cidx = 0; int iidx = 0; for (int i = 0; i < radii; i++) { float theta = (i * TWO_PI) / (radii - 1); float cosTheta = (float) Math.cos(theta); float sinTheta = (float) Math.sin(theta); vertices[vidx++] = toFixed(centerX + innerRadius * cosTheta); vertices[vidx++] = toFixed(centerY + innerRadius * sinTheta); vertices[vidx++] = toFixed(Z); vertices[vidx++] = toFixed(centerX + outerRadius * cosTheta); vertices[vidx++] = toFixed(centerY + outerRadius * sinTheta); vertices[vidx++] = toFixed(Z); colors[cidx++] = toFixed(rInner); colors[cidx++] = toFixed(gInner); colors[cidx++] = toFixed(bInner); colors[cidx++] = toFixed(aInner); colors[cidx++] = toFixed(rOuter); colors[cidx++] = toFixed(gOuter); colors[cidx++] = toFixed(bOuter); colors[cidx++] = toFixed(aOuter); } for (int i = 0; i < sectors; i++) { indices[iidx++] = (short) (2 * i); indices[iidx++] = (short) (2 * i + 1); indices[iidx++] = (short) (2 * i + 2); indices[iidx++] = (short) (2 * i + 1); indices[iidx++] = (short) (2 * i + 3); indices[iidx++] = (short) (2 * i + 2); } allocateBuffers(vertices, null, null, colors, indices); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import javax.microedition.khronos.egl.*; import javax.microedition.khronos.opengles.*; import android.app.Activity; import android.content.Context; import android.content.res.AssetManager; import android.graphics.Canvas; import android.opengl.Object3D; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.MessageQueue; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; /** * The main View of the GlobalTime Activity. */ class GTView extends SurfaceView implements SurfaceHolder.Callback { /** * A TimeZone object used to compute the current UTC time. */ private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("utc"); /** * The Sun's color is close to that of a 5780K blackbody. */ private static final float[] SUNLIGHT_COLOR = { 1.0f, 0.9375f, 0.91015625f, 1.0f }; /** * The inclination of the earth relative to the plane of the ecliptic * is 23.45 degrees. */ private static final float EARTH_INCLINATION = 23.45f * Shape.PI / 180.0f; /** Seconds in a day */ private static final int SECONDS_PER_DAY = 24 * 60 * 60; /** Flag for the depth test */ private static final boolean PERFORM_DEPTH_TEST= false; /** Use raw time zone offsets, disregarding "summer time." If false, * current offsets will be used, which requires a much longer startup time * in order to sort the city database. */ private static final boolean USE_RAW_OFFSETS = true; /** * The earth's atmosphere. */ private static final Annulus ATMOSPHERE = new Annulus(0.0f, 0.0f, 1.75f, 0.9f, 1.08f, 0.4f, 0.4f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 50); /** * The tesselation of the earth by latitude. */ private static final int SPHERE_LATITUDES = 25; /** * The tesselation of the earth by longitude. */ private static int SPHERE_LONGITUDES = 25; /** * A flattened version of the earth. The normals are computed identically * to those of the round earth, allowing the day/night lighting to be * applied to the flattened surface. */ private static Sphere worldFlat = new LatLongSphere(0.0f, 0.0f, 0.0f, 1.0f, SPHERE_LATITUDES, SPHERE_LONGITUDES, 0.0f, 360.0f, true, true, false, true); /** * The earth. */ private Object3D mWorld; /** * Geometry of the city lights */ private PointCloud mLights; /** * True if the activiy has been initialized. */ boolean mInitialized = false; /** * True if we're in alphabetic entry mode. */ private boolean mAlphaKeySet = false; private EGLContext mEGLContext; private EGLSurface mEGLSurface; private EGLDisplay mEGLDisplay; private EGLConfig mEGLConfig; GLView mGLView; // Rotation and tilt of the Earth private float mRotAngle = 0.0f; private float mTiltAngle = 0.0f; // Rotational velocity of the orbiting viewer private float mRotVelocity = 1.0f; // Rotation of the flat view private float mWrapX = 0.0f; private float mWrapVelocity = 0.0f; private float mWrapVelocityFactor = 0.01f; // Toggle switches private boolean mDisplayAtmosphere = true; private boolean mDisplayClock = false; private boolean mClockShowing = false; private boolean mDisplayLights = false; private boolean mDisplayWorld = true; private boolean mDisplayWorldFlat = false; private boolean mSmoothShading = true; // City search string private String mCityName = ""; // List of all cities private List<City> mClockCities; // List of cities matching a user-supplied prefix private List<City> mCityNameMatches = new ArrayList<City>(); private List<City> mCities; // Start time for clock fade animation private long mClockFadeTime; // Interpolator for clock fade animation private Interpolator mClockSizeInterpolator = new DecelerateInterpolator(1.0f); // Index of current clock private int mCityIndex; // Current clock private Clock mClock; // City-to-city flight animation parameters private boolean mFlyToCity = false; private long mCityFlyStartTime; private float mCityFlightTime; private float mRotAngleStart, mRotAngleDest; private float mTiltAngleStart, mTiltAngleDest; // Interpolator for flight motion animation private Interpolator mFlyToCityInterpolator = new AccelerateDecelerateInterpolator(); private static int sNumLights; private static int[] sLightCoords; // static Map<Float,int[]> cityCoords = new HashMap<Float,int[]>(); // Arrays for GL calls private float[] mClipPlaneEquation = new float[4]; private float[] mLightDir = new float[4]; // Calendar for computing the Sun's position Calendar mSunCal = Calendar.getInstance(UTC_TIME_ZONE); // Triangles drawn per frame private int mNumTriangles; private long startTime; private static final int MOTION_NONE = 0; private static final int MOTION_X = 1; private static final int MOTION_Y = 2; private static final int MIN_MANHATTAN_DISTANCE = 20; private static final float ROTATION_FACTOR = 1.0f / 30.0f; private static final float TILT_FACTOR = 0.35f; // Touchscreen support private float mMotionStartX; private float mMotionStartY; private float mMotionStartRotVelocity; private float mMotionStartTiltAngle; private int mMotionDirection; public void surfaceCreated(SurfaceHolder holder) { EGL10 egl = (EGL10)EGLContext.getEGL(); mEGLSurface = egl.eglCreateWindowSurface(mEGLDisplay, mEGLConfig, this, null); egl.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext); } public void surfaceDestroyed(SurfaceHolder holder) { // nothing to do } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // nothing to do } /** * Set up the view. * * @param context the Context * @param am an AssetManager to retrieve the city database from */ public GTView(Context context) { super(context); getHolder().addCallback(this); getHolder().setType(SurfaceHolder.SURFACE_TYPE_GPU); AssetManager am = context.getAssets(); startTime = System.currentTimeMillis(); EGL10 egl = (EGL10)EGLContext.getEGL(); EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int[] version = new int[2]; egl.eglInitialize(dpy, version); int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_NONE }; EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config); mEGLConfig = configs[0]; mEGLContext = egl.eglCreateContext(dpy, mEGLConfig, EGL10.EGL_NO_CONTEXT, null); mEGLDisplay = dpy; mClock = new Clock(); setFocusable(true); setFocusableInTouchMode(true); requestFocus(); try { loadAssets(am); } catch (IOException ioe) { ioe.printStackTrace(); throw new RuntimeException(ioe); } catch (ArrayIndexOutOfBoundsException aioobe) { aioobe.printStackTrace(); throw new RuntimeException(aioobe); } } /** * Destroy the view. */ public void destroy() { EGL10 egl = (EGL10)EGLContext.getEGL(); egl.eglMakeCurrent(mEGLDisplay, egl.EGL_NO_SURFACE, egl.EGL_NO_SURFACE, egl.EGL_NO_CONTEXT); egl.eglDestroyContext(mEGLDisplay, mEGLContext); egl.eglDestroySurface(mEGLDisplay, mEGLSurface); egl.eglTerminate(mEGLDisplay); mEGLContext = null; } /** * Begin animation. */ public void startAnimating() { mHandler.sendEmptyMessage(INVALIDATE); } /** * Quit animation. */ public void stopAnimating() { mHandler.removeMessages(INVALIDATE); } /** * Read a two-byte integer from the input stream. */ private int readInt16(InputStream is) throws IOException { int lo = is.read(); int hi = is.read(); return (hi << 8) | lo; } /** * Returns the offset from UTC for the given city. If USE_RAW_OFFSETS * is true, summer/daylight savings is ignored. */ private static float getOffset(City c) { return USE_RAW_OFFSETS ? c.getRawOffset() : c.getOffset(); } private InputStream cache(InputStream is) throws IOException { int nbytes = is.available(); byte[] data = new byte[nbytes]; int nread = 0; while (nread < nbytes) { nread += is.read(data, nread, nbytes - nread); } return new ByteArrayInputStream(data); } /** * Load the city and lights databases. * * @param am the AssetManager to load from. */ private void loadAssets(final AssetManager am) throws IOException { Locale locale = Locale.getDefault(); String language = locale.getLanguage(); String country = locale.getCountry(); InputStream cis = null; try { // Look for (e.g.) cities_fr_FR.dat or cities_fr_CA.dat cis = am.open("cities_" + language + "_" + country + ".dat"); } catch (FileNotFoundException e1) { try { // Look for (e.g.) cities_fr.dat or cities_fr.dat cis = am.open("cities_" + language + ".dat"); } catch (FileNotFoundException e2) { try { // Use English city names by default cis = am.open("cities_en.dat"); } catch (FileNotFoundException e3) { throw e3; } } } cis = cache(cis); City.loadCities(cis); City[] cities; if (USE_RAW_OFFSETS) { cities = City.getCitiesByRawOffset(); } else { cities = City.getCitiesByOffset(); } mClockCities = new ArrayList<City>(cities.length); for (int i = 0; i < cities.length; i++) { mClockCities.add(cities[i]); } mCities = mClockCities; mCityIndex = 0; this.mWorld = new Object3D() { @Override public InputStream readFile(String filename) throws IOException { return cache(am.open(filename)); } }; mWorld.load("world.gles"); // lights.dat has the following format. All integers // are 16 bits, low byte first. // // width // height // N [# of lights] // light 0 X [in the range 0 to (width - 1)] // light 0 Y ]in the range 0 to (height - 1)] // light 1 X [in the range 0 to (width - 1)] // light 1 Y ]in the range 0 to (height - 1)] // ... // light (N - 1) X [in the range 0 to (width - 1)] // light (N - 1) Y ]in the range 0 to (height - 1)] // // For a larger number of lights, it could make more // sense to store the light positions in a bitmap // and extract them manually InputStream lis = am.open("lights.dat"); lis = cache(lis); int lightWidth = readInt16(lis); int lightHeight = readInt16(lis); sNumLights = readInt16(lis); sLightCoords = new int[3 * sNumLights]; int lidx = 0; float lightRadius = 1.009f; float lightScale = 65536.0f * lightRadius; float[] cosTheta = new float[lightWidth]; float[] sinTheta = new float[lightWidth]; float twoPi = (float) (2.0 * Math.PI); float scaleW = twoPi / lightWidth; for (int i = 0; i < lightWidth; i++) { float theta = twoPi - i * scaleW; cosTheta[i] = (float)Math.cos(theta); sinTheta[i] = (float)Math.sin(theta); } float[] cosPhi = new float[lightHeight]; float[] sinPhi = new float[lightHeight]; float scaleH = (float) (Math.PI / lightHeight); for (int j = 0; j < lightHeight; j++) { float phi = j * scaleH; cosPhi[j] = (float)Math.cos(phi); sinPhi[j] = (float)Math.sin(phi); } int nbytes = 4 * sNumLights; byte[] ilights = new byte[nbytes]; int nread = 0; while (nread < nbytes) { nread += lis.read(ilights, nread, nbytes - nread); } int idx = 0; for (int i = 0; i < sNumLights; i++) { int lx = (((ilights[idx + 1] & 0xff) << 8) | (ilights[idx ] & 0xff)); int ly = (((ilights[idx + 3] & 0xff) << 8) | (ilights[idx + 2] & 0xff)); idx += 4; float sin = sinPhi[ly]; float x = cosTheta[lx]*sin; float y = cosPhi[ly]; float z = sinTheta[lx]*sin; sLightCoords[lidx++] = (int) (x * lightScale); sLightCoords[lidx++] = (int) (y * lightScale); sLightCoords[lidx++] = (int) (z * lightScale); } mLights = new PointCloud(sLightCoords); } /** * Returns true if two time zone offsets are equal. We assume distinct * time zone offsets will differ by at least a few minutes. */ private boolean tzEqual(float o1, float o2) { return Math.abs(o1 - o2) < 0.001; } /** * Move to a different time zone. * * @param incr The increment between the current and future time zones. */ private void shiftTimeZone(int incr) { // If only 1 city in the current set, there's nowhere to go if (mCities.size() <= 1) { return; } float offset = getOffset(mCities.get(mCityIndex)); do { mCityIndex = (mCityIndex + mCities.size() + incr) % mCities.size(); } while (tzEqual(getOffset(mCities.get(mCityIndex)), offset)); offset = getOffset(mCities.get(mCityIndex)); locateCity(true, offset); goToCity(); } /** * Returns true if there is another city within the current time zone * that is the given increment away from the current city. * * @param incr the increment, +1 or -1 * @return */ private boolean atEndOfTimeZone(int incr) { if (mCities.size() <= 1) { return true; } float offset = getOffset(mCities.get(mCityIndex)); int nindex = (mCityIndex + mCities.size() + incr) % mCities.size(); if (tzEqual(getOffset(mCities.get(nindex)), offset)) { return false; } return true; } /** * Shifts cities within the current time zone. * * @param incr the increment, +1 or -1 */ private void shiftWithinTimeZone(int incr) { float offset = getOffset(mCities.get(mCityIndex)); int nindex = (mCityIndex + mCities.size() + incr) % mCities.size(); if (tzEqual(getOffset(mCities.get(nindex)), offset)) { mCityIndex = nindex; goToCity(); } } /** * Returns true if the city name matches the given prefix, ignoring spaces. */ private boolean nameMatches(City city, String prefix) { String cityName = city.getName().replaceAll("[ ]", ""); return prefix.regionMatches(true, 0, cityName, 0, prefix.length()); } /** * Returns true if there are cities matching the given name prefix. */ private boolean hasMatches(String prefix) { for (int i = 0; i < mClockCities.size(); i++) { City city = mClockCities.get(i); if (nameMatches(city, prefix)) { return true; } } return false; } /** * Shifts to the nearest city that matches the new prefix. */ private void shiftByName() { // Attempt to keep current city if it matches City finalCity = null; City currCity = mCities.get(mCityIndex); if (nameMatches(currCity, mCityName)) { finalCity = currCity; } mCityNameMatches.clear(); for (int i = 0; i < mClockCities.size(); i++) { City city = mClockCities.get(i); if (nameMatches(city, mCityName)) { mCityNameMatches.add(city); } } mCities = mCityNameMatches; if (finalCity != null) { for (int i = 0; i < mCityNameMatches.size(); i++) { if (mCityNameMatches.get(i) == finalCity) { mCityIndex = i; break; } } } else { // Find the closest matching city locateCity(false, 0.0f); } goToCity(); } /** * Increases or decreases the rotational speed of the earth. */ private void incrementRotationalVelocity(float incr) { if (mDisplayWorldFlat) { mWrapVelocity -= incr; } else { mRotVelocity -= incr; } } /** * Clears the current matching prefix, while keeping the focus on * the current city. */ private void clearCityMatches() { // Determine the global city index that matches the current city if (mCityNameMatches.size() > 0) { City city = mCityNameMatches.get(mCityIndex); for (int i = 0; i < mClockCities.size(); i++) { City ncity = mClockCities.get(i); if (city.equals(ncity)) { mCityIndex = i; break; } } } mCityName = ""; mCityNameMatches.clear(); mCities = mClockCities; goToCity(); } /** * Fade the clock in or out. */ private void enableClock(boolean enabled) { mClockFadeTime = System.currentTimeMillis(); mDisplayClock = enabled; mClockShowing = true; mAlphaKeySet = enabled; if (enabled) { // Find the closest matching city locateCity(false, 0.0f); } clearCityMatches(); } /** * Use the touchscreen to alter the rotational velocity or the * tilt of the earth. */ @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mMotionStartX = event.getX(); mMotionStartY = event.getY(); mMotionStartRotVelocity = mDisplayWorldFlat ? mWrapVelocity : mRotVelocity; mMotionStartTiltAngle = mTiltAngle; // Stop the rotation if (mDisplayWorldFlat) { mWrapVelocity = 0.0f; } else { mRotVelocity = 0.0f; } mMotionDirection = MOTION_NONE; break; case MotionEvent.ACTION_MOVE: // Disregard motion events when the clock is displayed float dx = event.getX() - mMotionStartX; float dy = event.getY() - mMotionStartY; float delx = Math.abs(dx); float dely = Math.abs(dy); // Determine the direction of motion (major axis) // Once if has been determined, it's locked in until // we receive ACTION_UP or ACTION_CANCEL if ((mMotionDirection == MOTION_NONE) && (delx + dely > MIN_MANHATTAN_DISTANCE)) { if (delx > dely) { mMotionDirection = MOTION_X; } else { mMotionDirection = MOTION_Y; } } // If the clock is displayed, don't actually rotate or tilt; // just use mMotionDirection to record whether motion occurred if (!mDisplayClock) { if (mMotionDirection == MOTION_X) { if (mDisplayWorldFlat) { mWrapVelocity = mMotionStartRotVelocity + dx * ROTATION_FACTOR; } else { mRotVelocity = mMotionStartRotVelocity + dx * ROTATION_FACTOR; } mClock.setCity(null); } else if (mMotionDirection == MOTION_Y && !mDisplayWorldFlat) { mTiltAngle = mMotionStartTiltAngle + dy * TILT_FACTOR; if (mTiltAngle < -90.0f) { mTiltAngle = -90.0f; } if (mTiltAngle > 90.0f) { mTiltAngle = 90.0f; } mClock.setCity(null); } } break; case MotionEvent.ACTION_UP: mMotionDirection = MOTION_NONE; break; case MotionEvent.ACTION_CANCEL: mTiltAngle = mMotionStartTiltAngle; if (mDisplayWorldFlat) { mWrapVelocity = mMotionStartRotVelocity; } else { mRotVelocity = mMotionStartRotVelocity; } mMotionDirection = MOTION_NONE; break; } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mInitialized && mGLView.processKey(keyCode)) { boolean drawing = (mClockShowing || mGLView.hasMessages()); this.setWillNotDraw(!drawing); return true; } boolean handled = false; // If we're not in alphabetical entry mode, convert letters // to their digit equivalents if (!mAlphaKeySet) { char numChar = event.getNumber(); if (numChar >= '0' && numChar <= '9') { keyCode = KeyEvent.KEYCODE_0 + (numChar - '0'); } } switch (keyCode) { // The 'space' key toggles the clock case KeyEvent.KEYCODE_SPACE: mAlphaKeySet = !mAlphaKeySet; enableClock(mAlphaKeySet); handled = true; break; // The 'left' and 'right' buttons shift time zones if the clock is // displayed, otherwise they alters the rotational speed of the earthh case KeyEvent.KEYCODE_DPAD_LEFT: if (mDisplayClock) { shiftTimeZone(-1); } else { mClock.setCity(null); incrementRotationalVelocity(1.0f); } handled = true; break; case KeyEvent.KEYCODE_DPAD_RIGHT: if (mDisplayClock) { shiftTimeZone(1); } else { mClock.setCity(null); incrementRotationalVelocity(-1.0f); } handled = true; break; // The 'up' and 'down' buttons shift cities within a time zone if the // clock is displayed, otherwise they tilt the earth case KeyEvent.KEYCODE_DPAD_UP: if (mDisplayClock) { shiftWithinTimeZone(-1); } else { mClock.setCity(null); if (!mDisplayWorldFlat) { mTiltAngle += 360.0f / 48.0f; } } handled = true; break; case KeyEvent.KEYCODE_DPAD_DOWN: if (mDisplayClock) { shiftWithinTimeZone(1); } else { mClock.setCity(null); if (!mDisplayWorldFlat) { mTiltAngle -= 360.0f / 48.0f; } } handled = true; break; // The center key stops the earth's rotation, then toggles between the // round and flat views of the earth case KeyEvent.KEYCODE_DPAD_CENTER: if ((!mDisplayWorldFlat && mRotVelocity == 0.0f) || (mDisplayWorldFlat && mWrapVelocity == 0.0f)) { mDisplayWorldFlat = !mDisplayWorldFlat; } else { if (mDisplayWorldFlat) { mWrapVelocity = 0.0f; } else { mRotVelocity = 0.0f; } } handled = true; break; // The 'L' key toggles the city lights case KeyEvent.KEYCODE_L: if (!mAlphaKeySet && !mDisplayWorldFlat) { mDisplayLights = !mDisplayLights; handled = true; } break; // The 'W' key toggles the earth (just for fun) case KeyEvent.KEYCODE_W: if (!mAlphaKeySet && !mDisplayWorldFlat) { mDisplayWorld = !mDisplayWorld; handled = true; } break; // The 'A' key toggles the atmosphere case KeyEvent.KEYCODE_A: if (!mAlphaKeySet && !mDisplayWorldFlat) { mDisplayAtmosphere = !mDisplayAtmosphere; handled = true; } break; // The '2' key zooms out case KeyEvent.KEYCODE_2: if (!mAlphaKeySet && !mDisplayWorldFlat) { mGLView.zoom(-2); handled = true; } break; // The '8' key zooms in case KeyEvent.KEYCODE_8: if (!mAlphaKeySet && !mDisplayWorldFlat) { mGLView.zoom(2); handled = true; } break; } // Handle letters in city names if (!handled && mAlphaKeySet) { switch (keyCode) { // Add a letter to the city name prefix case KeyEvent.KEYCODE_A: case KeyEvent.KEYCODE_B: case KeyEvent.KEYCODE_C: case KeyEvent.KEYCODE_D: case KeyEvent.KEYCODE_E: case KeyEvent.KEYCODE_F: case KeyEvent.KEYCODE_G: case KeyEvent.KEYCODE_H: case KeyEvent.KEYCODE_I: case KeyEvent.KEYCODE_J: case KeyEvent.KEYCODE_K: case KeyEvent.KEYCODE_L: case KeyEvent.KEYCODE_M: case KeyEvent.KEYCODE_N: case KeyEvent.KEYCODE_O: case KeyEvent.KEYCODE_P: case KeyEvent.KEYCODE_Q: case KeyEvent.KEYCODE_R: case KeyEvent.KEYCODE_S: case KeyEvent.KEYCODE_T: case KeyEvent.KEYCODE_U: case KeyEvent.KEYCODE_V: case KeyEvent.KEYCODE_W: case KeyEvent.KEYCODE_X: case KeyEvent.KEYCODE_Y: case KeyEvent.KEYCODE_Z: char c = (char)(keyCode - KeyEvent.KEYCODE_A + 'A'); if (hasMatches(mCityName + c)) { mCityName += c; shiftByName(); } handled = true; break; // Remove a letter from the city name prefix case KeyEvent.KEYCODE_DEL: if (mCityName.length() > 0) { mCityName = mCityName.substring(0, mCityName.length() - 1); shiftByName(); } else { clearCityMatches(); } handled = true; break; // Clear the city name prefix case KeyEvent.KEYCODE_ENTER: clearCityMatches(); handled = true; break; } } boolean drawing = (mClockShowing || ((mGLView != null) && (mGLView.hasMessages()))); this.setWillNotDraw(!drawing); // Let the system handle other keypresses if (!handled) { return super.onKeyDown(keyCode, event); } return true; } /** * Initialize OpenGL ES drawing. */ private synchronized void init(GL10 gl) { mGLView = new GLView(); mGLView.setNearFrustum(5.0f); mGLView.setFarFrustum(50.0f); mGLView.setLightModelAmbientIntensity(0.225f); mGLView.setAmbientIntensity(0.0f); mGLView.setDiffuseIntensity(1.5f); mGLView.setDiffuseColor(SUNLIGHT_COLOR); mGLView.setSpecularIntensity(0.0f); mGLView.setSpecularColor(SUNLIGHT_COLOR); if (PERFORM_DEPTH_TEST) { gl.glEnable(GL10.GL_DEPTH_TEST); } gl.glDisable(GL10.GL_SCISSOR_TEST); gl.glClearColor(0, 0, 0, 1); gl.glHint(GL10.GL_POINT_SMOOTH_HINT, GL10.GL_NICEST); mInitialized = true; } /** * Computes the vector from the center of the earth to the sun for a * particular moment in time. */ private void computeSunDirection() { mSunCal.setTimeInMillis(System.currentTimeMillis()); int day = mSunCal.get(Calendar.DAY_OF_YEAR); int seconds = 3600 * mSunCal.get(Calendar.HOUR_OF_DAY) + 60 * mSunCal.get(Calendar.MINUTE) + mSunCal.get(Calendar.SECOND); day += (float) seconds / SECONDS_PER_DAY; // Approximate declination of the sun, changes sinusoidally // during the year. The winter solstice occurs 10 days before // the start of the year. float decl = (float) (EARTH_INCLINATION * Math.cos(Shape.TWO_PI * (day + 10) / 365.0)); // Subsolar latitude, convert from (-PI/2, PI/2) -> (0, PI) form float phi = decl + Shape.PI_OVER_TWO; // Subsolar longitude float theta = Shape.TWO_PI * seconds / SECONDS_PER_DAY; float sinPhi = (float) Math.sin(phi); float cosPhi = (float) Math.cos(phi); float sinTheta = (float) Math.sin(theta); float cosTheta = (float) Math.cos(theta); // Convert from polar to rectangular coordinates float x = cosTheta * sinPhi; float y = cosPhi; float z = sinTheta * sinPhi; // Directional light -> w == 0 mLightDir[0] = x; mLightDir[1] = y; mLightDir[2] = z; mLightDir[3] = 0.0f; } /** * Computes the approximate spherical distance between two * (latitude, longitude) coordinates. */ private float distance(float lat1, float lon1, float lat2, float lon2) { lat1 *= Shape.DEGREES_TO_RADIANS; lat2 *= Shape.DEGREES_TO_RADIANS; lon1 *= Shape.DEGREES_TO_RADIANS; lon2 *= Shape.DEGREES_TO_RADIANS; float r = 6371.0f; // Earth's radius in km float dlat = lat2 - lat1; float dlon = lon2 - lon1; double sinlat2 = Math.sin(dlat / 2.0f); sinlat2 *= sinlat2; double sinlon2 = Math.sin(dlon / 2.0f); sinlon2 *= sinlon2; double a = sinlat2 + Math.cos(lat1) * Math.cos(lat2) * sinlon2; double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return (float) (r * c); } /** * Locates the closest city to the currently displayed center point, * optionally restricting the search to cities within a given time zone. */ private void locateCity(boolean useOffset, float offset) { float mindist = Float.MAX_VALUE; int minidx = -1; for (int i = 0; i < mCities.size(); i++) { City city = mCities.get(i); if (useOffset && !tzEqual(getOffset(city), offset)) { continue; } float dist = distance(city.getLatitude(), city.getLongitude(), mTiltAngle, mRotAngle - 90.0f); if (dist < mindist) { mindist = dist; minidx = i; } } mCityIndex = minidx; } /** * Animates the earth to be centered at the current city. */ private void goToCity() { City city = mCities.get(mCityIndex); float dist = distance(city.getLatitude(), city.getLongitude(), mTiltAngle, mRotAngle - 90.0f); mFlyToCity = true; mCityFlyStartTime = System.currentTimeMillis(); mCityFlightTime = dist / 5.0f; // 5000 km/sec mRotAngleStart = mRotAngle; mRotAngleDest = city.getLongitude() + 90; if (mRotAngleDest - mRotAngleStart > 180.0f) { mRotAngleDest -= 360.0f; } else if (mRotAngleStart - mRotAngleDest > 180.0f) { mRotAngleDest += 360.0f; } mTiltAngleStart = mTiltAngle; mTiltAngleDest = city.getLatitude(); mRotVelocity = 0.0f; } /** * Returns a linearly interpolated value between two values. */ private float lerp(float a, float b, float lerp) { return a + (b - a)*lerp; } /** * Draws the city lights, using a clip plane to restrict the lights * to the night side of the earth. */ private void drawCityLights(GL10 gl, float brightness) { gl.glEnable(GL10.GL_POINT_SMOOTH); gl.glDisable(GL10.GL_DEPTH_TEST); gl.glDisable(GL10.GL_LIGHTING); gl.glDisable(GL10.GL_DITHER); gl.glShadeModel(GL10.GL_FLAT); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glPointSize(1.0f); float ls = lerp(0.8f, 0.3f, brightness); gl.glColor4f(ls * 1.0f, ls * 1.0f, ls * 0.8f, 1.0f); if (mDisplayWorld) { mClipPlaneEquation[0] = -mLightDir[0]; mClipPlaneEquation[1] = -mLightDir[1]; mClipPlaneEquation[2] = -mLightDir[2]; mClipPlaneEquation[3] = 0.0f; // Assume we have glClipPlanef() from OpenGL ES 1.1 ((GL11) gl).glClipPlanef(GL11.GL_CLIP_PLANE0, mClipPlaneEquation, 0); gl.glEnable(GL11.GL_CLIP_PLANE0); } mLights.draw(gl); if (mDisplayWorld) { gl.glDisable(GL11.GL_CLIP_PLANE0); } mNumTriangles += mLights.getNumTriangles()*2; } /** * Draws the atmosphere. */ private void drawAtmosphere(GL10 gl) { gl.glDisable(GL10.GL_LIGHTING); gl.glDisable(GL10.GL_CULL_FACE); gl.glDisable(GL10.GL_DITHER); gl.glDisable(GL10.GL_DEPTH_TEST); gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT); // Draw the atmospheric layer float tx = mGLView.getTranslateX(); float ty = mGLView.getTranslateY(); float tz = mGLView.getTranslateZ(); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); gl.glTranslatef(tx, ty, tz); // Blend in the atmosphere a bit gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); ATMOSPHERE.draw(gl); mNumTriangles += ATMOSPHERE.getNumTriangles(); } /** * Draws the world in a 2D map view. */ private void drawWorldFlat(GL10 gl) { gl.glDisable(GL10.GL_BLEND); gl.glEnable(GL10.GL_DITHER); gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT); gl.glTranslatef(mWrapX - 2, 0.0f, 0.0f); worldFlat.draw(gl); gl.glTranslatef(2.0f, 0.0f, 0.0f); worldFlat.draw(gl); mNumTriangles += worldFlat.getNumTriangles() * 2; mWrapX += mWrapVelocity * mWrapVelocityFactor; while (mWrapX < 0.0f) { mWrapX += 2.0f; } while (mWrapX > 2.0f) { mWrapX -= 2.0f; } } /** * Draws the world in a 2D round view. */ private void drawWorldRound(GL10 gl) { gl.glDisable(GL10.GL_BLEND); gl.glEnable(GL10.GL_DITHER); gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT); mWorld.draw(gl); mNumTriangles += mWorld.getNumTriangles(); } /** * Draws the clock. * * @param canvas the Canvas to draw to * @param now the current time * @param w the width of the screen * @param h the height of the screen * @param lerp controls the animation, between 0.0 and 1.0 */ private void drawClock(Canvas canvas, long now, int w, int h, float lerp) { float clockAlpha = lerp(0.0f, 0.8f, lerp); mClockShowing = clockAlpha > 0.0f; if (clockAlpha > 0.0f) { City city = mCities.get(mCityIndex); mClock.setCity(city); mClock.setTime(now); float cx = w / 2.0f; float cy = h / 2.0f; float smallRadius = 18.0f; float bigRadius = 0.75f * 0.5f * Math.min(w, h); float radius = lerp(smallRadius, bigRadius, lerp); // Only display left/right arrows if we are in a name search boolean scrollingByName = (mCityName.length() > 0) && (mCities.size() > 1); mClock.drawClock(canvas, cx, cy, radius, clockAlpha, 1.0f, lerp == 1.0f, lerp == 1.0f, !atEndOfTimeZone(-1), !atEndOfTimeZone(1), scrollingByName, mCityName.length()); } } /** * Draws the 2D layer. */ @Override protected void onDraw(Canvas canvas) { long now = System.currentTimeMillis(); if (startTime != -1) { startTime = -1; } int w = getWidth(); int h = getHeight(); // Interpolator for clock size, clock alpha, night lights intensity float lerp = Math.min((now - mClockFadeTime)/1000.0f, 1.0f); if (!mDisplayClock) { // Clock is receding lerp = 1.0f - lerp; } lerp = mClockSizeInterpolator.getInterpolation(lerp); // we don't need to make sure OpenGL rendering is done because // we're drawing in to a different surface drawClock(canvas, now, w, h, lerp); mGLView.showMessages(canvas); mGLView.showStatistics(canvas, w); } /** * Draws the 3D layer. */ protected void drawOpenGLScene() { long now = System.currentTimeMillis(); mNumTriangles = 0; EGL10 egl = (EGL10)EGLContext.getEGL(); GL10 gl = (GL10)mEGLContext.getGL(); if (!mInitialized) { init(gl); } int w = getWidth(); int h = getHeight(); gl.glViewport(0, 0, w, h); gl.glEnable(GL10.GL_LIGHTING); gl.glEnable(GL10.GL_LIGHT0); gl.glEnable(GL10.GL_CULL_FACE); gl.glFrontFace(GL10.GL_CCW); float ratio = (float) w / h; mGLView.setAspectRatio(ratio); mGLView.setTextureParameters(gl); if (PERFORM_DEPTH_TEST) { gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); } else { gl.glClear(GL10.GL_COLOR_BUFFER_BIT); } if (mDisplayWorldFlat) { gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-1.0f, 1.0f, -1.0f / ratio, 1.0f / ratio, 1.0f, 2.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); gl.glTranslatef(0.0f, 0.0f, -1.0f); } else { mGLView.setProjection(gl); mGLView.setView(gl); } if (!mDisplayWorldFlat) { if (mFlyToCity) { float lerp = (now - mCityFlyStartTime)/mCityFlightTime; if (lerp >= 1.0f) { mFlyToCity = false; } lerp = Math.min(lerp, 1.0f); lerp = mFlyToCityInterpolator.getInterpolation(lerp); mRotAngle = lerp(mRotAngleStart, mRotAngleDest, lerp); mTiltAngle = lerp(mTiltAngleStart, mTiltAngleDest, lerp); } // Rotate the viewpoint around the earth gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glRotatef(mTiltAngle, 1, 0, 0); gl.glRotatef(mRotAngle, 0, 1, 0); // Increment the rotation angle mRotAngle += mRotVelocity; if (mRotAngle < 0.0f) { mRotAngle += 360.0f; } if (mRotAngle > 360.0f) { mRotAngle -= 360.0f; } } // Draw the world with lighting gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, mLightDir, 0); mGLView.setLights(gl, GL10.GL_LIGHT0); if (mDisplayWorldFlat) { drawWorldFlat(gl); } else if (mDisplayWorld) { drawWorldRound(gl); } if (mDisplayLights && !mDisplayWorldFlat) { // Interpolator for clock size, clock alpha, night lights intensity float lerp = Math.min((now - mClockFadeTime)/1000.0f, 1.0f); if (!mDisplayClock) { // Clock is receding lerp = 1.0f - lerp; } lerp = mClockSizeInterpolator.getInterpolation(lerp); drawCityLights(gl, lerp); } if (mDisplayAtmosphere && !mDisplayWorldFlat) { drawAtmosphere(gl); } mGLView.setNumTriangles(mNumTriangles); egl.eglSwapBuffers(mEGLDisplay, mEGLSurface); if (egl.eglGetError() == EGL11.EGL_CONTEXT_LOST) { // we lost the gpu, quit immediately Context c = getContext(); if (c instanceof Activity) { ((Activity)c).finish(); } } } private static final int INVALIDATE = 1; private static final int ONE_MINUTE = 60000; /** * Controls the animation using the message queue. Every time we receive * an INVALIDATE message, we redraw and place another message in the queue. */ private final Handler mHandler = new Handler() { private long mLastSunPositionTime = 0; @Override public void handleMessage(Message msg) { if (msg.what == INVALIDATE) { // Use the message's time, it's good enough and // allows us to avoid a system call. if ((msg.getWhen() - mLastSunPositionTime) >= ONE_MINUTE) { // Recompute the sun's position once per minute // Place the light at the Sun's direction computeSunDirection(); mLastSunPositionTime = msg.getWhen(); } // Draw the GL scene drawOpenGLScene(); // Send an update for the 2D overlay if needed if (mInitialized && (mClockShowing || mGLView.hasMessages())) { invalidate(); } // Just send another message immediately. This works because // drawOpenGLScene() does the timing for us -- it will // block until the last frame has been processed. // The invalidate message we're posting here will be // interleaved properly with motion/key events which // guarantee a prompt reaction to the user input. sendEmptyMessage(INVALIDATE); } } }; } /** * The main activity class for GlobalTime. */ public class GlobalTime extends Activity { GTView gtView = null; private void setGTView() { if (gtView == null) { gtView = new GTView(this); setContentView(gtView); } } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setGTView(); } @Override protected void onResume() { super.onResume(); setGTView(); Looper.myQueue().addIdleHandler(new Idler()); } @Override protected void onPause() { super.onPause(); gtView.stopAnimating(); } @Override protected void onStop() { super.onStop(); gtView.stopAnimating(); gtView.destroy(); gtView = null; } // Allow the activity to go idle before its animation starts class Idler implements MessageQueue.IdleHandler { public Idler() { super(); } public final boolean queueIdle() { if (gtView != null) { gtView.startAnimating(); } return false; } } }
Java
/* * Copyright (C) 2006-2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.HashMap; import javax.microedition.khronos.opengles.GL10; import android.graphics.Canvas; import android.graphics.Paint; import android.view.KeyEvent; class Message { private String mText; private long mExpirationTime; public Message(String text, long expirationTime) { this.mText = text; this.mExpirationTime = expirationTime; } public String getText() { return mText; } public long getExpirationTime() { return mExpirationTime; } } /** * A helper class to simplify writing an Activity that renders using * OpenGL ES. * * <p> A GLView object stores common elements of GL state and allows * them to be modified interactively. This is particularly useful for * determining the proper settings of parameters such as the view * frustum and light intensities during application development. * * <p> A GLView is not an actual View; instead, it is meant to be * called from within a View to perform event processing on behalf of the * actual View. * * <p> By passing key events to the GLView object from the View, * the application can automatically allow certain parameters to * be user-controlled from the keyboard. Key events may be passed as * shown below: * * <pre> * GLView mGlView = new GLView(); * * public boolean onKeyDown(int keyCode, KeyEvent event) { * // Hand the key to the GLView object first * if (mGlView.processKey(keyCode)) { * return; * } * * switch (keyCode) { * case KeyEvent.KEY_CODE_X: * // perform app processing * break; * * default: * super.onKeyDown(keyCode, event); * break; * } * } * </pre> * * <p> During drawing of a frame, the GLView object should be given the * opportunity to manage GL parameters as shown below: * * OpenGLContext mGLContext; // initialization not shown * int mNumTrianglesDrawn = 0; * * protected void onDraw(Canvas canvas) { * int w = getWidth(); * int h = getHeight(); * * float ratio = (float) w / h; * mGLView.setAspectRatio(ratio); * * GL10 gl = (GL10) mGLContext.getGL(); * mGLContext.waitNative(canvas, this); * * // Enable a light for the GLView to manipulate * gl.glEnable(GL10.GL_LIGHTING); * gl.glEnable(GL10.GL_LIGHT0); * * // Allow the GLView to set GL parameters * mGLView.setTextureParameters(gl); * mGLView.setProjection(gl); * mGLView.setView(gl); * mGLView.setLights(gl, GL10.GL_LIGHT0); * * // Draw some stuff (not shown) * mNumTrianglesDrawn += <num triangles just drawn>; * * // Wait for GL drawing to complete * mGLContext.waitGL(); * * // Inform the GLView of what was drawn, and ask it to display statistics * mGLView.setNumTriangles(mNumTrianglesDrawn); * mGLView.showMessages(canvas); * mGLView.showStatistics(canvas, w); * } * </pre> * * <p> At the end of each frame, following the call to * GLContext.waitGL, the showStatistics and showMessages methods * will cause additional information to be displayed. * * <p> To enter the interactive command mode, the 'tab' key must be * pressed twice in succession. A subsequent press of the 'tab' key * exits the interactive command mode. Entering a multi-letter code * sets the parameter to be modified. The 'newline' key erases the * current code, and the 'del' key deletes the last letter of * the code. The parameter value may be modified by pressing the * keypad left or up to decrement the value and right or down to * increment the value. The current value will be displayed as an * overlay above the GL rendered content. * * <p> The supported keyboard commands are as follows: * * <ul> * <li> h - display a list of commands * <li> fn - near frustum * <li> ff - far frustum * <li> tx - translate x * <li> ty - translate y * <li> tz - translate z * <li> z - zoom (frustum size) * <li> la - ambient light (all RGB channels) * <li> lar - ambient light red channel * <li> lag - ambient light green channel * <li> lab - ambient light blue channel * <li> ld - diffuse light (all RGB channels) * <li> ldr - diffuse light red channel * <li> ldg - diffuse light green channel * <li> ldb - diffuse light blue channel * <li> ls - specular light (all RGB channels) * <li> lsr - specular light red channel * <li> lsg - specular light green channel * <li> lsb - specular light blue channel * <li> lma - light model ambient (all RGB channels) * <li> lmar - light model ambient light red channel * <li> lmag - light model ambient green channel * <li> lmab - light model ambient blue channel * <li> tmin - texture min filter * <li> tmag - texture mag filter * <li> tper - texture perspective correction * </ul> * * {@hide} */ public class GLView { private static final int DEFAULT_DURATION_MILLIS = 1000; private static final int STATE_KEY = KeyEvent.KEYCODE_TAB; private static final int HAVE_NONE = 0; private static final int HAVE_ONE = 1; private static final int HAVE_TWO = 2; private static final float MESSAGE_Y_SPACING = 12.0f; private int mState = HAVE_NONE; private static final int NEAR_FRUSTUM = 0; private static final int FAR_FRUSTUM = 1; private static final int TRANSLATE_X = 2; private static final int TRANSLATE_Y = 3; private static final int TRANSLATE_Z = 4; private static final int ZOOM_EXPONENT = 5; private static final int AMBIENT_INTENSITY = 6; private static final int AMBIENT_RED = 7; private static final int AMBIENT_GREEN = 8; private static final int AMBIENT_BLUE = 9; private static final int DIFFUSE_INTENSITY = 10; private static final int DIFFUSE_RED = 11; private static final int DIFFUSE_GREEN = 12; private static final int DIFFUSE_BLUE = 13; private static final int SPECULAR_INTENSITY = 14; private static final int SPECULAR_RED = 15; private static final int SPECULAR_GREEN = 16; private static final int SPECULAR_BLUE = 17; private static final int LIGHT_MODEL_AMBIENT_INTENSITY = 18; private static final int LIGHT_MODEL_AMBIENT_RED = 19; private static final int LIGHT_MODEL_AMBIENT_GREEN = 20; private static final int LIGHT_MODEL_AMBIENT_BLUE = 21; private static final int TEXTURE_MIN_FILTER = 22; private static final int TEXTURE_MAG_FILTER = 23; private static final int TEXTURE_PERSPECTIVE_CORRECTION = 24; private static final String[] commands = { "fn", "ff", "tx", "ty", "tz", "z", "la", "lar", "lag", "lab", "ld", "ldr", "ldg", "ldb", "ls", "lsr", "lsg", "lsb", "lma", "lmar", "lmag", "lmab", "tmin", "tmag", "tper" }; private static final String[] labels = { "Near Frustum", "Far Frustum", "Translate X", "Translate Y", "Translate Z", "Zoom", "Ambient Intensity", "Ambient Red", "Ambient Green", "Ambient Blue", "Diffuse Intensity", "Diffuse Red", "Diffuse Green", "Diffuse Blue", "Specular Intenstity", "Specular Red", "Specular Green", "Specular Blue", "Light Model Ambient Intensity", "Light Model Ambient Red", "Light Model Ambient Green", "Light Model Ambient Blue", "Texture Min Filter", "Texture Mag Filter", "Texture Perspective Correction", }; private static final float[] defaults = { 5.0f, 100.0f, 0.0f, 0.0f, -50.0f, 0, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_FASTEST }; private static final float[] increments = { 0.01f, 0.5f, 0.125f, 0.125f, 0.125f, 1.0f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0, 0, 0 }; private float[] params = new float[commands.length]; private static final float mZoomScale = 0.109f; private static final float mZoomBase = 1.01f; private int mParam = -1; private float mIncr = 0; private Paint mPaint = new Paint(); private float mAspectRatio = 1.0f; private float mZoom; // private boolean mPerspectiveCorrection = false; // private int mTextureMinFilter = GL10.GL_NEAREST; // private int mTextureMagFilter = GL10.GL_NEAREST; // Counters for FPS calculation private boolean mDisplayFPS = false; private boolean mDisplayCounts = false; private int mFramesFPS = 10; private long[] mTimes = new long[mFramesFPS]; private int mTimesIdx = 0; private Map<String,Message> mMessages = new HashMap<String,Message>(); /** * Constructs a new GLView. */ public GLView() { mPaint.setColor(0xffffffff); reset(); } /** * Sets the aspect ratio (width/height) of the screen. * * @param aspectRatio the screen width divided by the screen height */ public void setAspectRatio(float aspectRatio) { this.mAspectRatio = aspectRatio; } /** * Sets the overall ambient light intensity. This intensity will * be used to modify the ambient light value for each of the red, * green, and blue channels passed to glLightfv(...GL_AMBIENT...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setAmbientIntensity(float intensity) { params[AMBIENT_INTENSITY] = intensity; } /** * Sets the light model ambient intensity. This intensity will be * used to modify the ambient light value for each of the red, * green, and blue channels passed to * glLightModelfv(GL_LIGHT_MODEL_AMBIENT...). The default value * is 0.125f. * * @param intensity a floating-point value controlling the overall * light model ambient intensity. */ public void setLightModelAmbientIntensity(float intensity) { params[LIGHT_MODEL_AMBIENT_INTENSITY] = intensity; } /** * Sets the ambient color for the red, green, and blue channels * that will be multiplied by the value of setAmbientIntensity and * passed to glLightfv(...GL_AMBIENT...). The default values are * {1, 1, 1}. * * @param ambient an arry of three floats containing ambient * red, green, and blue intensity values. */ public void setAmbientColor(float[] ambient) { params[AMBIENT_RED] = ambient[0]; params[AMBIENT_GREEN] = ambient[1]; params[AMBIENT_BLUE] = ambient[2]; } /** * Sets the overall diffuse light intensity. This intensity will * be used to modify the diffuse light value for each of the red, * green, and blue channels passed to glLightfv(...GL_DIFFUSE...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setDiffuseIntensity(float intensity) { params[DIFFUSE_INTENSITY] = intensity; } /** * Sets the diffuse color for the red, green, and blue channels * that will be multiplied by the value of setDiffuseIntensity and * passed to glLightfv(...GL_DIFFUSE...). The default values are * {1, 1, 1}. * * @param diffuse an array of three floats containing diffuse * red, green, and blue intensity values. */ public void setDiffuseColor(float[] diffuse) { params[DIFFUSE_RED] = diffuse[0]; params[DIFFUSE_GREEN] = diffuse[1]; params[DIFFUSE_BLUE] = diffuse[2]; } /** * Sets the overall specular light intensity. This intensity will * be used to modify the diffuse light value for each of the red, * green, and blue channels passed to glLightfv(...GL_SPECULAR...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setSpecularIntensity(float intensity) { params[SPECULAR_INTENSITY] = intensity; } /** * Sets the specular color for the red, green, and blue channels * that will be multiplied by the value of setSpecularIntensity and * passed to glLightfv(...GL_SPECULAR...). The default values are * {1, 1, 1}. * * @param specular an array of three floats containing specular * red, green, and blue intensity values. */ public void setSpecularColor(float[] specular) { params[SPECULAR_RED] = specular[0]; params[SPECULAR_GREEN] = specular[1]; params[SPECULAR_BLUE] = specular[2]; } /** * Returns the current X translation of the modelview * transformation as passed to glTranslatef. The default value is * 0.0f. * * @return the X modelview translation as a float. */ public float getTranslateX() { return params[TRANSLATE_X]; } /** * Returns the current Y translation of the modelview * transformation as passed to glTranslatef. The default value is * 0.0f. * * @return the Y modelview translation as a float. */ public float getTranslateY() { return params[TRANSLATE_Y]; } /** * Returns the current Z translation of the modelview * transformation as passed to glTranslatef. The default value is * -50.0f. * * @return the Z modelview translation as a float. */ public float getTranslateZ() { return params[TRANSLATE_Z]; } /** * Sets the position of the near frustum clipping plane as passed * to glFrustumf. The default value is 5.0f; * * @param nearFrustum the near frustum clipping plane distance as * a float. */ public void setNearFrustum(float nearFrustum) { params[NEAR_FRUSTUM] = nearFrustum; } /** * Sets the position of the far frustum clipping plane as passed * to glFrustumf. The default value is 100.0f; * * @param farFrustum the far frustum clipping plane distance as a * float. */ public void setFarFrustum(float farFrustum) { params[FAR_FRUSTUM] = farFrustum; } private void computeZoom() { mZoom = mZoomScale*(float)Math.pow(mZoomBase, -params[ZOOM_EXPONENT]); } /** * Resets all parameters to their default values. */ public void reset() { for (int i = 0; i < params.length; i++) { params[i] = defaults[i]; } computeZoom(); } private void removeExpiredMessages() { long now = System.currentTimeMillis(); List<String> toBeRemoved = new ArrayList<String>(); Iterator<String> keyIter = mMessages.keySet().iterator(); while (keyIter.hasNext()) { String key = keyIter.next(); Message msg = mMessages.get(key); if (msg.getExpirationTime() < now) { toBeRemoved.add(key); } } Iterator<String> tbrIter = toBeRemoved.iterator(); while (tbrIter.hasNext()) { String key = tbrIter.next(); mMessages.remove(key); } } /** * Displays the message overlay on the given Canvas. The * GLContext.waitGL method should be called prior to calling this * method. The interactive command display is drawn by this * method. * * @param canvas the Canvas on which messages are to appear. */ public void showMessages(Canvas canvas) { removeExpiredMessages(); float y = 10.0f; List<String> l = new ArrayList<String>(); l.addAll(mMessages.keySet()); Collections.sort(l); Iterator<String> iter = l.iterator(); while (iter.hasNext()) { String key = iter.next(); String text = mMessages.get(key).getText(); canvas.drawText(text, 10.0f, y, mPaint); y += MESSAGE_Y_SPACING; } } private int mTriangles; /** * Sets the number of triangles drawn in the previous frame for * display by the showStatistics method. The number of triangles * is not computed by GLView but must be supplied by the * calling Activity. * * @param triangles an Activity-supplied estimate of the number of * triangles drawn in the previous frame. */ public void setNumTriangles(int triangles) { this.mTriangles = triangles; } /** * Displays statistics on frames and triangles per second. The * GLContext.waitGL method should be called prior to calling this * method. * * @param canvas the Canvas on which statistics are to appear. * @param width the width of the Canvas. */ public void showStatistics(Canvas canvas, int width) { long endTime = mTimes[mTimesIdx] = System.currentTimeMillis(); mTimesIdx = (mTimesIdx + 1) % mFramesFPS; float th = mPaint.getTextSize(); if (mDisplayFPS) { // Use end time from mFramesFPS frames ago long startTime = mTimes[mTimesIdx]; String fps = "" + (1000.0f*mFramesFPS/(endTime - startTime)); // Normalize fps to XX.XX format if (fps.indexOf(".") == 1) { fps = " " + fps; } int len = fps.length(); if (len == 2) { fps += ".00"; } else if (len == 4) { fps += "0"; } else if (len > 5) { fps = fps.substring(0, 5); } canvas.drawText(fps + " fps", width - 60.0f, 10.0f, mPaint); } if (mDisplayCounts) { canvas.drawText(mTriangles + " triangles", width - 100.0f, 10.0f + th + 5, mPaint); } } private void addMessage(String key, String text, int durationMillis) { long expirationTime = System.currentTimeMillis() + durationMillis; mMessages.put(key, new Message(text, expirationTime)); } private void addMessage(String key, String text) { addMessage(key, text, DEFAULT_DURATION_MILLIS); } private void addMessage(String text) { addMessage(text, text, DEFAULT_DURATION_MILLIS); } private void clearMessages() { mMessages.clear(); } String command = ""; private void toggleFilter() { if (params[mParam] == GL10.GL_NEAREST) { params[mParam] = GL10.GL_LINEAR; } else { params[mParam] = GL10.GL_NEAREST; } addMessage(commands[mParam], "Texture " + (mParam == TEXTURE_MIN_FILTER ? "min" : "mag") + " filter = " + (params[mParam] == GL10.GL_NEAREST ? "nearest" : "linear")); } private void togglePerspectiveCorrection() { if (params[mParam] == GL10.GL_NICEST) { params[mParam] = GL10.GL_FASTEST; } else { params[mParam] = GL10.GL_NICEST; } addMessage(commands[mParam], "Texture perspective correction = " + (params[mParam] == GL10.GL_FASTEST ? "fastest" : "nicest")); } private String valueString() { if (mParam == TEXTURE_MIN_FILTER || mParam == TEXTURE_MAG_FILTER) { if (params[mParam] == GL10.GL_NEAREST) { return "nearest"; } if (params[mParam] == GL10.GL_LINEAR) { return "linear"; } } if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { if (params[mParam] == GL10.GL_FASTEST) { return "fastest"; } if (params[mParam] == GL10.GL_NICEST) { return "nicest"; } } return "" + params[mParam]; } /** * * @return true if the view */ public boolean hasMessages() { return mState == HAVE_TWO || mDisplayFPS || mDisplayCounts; } /** * Process a key stroke. The calling Activity should pass all * keys from its onKeyDown method to this method. If the key is * part of a GLView command, true is returned and the calling * Activity should ignore the key event. Otherwise, false is * returned and the calling Activity may process the key event * normally. * * @param keyCode the key code as passed to Activity.onKeyDown. * * @return true if the key is part of a GLView command sequence, * false otherwise. */ public boolean processKey(int keyCode) { // Pressing the state key twice enters the UI // Pressing it again exits the UI if ((keyCode == STATE_KEY) || (keyCode == KeyEvent.KEYCODE_SLASH) || (keyCode == KeyEvent.KEYCODE_PERIOD)) { mState = (mState + 1) % 3; if (mState == HAVE_NONE) { clearMessages(); } if (mState == HAVE_TWO) { clearMessages(); addMessage("aaaa", "GL", Integer.MAX_VALUE); addMessage("aaab", "", Integer.MAX_VALUE); command = ""; } return true; } else { if (mState == HAVE_ONE) { mState = HAVE_NONE; return false; } } // If we're not in the UI, exit without handling the key if (mState != HAVE_TWO) { return false; } if (keyCode == KeyEvent.KEYCODE_ENTER) { command = ""; } else if (keyCode == KeyEvent.KEYCODE_DEL) { if (command.length() > 0) { command = command.substring(0, command.length() - 1); } } else if (keyCode >= KeyEvent.KEYCODE_A && keyCode <= KeyEvent.KEYCODE_Z) { command += "" + (char)(keyCode - KeyEvent.KEYCODE_A + 'a'); } addMessage("aaaa", "GL " + command, Integer.MAX_VALUE); if (command.equals("h")) { addMessage("aaaa", "GL", Integer.MAX_VALUE); addMessage("h - help"); addMessage("fn/ff - frustum near/far clip Z"); addMessage("la/lar/lag/lab - abmient intensity/r/g/b"); addMessage("ld/ldr/ldg/ldb - diffuse intensity/r/g/b"); addMessage("ls/lsr/lsg/lsb - specular intensity/r/g/b"); addMessage("s - toggle statistics display"); addMessage("tmin/tmag - texture min/mag filter"); addMessage("tpersp - texture perspective correction"); addMessage("tx/ty/tz - view translate x/y/z"); addMessage("z - zoom"); command = ""; return true; } else if (command.equals("s")) { mDisplayCounts = !mDisplayCounts; mDisplayFPS = !mDisplayFPS; command = ""; return true; } mParam = -1; for (int i = 0; i < commands.length; i++) { if (command.equals(commands[i])) { mParam = i; mIncr = increments[i]; } } if (mParam == -1) { return true; } boolean addMessage = true; // Increment or decrement if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { if (mParam == ZOOM_EXPONENT) { params[mParam] += mIncr; computeZoom(); } else if ((mParam == TEXTURE_MIN_FILTER) || (mParam == TEXTURE_MAG_FILTER)) { toggleFilter(); } else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { togglePerspectiveCorrection(); } else { params[mParam] += mIncr; } } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { if (mParam == ZOOM_EXPONENT) { params[mParam] -= mIncr; computeZoom(); } else if ((mParam == TEXTURE_MIN_FILTER) || (mParam == TEXTURE_MAG_FILTER)) { toggleFilter(); } else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { togglePerspectiveCorrection(); } else { params[mParam] -= mIncr; } } if (addMessage) { addMessage(commands[mParam], labels[mParam] + ": " + valueString()); } return true; } /** * Zoom in by a given number of steps. A negative value of steps * zooms out. Each step zooms in by 1%. * * @param steps the number of steps to zoom by. */ public void zoom(int steps) { params[ZOOM_EXPONENT] += steps; computeZoom(); } /** * Set the projection matrix using glFrustumf. The left and right * clipping planes are set at -+(aspectRatio*zoom), the bottom and * top clipping planes are set at -+zoom, and the near and far * clipping planes are set to the values set by setNearFrustum and * setFarFrustum or interactively. * * <p> GL side effects: * <ul> * <li>overwrites the matrix mode</li> * <li>overwrites the projection matrix</li> * </ul> * * @param gl a GL10 instance whose projection matrix is to be modified. */ public void setProjection(GL10 gl) { gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); if (mAspectRatio >= 1.0f) { gl.glFrustumf(-mAspectRatio*mZoom, mAspectRatio*mZoom, -mZoom, mZoom, params[NEAR_FRUSTUM], params[FAR_FRUSTUM]); } else { gl.glFrustumf(-mZoom, mZoom, -mZoom / mAspectRatio, mZoom / mAspectRatio, params[NEAR_FRUSTUM], params[FAR_FRUSTUM]); } } /** * Set the modelview matrix using glLoadIdentity and glTranslatef. * The translation values are set interactively. * * <p> GL side effects: * <ul> * <li>overwrites the matrix mode</li> * <li>overwrites the modelview matrix</li> * </ul> * * @param gl a GL10 instance whose modelview matrix is to be modified. */ public void setView(GL10 gl) { gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); // Move the viewpoint backwards gl.glTranslatef(params[TRANSLATE_X], params[TRANSLATE_Y], params[TRANSLATE_Z]); } /** * Sets texture parameters. * * <p> GL side effects: * <ul> * <li>sets the GL_PERSPECTIVE_CORRECTION_HINT</li> * <li>sets the GL_TEXTURE_MIN_FILTER texture parameter</li> * <li>sets the GL_TEXTURE_MAX_FILTER texture parameter</li> * </ul> * * @param gl a GL10 instance whose texture parameters are to be modified. */ public void setTextureParameters(GL10 gl) { gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, (int)params[TEXTURE_PERSPECTIVE_CORRECTION]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, params[TEXTURE_MIN_FILTER]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, params[TEXTURE_MAG_FILTER]); } /** * Sets the lighting parameters for the given light. * * <p> GL side effects: * <ul> * <li>sets the GL_LIGHT_MODEL_AMBIENT intensities * <li>sets the GL_AMBIENT intensities for the given light</li> * <li>sets the GL_DIFFUSE intensities for the given light</li> * <li>sets the GL_SPECULAR intensities for the given light</li> * </ul> * * @param gl a GL10 instance whose texture parameters are to be modified. */ public void setLights(GL10 gl, int lightNum) { float[] light = new float[4]; light[3] = 1.0f; float lmi = params[LIGHT_MODEL_AMBIENT_INTENSITY]; light[0] = params[LIGHT_MODEL_AMBIENT_RED]*lmi; light[1] = params[LIGHT_MODEL_AMBIENT_GREEN]*lmi; light[2] = params[LIGHT_MODEL_AMBIENT_BLUE]*lmi; gl.glLightModelfv(GL10.GL_LIGHT_MODEL_AMBIENT, light, 0); float ai = params[AMBIENT_INTENSITY]; light[0] = params[AMBIENT_RED]*ai; light[1] = params[AMBIENT_GREEN]*ai; light[2] = params[AMBIENT_BLUE]*ai; gl.glLightfv(lightNum, GL10.GL_AMBIENT, light, 0); float di = params[DIFFUSE_INTENSITY]; light[0] = params[DIFFUSE_RED]*di; light[1] = params[DIFFUSE_GREEN]*di; light[2] = params[DIFFUSE_BLUE]*di; gl.glLightfv(lightNum, GL10.GL_DIFFUSE, light, 0); float si = params[SPECULAR_INTENSITY]; light[0] = params[SPECULAR_RED]*si; light[1] = params[SPECULAR_GREEN]*si; light[2] = params[SPECULAR_BLUE]*si; gl.glLightfv(lightNum, GL10.GL_SPECULAR, light, 0); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; public class LatLongSphere extends Sphere { public LatLongSphere(float centerX, float centerY, float centerZ, float radius, int lats, int longs, float minLongitude, float maxLongitude, boolean emitTextureCoordinates, boolean emitNormals, boolean emitColors, boolean flatten) { super(emitTextureCoordinates, emitNormals, emitColors); int tris = 2 * (lats - 1) * (longs - 1); int[] vertices = new int[3 * lats * longs]; int[] texcoords = new int[2 * lats * longs]; int[] colors = new int[4 * lats * longs]; int[] normals = new int[3 * lats * longs]; short[] indices = new short[3 * tris]; int vidx = 0; int tidx = 0; int nidx = 0; int cidx = 0; int iidx = 0; minLongitude *= DEGREES_TO_RADIANS; maxLongitude *= DEGREES_TO_RADIANS; for (int i = 0; i < longs; i++) { float fi = (float) i / (longs - 1); // theta is the longitude float theta = (maxLongitude - minLongitude) * (1.0f - fi) + minLongitude; float sinTheta = (float) Math.sin(theta); float cosTheta = (float) Math.cos(theta); for (int j = 0; j < lats; j++) { float fj = (float) j / (lats - 1); // phi is the latitude float phi = PI * fj; float sinPhi = (float) Math.sin(phi); float cosPhi = (float) Math.cos(phi); float x = cosTheta * sinPhi; float y = cosPhi; float z = sinTheta * sinPhi; if (flatten) { // Place vertices onto a flat projection vertices[vidx++] = toFixed(2.0f * fi - 1.0f); vertices[vidx++] = toFixed(0.5f - fj); vertices[vidx++] = toFixed(0.0f); } else { // Place vertices onto the surface of a sphere // with the given center and radius vertices[vidx++] = toFixed(x * radius + centerX); vertices[vidx++] = toFixed(y * radius + centerY); vertices[vidx++] = toFixed(z * radius + centerZ); } if (emitTextureCoordinates) { texcoords[tidx++] = toFixed(1.0f - (theta / (TWO_PI))); texcoords[tidx++] = toFixed(fj); } if (emitNormals) { float norm = 1.0f / Shape.length(x, y, z); normals[nidx++] = toFixed(x * norm); normals[nidx++] = toFixed(y * norm); normals[nidx++] = toFixed(z * norm); } // 0 == black, 65536 == white if (emitColors) { colors[cidx++] = (i % 2) * 65536; colors[cidx++] = 0; colors[cidx++] = (j % 2) * 65536; colors[cidx++] = 65536; } } } for (int i = 0; i < longs - 1; i++) { for (int j = 0; j < lats - 1; j++) { int base = i * lats + j; // Ensure both triangles have the same final vertex // since this vertex carries the color for flat // shading indices[iidx++] = (short) (base); indices[iidx++] = (short) (base + 1); indices[iidx++] = (short) (base + lats + 1); indices[iidx++] = (short) (base + lats); indices[iidx++] = (short) (base); indices[iidx++] = (short) (base + lats + 1); } } allocateBuffers(vertices, texcoords, normals, colors, indices); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.nio.ByteBuffer; public class Texture { private ByteBuffer data; private int width, height; public Texture(ByteBuffer data, int width, int height) { this.data = data; this.width = width; this.height = height; } public ByteBuffer getData() { return data; } public int getWidth() { return width; } public int getHeight() { return height; } }
Java
package com.onpositive.plugin.model.store; import java.util.List; public class SecondaryList { //public String key; public List<Entity> list; }
Java
package com.onpositive.plugin.model.store; import java.util.List; public class PrimaryList { public String targetKey; public String targetName; public List<Annotation> list; }
Java
package com.onpositive.plugin.model.store; import java.util.List; public class Model { public List<PrimaryList> root; }
Java
package com.onpositive.plugin.model.store; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.eclipse.jdt.core.IJavaElement; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.onpositive.plugin.model.defenition.AnnotationDefinitionModel; import com.onpositive.plugin.model.defenition.AttributeDefinitionModel; import com.onpositive.plugin.ui.model.Performable; public class ModelController implements IModelController { private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); HashMap<Entity, AttributeDefinitionModel> defMapEntities = new HashMap<Entity, AttributeDefinitionModel>(); HashMap<SecondaryList, AttributeDefinitionModel> defMapLists = new HashMap<SecondaryList, AttributeDefinitionModel>(); List<AnnotationDefinitionModel> defenitions = null; DocumentBuilder db = null; Document doc = null; boolean dirty = false; Model model = null; private Performable modelChangedNotifier = null; public ModelController(InputStream inputStream, List<AnnotationDefinitionModel> list, Performable modelChangedNotifier) { this.modelChangedNotifier = modelChangedNotifier; this.defenitions = list; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { db = dbf.newDocumentBuilder(); doc = db.parse(inputStream); readFromDocument(); } catch (Exception e) { e.printStackTrace(); System.out.println("Can not read the file, creating new one..."); model = new Model(); model.root = new ArrayList<PrimaryList>(); serializeToDocument(); dirty = true; } if(!doc.getDocumentElement().getTagName().equals("root")) { model = new Model(); model.root = new ArrayList<PrimaryList>(); serializeToDocument(); dirty = true; } } @Override public AnnotationDefinitionModel getAnnotationDefenition(Annotation annotation) { for(AnnotationDefinitionModel def: defenitions) if(def.name.equals(annotation.key)) return def; return null; } private AttributeDefinitionModel getAttributeDefenition(Entity entity) { return defMapEntities.get(entity); } private AttributeDefinitionModel getAttributeDefenition(SecondaryList list) { return defMapLists.get(list); } @Override public Model getModel() { return model; } @Override public boolean isModelDirty() { return this.dirty; } private void readFromDocument() { model = new Model(); model.root = new ArrayList<PrimaryList>(); NodeList list = doc.getDocumentElement().getElementsByTagName("primary-list"); for(int i = 0; i < list.getLength(); i++) model.root.add(elementToPrimaryList((Element)list.item(i))); } private PrimaryList elementToPrimaryList(Element element) { PrimaryList result = new PrimaryList(); result.list = new ArrayList<Annotation>(); result.targetKey = element.getAttribute("owner"); NodeList list = element.getElementsByTagName("annotation"); for(int i = 0; i < list.getLength(); i++) result.list.add(elementToAnnotation((Element)list.item(i))); return result; } private Annotation elementToAnnotation(Element element) { Annotation result = new Annotation(); result.key = element.getAttribute("type"); result.attributes = new ArrayList<Entity>(); AnnotationDefinitionModel adm = getAnnotationDefenition(result); NodeList childs = element.getChildNodes(); for(int i = 0; i < childs.getLength(); i++) { Node child = childs.item(i); if(child.getNodeName().equals("primitive")) { Element primitive = (Element)child; Entity entity = new Entity(); entity.key = primitive.getAttribute("name"); AttributeDefinitionModel attdm = getAttributeDefenition(adm, entity.key); entity.value = getValue(attdm, primitive.getAttribute("value")); result.attributes.add(entity); registrate(entity, attdm); } else if(child.getNodeName().equals("annotation")) { Element ann = (Element)child; Entity entity = new Entity(); entity.key = ann.getAttribute("name"); AttributeDefinitionModel attdm = getAttributeDefenition(adm, entity.key); entity.value = elementToAnnotation(ann); result.attributes.add(entity); registrate(entity, attdm); } else if(child.getNodeName().equals("secondary-list")) { Element lst = (Element)child; Entity entity = new Entity(); entity.key = lst.getAttribute("name"); AttributeDefinitionModel attdm = getAttributeDefenition(adm, entity.key); entity.value = elementToSecondaryList(lst); result.attributes.add(entity); registrate(entity, attdm); } } return result; } private void registrate(Entity e, AttributeDefinitionModel adm) { defMapEntities.put(e, adm); if(e.value instanceof SecondaryList) { defMapLists.put((SecondaryList) e.value, adm); for(Entity ent: ((SecondaryList) e.value).list) defMapEntities.put(ent, adm); } return; } public Object getValue(AttributeDefinitionModel attribute, String value) { if(value != null) if (value.length() > 0) { switch(attribute.type) { case STRING: return value; case BYTE: return new Byte(value); case INT: return new Integer(value); case LONG: return new Long(value); case SHORT: return new Short(value); case FLOAT: return new Float(value); case DOUBLE: return new Double(value); case CHAR: return new Character(value.charAt(0)); case BOOLEAN: return new Boolean(value); case ENUM: return value; case CLASS: return value; } } return null; } private AttributeDefinitionModel getAttributeDefenition(AnnotationDefinitionModel adm, String name) { for(AttributeDefinitionModel attrDef: adm.attributes) if(name.equals(attrDef.attributeName)) return attrDef; return null; } private SecondaryList elementToSecondaryList(Element element) { SecondaryList result = new SecondaryList(); result.list = new ArrayList<Entity>(); NodeList childs = element.getChildNodes(); for(int i = 0; i < childs.getLength(); i++) { Node child = childs.item(i); if(child.getNodeName().equals("primitive")) { Element primitive = (Element)child; Entity entity = new Entity(); entity.key = primitive.getAttribute("name"); entity.value = primitive.getAttribute("value"); result.list.add(entity); } else if(child.getNodeName().equals("annotation")) { Element ann = (Element)child; Entity entity = new Entity(); entity.key = ann.getAttribute("name"); entity.value = elementToAnnotation(ann); result.list.add(entity); } } return result; } private void serializeToDocument() { doc = db.newDocument(); Element root = doc.createElement("root"); doc.appendChild(root); for(PrimaryList list: model.root) { Element plist = doc.createElement("primary-list"); plist.setAttribute("owner", list.targetKey); root.appendChild(plist); for(Annotation annotation: list.list) plist.appendChild(annotationToElement(annotation, null)); } } private Element annotationToElement(Annotation annotation, String name) { Element result = doc.createElement("annotation"); result.setAttribute("type", annotation.key); if(name != null) result.setAttribute("name", name); for(Entity entity : annotation.attributes) { Element child = entityToElement(entity); result.appendChild(child); } return result; } private Element entityToElement(Entity entity) { Element result = null; if(entity.value instanceof SecondaryList) { result = doc.createElement("secondary-list"); result.setAttribute("name", (String)entity.key); SecondaryList list = entityToSecondaryList(entity); for(Entity child: list.list) result.appendChild(entityToElement(child)); } else if(entity.value instanceof Annotation) { result = annotationToElement((Annotation)entity.value, entity.key); } else { result = doc.createElement("primitive"); result.setAttribute("name", (String)entity.key); if(entity.value != null) result.setAttribute("value", entity.value.toString()); } return result; } private SecondaryList entityToSecondaryList(Entity entity) { return (SecondaryList)entity.value; } @Override public void setDirty(boolean dirty) { this.dirty = dirty; modelChangedNotifier.perform(null); } @Override public InputStream getInputStream() { serializeToDocument(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Source xmlSource = new DOMSource(doc); Result outputTarget = new StreamResult(outputStream); try { TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } InputStream is = new ByteArrayInputStream(outputStream.toByteArray()); return is; } @Override public PrimaryList getPrimaryList(IJavaElement element) { for(PrimaryList list: model.root) if(list.targetKey.equals(element.getHandleIdentifier())) return list; return null; } public Annotation create(AnnotationDefinitionModel defenition) { Annotation result = new Annotation(); result.attributes = new ArrayList<Entity>(); for(AttributeDefinitionModel attrDef: defenition.attributes) { Entity attribute = new Entity(); attribute.key = attrDef.attributeName; defMapEntities.put(attribute, attrDef); if(attrDef.isArray) { SecondaryList sl = new SecondaryList(); defMapLists.put(sl, attrDef); sl.list = new ArrayList<Entity>(); attribute.value = sl; } result.attributes.add(attribute); } result.key = defenition.name; return result; } @Override public void addAnnotation(IJavaElement element, AnnotationDefinitionModel defenition) { PrimaryList list = getPrimaryList(element); if(list == null) list = createPrimaryList(element); list.list.add(create(defenition)); } private PrimaryList createPrimaryList(IJavaElement element) { PrimaryList list = new PrimaryList(); list.list = new ArrayList<Annotation>(); list.targetKey = element.getHandleIdentifier(); list.targetName = element.getElementName(); model.root.add(list); return list; } @Override public void setAnnotationDefenitions(List<AnnotationDefinitionModel> list) { defenitions = list; } @Override public AttributeDefinitionModel getAttributeDefenition(Object object) { if(object instanceof SecondaryList) return getAttributeDefenition((SecondaryList)object); if(object instanceof Entity) return getAttributeDefenition((Entity)object); return null; } @Override public void addEntityToList(SecondaryList list) { AttributeDefinitionModel atdm = this.getAttributeDefenition(list); Entity e = new Entity(); e.key = atdm.type.name().equals("ANNOTATION") ? "annotation" : "primitive"; defMapEntities.put(e, atdm); list.list.add(e); } @Override public Annotation create(String key) { for(AnnotationDefinitionModel def: defenitions) if(def.name.equals(key)) return create(def); return null; } }
Java
package com.onpositive.plugin.model.store; public class Entity { public String key; public Object value; }
Java
package com.onpositive.plugin.model.store; import java.io.InputStream; import java.util.List; import org.eclipse.jdt.core.IJavaElement; import com.onpositive.plugin.model.defenition.AnnotationDefinitionModel; import com.onpositive.plugin.model.defenition.AttributeDefinitionModel; import com.onpositive.plugin.ui.model.Performable; public interface IModelController { public void setAnnotationDefenitions(List<AnnotationDefinitionModel> list); public AnnotationDefinitionModel getAnnotationDefenition(Annotation annotation); public AttributeDefinitionModel getAttributeDefenition(Object object); public Model getModel(); public boolean isModelDirty(); public void setDirty(boolean dirty); public InputStream getInputStream(); public PrimaryList getPrimaryList(IJavaElement element); public void addAnnotation(IJavaElement element, AnnotationDefinitionModel defenition); public void addEntityToList(SecondaryList list); public Annotation create(String key); public Object getValue(AttributeDefinitionModel attribute, String value); }
Java
package com.onpositive.plugin.model.store; import java.util.List; public class Annotation { public String key; public List<Entity> attributes; }
Java
package com.onpositive.plugin.model.defenition; import java.util.ArrayList; import java.util.List; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.Signature; import com.onpositive.plugin.model.store.Entity; public class AttributeDefinitionModel { public AttributeType type; public String attributeName; public String fullTypeName; public String simpleTypeName; public List<String> availableValues; public String annotationKey; public boolean isArray = false; AttributeDefinitionModel(IMethod method) { try { this.simpleTypeName = detectArray(Signature.toString(method.getReturnType())); this.attributeName = method.getElementName(); IType declaredType = method.getDeclaringType(); String[][] resolved = declaredType.resolveType(this.simpleTypeName); if(resolved == null) { this.type = getTypeForPrimitive(simpleTypeName); this.fullTypeName = this.type.name().toLowerCase(); } else { this.fullTypeName = Signature.toQualifiedName(resolved[0]); IType t = declaredType.getPackageFragment().getJavaProject().findType(this.fullTypeName); this.type = getTypeForNonPrimitive(t); if(type.equals(AttributeType.ENUM)) { availableValues = new ArrayList<String>(); for(IField field: t.getFields()) { availableValues.add(field.getElementName()); } } } } catch (Exception e) { e.printStackTrace(); } } private AttributeType getTypeForPrimitive(String simpleName) { for(AttributeType t: AttributeType.values()) if(t.toString().toLowerCase().equals(simpleName)) return t; return null; } private AttributeType getTypeForNonPrimitive(IType type) { try { if (type.isAnnotation()) { this.annotationKey = type.getFullyQualifiedName(); return AttributeType.ANNOTATION; } if (type.isEnum()) return AttributeType.ENUM; if (type.getElementName().equals("String")) return AttributeType.STRING; if (type.getElementName().equals("java.lang.String")) return AttributeType.STRING; } catch(Exception e) { e.printStackTrace(); } return AttributeType.CLASS; } private String detectArray(String simpleName) { isArray = simpleName.contains("[]"); return simpleName.replaceAll("\\[\\]", ""); } }
Java
package com.onpositive.plugin.model.defenition; public enum AttributeType { STRING, CHAR, BYTE, SHORT, INT, LONG, FLOAT, DOUBLE, BOOLEAN, ENUM, ANNOTATION, CLASS; }
Java
package com.onpositive.plugin.model.defenition; import java.lang.annotation.ElementType; import java.util.ArrayList; import java.util.List; import org.eclipse.jdt.core.IAnnotation; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; public class AnnotationDefinitionModel { public ElementType target = null; public String name = null; public List<AttributeDefinitionModel> attributes = new ArrayList<AttributeDefinitionModel>(); public AnnotationDefinitionModel(IType type) { try { this.name = type.getFullyQualifiedName(); this.target = getTargetAnnotationValue(type); Object ch = type.getChildren(); for(IMethod method: type.getMethods()) attributes.add(new AttributeDefinitionModel(method)); } catch (Exception e) { e.printStackTrace(); } } private ElementType getTargetAnnotationValue(IType type) throws JavaModelException { IAnnotation tarAnn = type.getAnnotation("Target"); String elTp = tarAnn.exists() ? tarAnn.getMemberValuePairs()[0].getValue().toString() : null; if(elTp != null) { try { ElementType result = ElementType.valueOf(elTp.replaceAll("ElementType.", "")); return result; } catch(Exception e) { return null; } } return null; } }
Java
package com.onpositive.plugin.contentproviders; import java.util.ArrayList; import org.eclipse.jdt.core.IAnnotatable; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.IParent; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; public class PackageContentProvider implements ITreeContentProvider { @Override public void dispose() { } @Override public void inputChanged(Viewer arg0, Object arg1, Object arg2) { } @Override public Object[] getChildren(Object arg0) { IJavaElement jel = (IJavaElement)arg0; Object res[] = null; try { if (jel instanceof IParent){ IParent p=(IParent) jel; return p.getChildren(); } res = null; } catch (JavaModelException e) { e.printStackTrace(); } return res; } @Override public Object[] getElements(Object arg0) { return skipChildren((IJavaElement) arg0); } @Override public Object getParent(Object arg0) { IJavaElement jel = (IJavaElement)arg0; return skipParents(jel); } @Override public boolean hasChildren(Object arg0) { IJavaElement jel = (IJavaElement)arg0; if (!(jel instanceof IParent)) return false; try { if(!((IParent)jel).hasChildren()) return false; } catch (JavaModelException e) { return false; } Object children[] = skipChildren(jel); return children == null ? false : children.length > 0; } private Object[] skipChildren(IJavaElement el) { ArrayList list = new ArrayList(); IParent parent = (IParent)el; try { for(IJavaElement child: parent.getChildren()) { if (child instanceof IAnnotatable) { if(!(child instanceof IPackageDeclaration))list.add(child); } else if(hasChildren(child)) { for(Object o: skipChildren(child)) list.add((IJavaElement) o); } } } catch(Exception e) { e.printStackTrace(); } return list.toArray(); } private IJavaElement skipParents(IJavaElement el) { IJavaElement parent = el.getParent(); if(parent instanceof IAnnotatable) return parent; return skipParents(parent); } }
Java
package com.onpositive.plugin.util; import java.util.HashMap; import java.util.Map; import org.eclipse.jface.viewers.ContentViewer; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Widget; import com.onpositive.plugin.model.defenition.AnnotationDefinitionModel; import com.onpositive.plugin.model.defenition.AttributeDefinitionModel; public class OldEditViewer extends ContentViewer { private Composite parent = null; private Composite editor = null; public OldEditViewer(Composite parent) { this.parent = parent; this.editor = new Composite(parent, SWT.NONE); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 1; editor.setLayout(gridLayout); editor.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); setContentProvider(new EditorContentProvider()); setLabelProvider(new EditorLabelProvider()); } @Override public Control getControl() { return editor; } @Override public ISelection getSelection() { int a = 1; return null; } @Override public void refresh() { int a = 1; } @Override public void setSelection(ISelection selection, boolean reveal) { int a = 1; } public Map<Control, AttributeDefinitionModel> getWidgetMap() { return ((EditorContentProvider)this.getContentProvider()).getWidgetMap(); } private class EditorContentProvider implements IContentProvider { private Control title = null; private Map<Control, AttributeDefinitionModel> map = new HashMap<Control, AttributeDefinitionModel>(); private GridData gridData = new GridData(); private GridData labelLayoutData = new GridData(GridData.FILL_BOTH); public EditorContentProvider() { labelLayoutData.verticalAlignment = SWT.CENTER; labelLayoutData.horizontalAlignment = SWT.BEGINNING; labelLayoutData.horizontalAlignment = SWT.FILL; gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; gridData.heightHint = 40; } @Override public void dispose() { for(Control c: map.keySet()) { c.dispose(); } if(title != null) title.dispose(); map.clear(); } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { dispose(); if(newInput != null) { AnnotationDefinitionModel model = (AnnotationDefinitionModel)newInput; title = getItem(viewer.getControl(), "Annotation", model.name); title.setLayoutData(gridData); for(AttributeDefinitionModel attr: model.attributes) { Control item = getItem(viewer.getControl(), attr.attributeName, attr); item.setLayoutData(gridData); map.put(item, attr); } } editor.layout(true, true); } private Control getItem(Control parent, String title, Object element) { Composite result = new Composite((Composite)parent, SWT.BORDER); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.makeColumnsEqualWidth = true; result.setLayout(gridLayout); Label label = new Label(result, SWT.NONE); label.setText(title); label.setLayoutData(labelLayoutData); label.pack(); Control right = null; if(element instanceof AttributeDefinitionModel) { //right = WidgetsFactory.create((AttributeDefinitionModel)element, result); } if(element instanceof String) { right = new Label(result, SWT.NONE); ((Label)right).setText((String)element); right.setLayoutData(labelLayoutData); right.pack(); } result.layout(true,true); return result; } public Map<Control, AttributeDefinitionModel> getWidgetMap() { return map; } } private class EditorLabelProvider implements ILabelProvider { @Override public void addListener(ILabelProviderListener listener) { } @Override public void dispose() { int a = 1; } @Override public boolean isLabelProperty(Object element, String property) { int a = 1; return false; } @Override public void removeListener(ILabelProviderListener listener) { int a = 1; } @Override public Image getImage(Object element) { int a = 1; return null; } @Override public String getText(Object element) { int a = 1; return null; } } }
Java
package com.onpositive.plugin.util.operations; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.operations.AbstractOperation; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import com.onpositive.plugin.ui.model.Actions; import com.onpositive.plugin.ui.model.Performable; public class Operation extends AbstractOperation { Performable executable = null; Actions actions = null; Object input = null; Performable undo = null; Performable redo = null; private Operation(String label) { super(label); } public Operation(Performable executable, Actions actions, Object input) { this("Operation!"); this.executable = executable; this.actions = actions; this.input = input; } public void setInput(Object input) { this.input = input; }; @Override public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { executable.perform(input); undo = actions.performableUndo; redo = actions.performableRedo; return Status.OK_STATUS; } @Override public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { redo.perform(null); return Status.OK_STATUS; } @Override public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { undo.perform(null); return Status.OK_STATUS; } }
Java
package com.onpositive.plugin.util; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import com.onpositive.plugin.ui.EditViewer; import com.onpositive.plugin.ui.model.IPage; import com.onpositive.plugin.ui.model.IPageFactory; import com.onpositive.plugin.ui.model.PageFactory; import com.onpositive.plugin.ui.model.Performable; public class EditViewerController implements SelectionListener { private EditViewer viewer = null; private IPageFactory pageFactory = null; public EditViewerController(EditViewer editViewer, PageFactory pageFactory) { this.viewer = editViewer; this.pageFactory = pageFactory; } public void showPrimaryListPage(IJavaElement element) { final IPage page = pageFactory.getPage(element); viewer.setInput(page); } @Override public void widgetSelected(SelectionEvent e) { Object data = e.item.getData(); if (data != null) if(data instanceof IJavaElement) showPrimaryListPage(((IJavaElement)data)); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }
Java
package com.onpositive.plugin; import java.util.ArrayList; import java.util.List; import org.eclipse.core.commands.operations.IOperationHistory; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.commands.operations.LinearUndoEnforcer; import org.eclipse.core.commands.operations.ObjectUndoContext; import org.eclipse.core.commands.operations.OperationHistoryFactory; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IParent; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPartConstants; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.operations.UndoActionHandler; import org.eclipse.ui.operations.UndoRedoActionGroup; import org.eclipse.ui.part.EditorPart; import com.onpositive.plugin.model.defenition.AnnotationDefinitionModel; import com.onpositive.plugin.model.store.IModelController; import com.onpositive.plugin.model.store.ModelController; import com.onpositive.plugin.ui.AnnotationsViewer; import com.onpositive.plugin.ui.EditViewer; import com.onpositive.plugin.ui.PackageViewer; import com.onpositive.plugin.ui.model.PageFactory; import com.onpositive.plugin.ui.model.Performable; import com.onpositive.plugin.ui.model.WidgetFactory; import com.onpositive.plugin.util.EditViewerController; public class TestEditor extends EditorPart { IJavaElement root = null; IModelController modelController = null; List<AnnotationDefinitionModel> annDefs = null; IOperationHistory history = OperationHistoryFactory.getOperationHistory(); @Override public void doSave(IProgressMonitor arg0) { try { ((IFileEditorInput)this.getEditorInput()).getFile().setContents(modelController.getInputStream(), true, true, arg0); modelController.setDirty(false); } catch (Exception e) { e.printStackTrace(); } } @Override public void doSaveAs() { } @Override public void init(IEditorSite arg0, IEditorInput arg1) throws PartInitException { try { IFileEditorInput input = (IFileEditorInput) arg1; root = JavaCore.create(input.getFile().getParent()); annDefs = getAnnotations(root); Performable modelChangedNotifier = new Performable() { @Override public Object perform(Object obj) { firePropertyChange(IWorkbenchPartConstants.PROP_DIRTY); return null; } }; this.modelController = new ModelController(input.getFile().getContents(), annDefs, modelChangedNotifier); if(isDirty()) { input.getFile().setContents(modelController.getInputStream(), true, true, null); modelController.setDirty(false); } setSite(arg0); setInput(arg1); } catch(Exception e) { e.printStackTrace(); } } @Override public boolean isDirty() { return modelController.isModelDirty(); } @Override public boolean isSaveAsAllowed() { return false; } @Override public void createPartControl(Composite arg0) { IUndoContext undoContext = new ObjectUndoContext(this); UndoRedoActionGroup group = new UndoRedoActionGroup(getSite(), undoContext, false); group.fillActionBars(getEditorSite().getActionBars()); history.addOperationApprover(new LinearUndoEnforcer()); history.setLimit(undoContext, 10); arg0.setLayout(new FillLayout(SWT.HORIZONTAL)); final PackageViewer packageViewer = new PackageViewer(arg0, root); EditViewer editViewer = new EditViewer(arg0, new WidgetFactory(modelController, history, undoContext)); Composite rightPanel = new Composite(arg0, SWT.BORDER); rightPanel.setLayout(new FormLayout()); FormData avData = new FormData(); avData.left = new FormAttachment(0); avData.right = new FormAttachment(100); avData.top = new FormAttachment(0); avData.bottom = new FormAttachment(90); FormData abData = new FormData(); abData.left = new FormAttachment(0); abData.right = new FormAttachment(100); abData.top = new FormAttachment(90); abData.bottom = new FormAttachment(100); final AnnotationsViewer annotationsViewer = new AnnotationsViewer(rightPanel); annotationsViewer.setInput(annDefs); annotationsViewer.getControl().setLayoutData(avData); final Button addAnnotationButton = new Button(rightPanel, SWT.PUSH); addAnnotationButton.setText("Add Annotation"); addAnnotationButton.setLayoutData(abData); final EditViewerController controller = new EditViewerController(editViewer, new PageFactory(modelController, history)); packageViewer.getTree().addSelectionListener(controller); addAnnotationButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { if(packageViewer.getTree().getSelection().length == 1) { IJavaElement el = (IJavaElement) packageViewer.getTree().getSelection()[0].getData(); AnnotationDefinitionModel model = (AnnotationDefinitionModel) annotationsViewer.getTable().getSelection()[0].getData(); if(model != null) { modelController.addAnnotation(el, model); modelController.setDirty(true); controller.showPrimaryListPage(el); } } }}); } @Override public void setFocus() { } private List<AnnotationDefinitionModel> getAnnotations(IJavaElement root) { ArrayList<AnnotationDefinitionModel> result = new ArrayList<AnnotationDefinitionModel>(); try { IJavaProject proj = root.getJavaModel().getJavaProject("Annotations"); IPackageFragmentRoot o = proj.getAllPackageFragmentRoots()[0]; IJavaElement jel = o.getChildren()[0]; IParent p1=(IParent) jel; ICompilationUnit o1 = (ICompilationUnit) p1.getChildren()[0]; IImportDeclaration[] imports = o1.getImports(); for(IImportDeclaration declaration: imports) { String oq = declaration.getElementName(); IJavaProject ip = root.getJavaProject(); IType t = ip.findType(oq); if(t == null) t = root.getJavaModel().getJavaProject("Samples").findType(oq); result.add(new AnnotationDefinitionModel(t)); } } catch(Exception e) { e.printStackTrace(); } return result; } }
Java
package com.onpositive.plugin; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "com.onpositive.plugin"; //$NON-NLS-1$ // The shared instance private static Activator plugin; /** * The constructor */ public Activator() { } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } }
Java
package com.onpositive.plugin.ui.model; import java.util.HashMap; import org.eclipse.core.commands.operations.IOperationHistory; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import com.onpositive.plugin.model.defenition.AttributeDefinitionModel; import com.onpositive.plugin.model.defenition.AttributeType; import com.onpositive.plugin.model.store.Annotation; import com.onpositive.plugin.model.store.Entity; import com.onpositive.plugin.model.store.IModelController; import com.onpositive.plugin.model.store.SecondaryList; import com.onpositive.plugin.util.operations.Operation; public class WidgetFactory implements IWidgetFactory { private HashMap<Entity, Control> controls = new HashMap<Entity, Control>(); IModelController modelController = null; IOperationHistory history = null; IUndoContext undoContext = null; public WidgetFactory(IModelController modelController, IOperationHistory history, IUndoContext undoContext) { this.modelController = modelController; this.history = history; this.undoContext = undoContext; } @Override public Control create(Composite parent, Object rowInput, Actions action) { if(rowInput instanceof Annotation) return getWidgetForAnnotation(parent, (Annotation) rowInput, action); if(rowInput instanceof Entity) return getWidgetForEntity(parent, (Entity) rowInput, action); return null; } private Control getWidgetForAnnotation(Composite parent, final Annotation annotation, final Actions action) { Composite result = new Composite((Composite)parent, SWT.BORDER); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.makeColumnsEqualWidth = true; result.setLayout(gridLayout); GridData layoutData = new GridData(GridData.FILL_BOTH); layoutData.verticalAlignment = SWT.CENTER; layoutData.horizontalAlignment = SWT.FILL; GridData labelData = new GridData(GridData.FILL_BOTH); labelData.verticalAlignment = SWT.CENTER; labelData.horizontalAlignment = SWT.FILL; Label label = new Label(result, SWT.NONE); label.setText(annotation.key); label.setLayoutData(labelData); label.pack(); Button button = new Button(result, SWT.PUSH); button.setText("Edit"); button.setLayoutData(layoutData); button.pack(); button.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { action.performEdit(annotation); } }); result.layout(true,true); return result; } private Control getWidgetForEntity(Composite parent, Entity entity, final Actions action) { AttributeDefinitionModel def = modelController.getAttributeDefenition(entity); Control result = null; if(def.isArray) { if (entity.value instanceof SecondaryList) { result = getWidgetForSecondaryList(def, parent, entity, action); } else { result = getWidgetForAttribute(def, parent, action, entity); } } else { result = getWidgetForAttribute(def, parent, action, entity); } return result; } private Control getWidgetForSecondaryList(AttributeDefinitionModel attribute, Composite parent, final Entity entity, final Actions action) { Composite result = new Composite((Composite)parent, SWT.BORDER); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 3; gridLayout.makeColumnsEqualWidth = true; result.setLayout(gridLayout); GridData layoutData = new GridData(GridData.FILL_BOTH); layoutData.verticalAlignment = SWT.CENTER; layoutData.horizontalAlignment = SWT.FILL; GridData labelData = new GridData(GridData.FILL_BOTH); labelData.verticalAlignment = SWT.CENTER; labelData.horizontalAlignment = SWT.FILL; Label label = new Label(result, SWT.NONE); label.setText(attribute.simpleTypeName + "[]"); label.setLayoutData(labelData); label.pack(); labelData = new GridData(GridData.FILL_BOTH); labelData.verticalAlignment = SWT.CENTER; labelData.horizontalAlignment = SWT.FILL; label = new Label(result, SWT.NONE); label.setText(attribute.attributeName); label.setLayoutData(labelData); label.pack(); Button button = new Button(result, SWT.PUSH); button.setText("Edit"); button.setLayoutData(layoutData); button.pack(); button.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { action.performEdit(entity.value); } }); result.layout(true,true); return result; } private Control getWidgetForAttribute(AttributeDefinitionModel attribute, Composite parent, final Actions action, Entity e) { Composite result = new Composite((Composite)parent, SWT.BORDER); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 3; gridLayout.makeColumnsEqualWidth = true; result.setLayout(gridLayout); GridData layoutData = new GridData(GridData.FILL_BOTH); layoutData.verticalAlignment = SWT.CENTER; layoutData.horizontalAlignment = attribute.type.equals(AttributeType.BOOLEAN) ? SWT.CENTER : SWT.FILL; GridData labelData = new GridData(GridData.FILL_BOTH); labelData.verticalAlignment = SWT.CENTER; labelData.horizontalAlignment = SWT.FILL; Label label = new Label(result, SWT.NONE); label.setText(attribute.simpleTypeName); label.setLayoutData(labelData); label.pack(); labelData = new GridData(GridData.FILL_BOTH); labelData.verticalAlignment = SWT.CENTER; labelData.horizontalAlignment = SWT.FILL; label = new Label(result, SWT.NONE); label.setText(attribute.isArray ? "element" : attribute.attributeName); label.setLayoutData(labelData); label.pack(); Control ctrl = create(attribute, result, action, e); ctrl.setLayoutData(layoutData); ctrl.pack(); result.layout(true,true); return result; } private Control create(final AttributeDefinitionModel attribute, Composite parent, final Actions action, final Entity e) { Control result = null; switch(attribute.type) { case STRING: result = getTextEditor(attribute, parent, action, e); break; case BYTE: result = getTextEditor(attribute, parent, action, e); break; case INT: result = getTextEditor(attribute, parent, action, e); break; case LONG: result = getTextEditor(attribute, parent, action, e); break; case SHORT: result = getTextEditor(attribute, parent, action, e); break; case FLOAT: result = getTextEditor(attribute, parent, action, e); break; case DOUBLE: result = getTextEditor(attribute, parent, action, e); break; case CHAR: result = getTextEditor(attribute, parent, action, e); break; case BOOLEAN: result = getCheckBox(attribute, parent, action, e); break; case ENUM: result = getComboBox(attribute, parent, action, e); break; case ANNOTATION: result = getButton(attribute, parent, action, e); break; case CLASS: result = getTextEditor(attribute, parent, action, e); break; } final Control res = result; if(!attribute.type.equals(AttributeType.ANNOTATION)) { controls.put(e, res); setValue(result, e.value); action.performableUpdate = new Performable() { @Override public Object perform(Object obj) { final Object newv = getValue(res, attribute); final Object old = e.value; e.value = newv; modelController.setDirty(true); action.performableUndo = new Performable() { @Override public Object perform(Object obj) { e.value = old; setValue(controls.get(e), old); modelController.setDirty(true); return null; } }; action.performableRedo = new Performable() { @Override public Object perform(Object obj) { e.value = newv; setValue(controls.get(e), newv); modelController.setDirty(true); return null; } }; return null; } }; Runnable runnable = new Runnable() { @Override public void run() { Operation operation = new Operation(action.performableUpdate, action, null); operation.addContext(undoContext); try { if(!res.isDisposed()) history.execute(operation, null, null); } catch (Exception e) { e.printStackTrace(); } } }; setListener(res, runnable); } return res; } private Control getTextEditor(final AttributeDefinitionModel attribute, Composite parent, Actions action, final Entity e) { final Text result = new Text(parent, SWT.SINGLE); return result; } private static Control getCheckBox(AttributeDefinitionModel attribute, Composite parent, Actions action, final Entity e) { final Button result = new Button(parent, SWT.CHECK); return result; } private Control getComboBox(final AttributeDefinitionModel attribute, Composite parent, final Actions action, final Entity e) { final Combo result = new Combo(parent, SWT.NONE); for(String value: attribute.availableValues) { result.add(value); } return result; } private Control getButton(AttributeDefinitionModel attribute, Composite parent, final Actions action, final Entity e) { Button result = new Button(parent, SWT.PUSH); if(e.value == null) e.value = modelController.create(attribute.annotationKey); result.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { action.performEdit(e.value); } }); result.setText("Edit"); return result; } private void setValue(Control c, Object value) { if(c != null) if(!c.isDisposed()) { if(c instanceof Text) { Text t = (Text)c; Listener[] listeners = t.getListeners(SWT.Modify); for(Listener l : listeners) { t.removeListener(SWT.Modify, l); } t.setText(value == null ? "" : value.toString()); for(Listener l : listeners) { t.addListener(SWT.Modify, l); } } else if(c instanceof Combo) { Combo cb = (Combo)c; Listener[] listeners = cb.getListeners(SWT.Modify); for(Listener l : listeners) { cb.removeListener(SWT.Modify, l); } if(value != null) { int i = cb.indexOf(value.toString()); if (i >= 0) cb.select(i); else cb.deselectAll(); } else { cb.deselectAll(); } for(Listener l : listeners) { cb.addListener(SWT.Modify, l); } } else if(c instanceof Button) { Button b = (Button)c; Listener[] listeners = b.getListeners(SWT.Selection); for(Listener l : listeners) { b.removeListener(SWT.Selection, l); } if(value != null) b.setSelection((Boolean)value); else b.setSelection(false); for(Listener l : listeners) { b.addListener(SWT.Selection, l); } } } } private Object getValue(Control c, AttributeDefinitionModel attribute) { Object value = null; if(!c.isDisposed()) { if(c instanceof Text) { Text t = (Text)c; value = modelController.getValue(attribute, t.getText()); } else if(c instanceof Combo) { Combo cb = (Combo)c; value = modelController.getValue(attribute, cb.getText()); } else if(c instanceof Button) { Button b = (Button)c; value = b.getSelection(); } } return value; } private void setListener(final Control c, final Runnable r) { if(c instanceof Text) { final Text t = (Text)c; t.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { Display.getDefault().timerExec(400, r); } }); } else if(c instanceof Combo) { Combo cb = (Combo)c; cb.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { Display.getDefault().timerExec(400, r); } }); } else if(c instanceof Button) { Button b = (Button)c; b.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { Display.getDefault().timerExec(400, r); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); } } @Override public void clean() { controls.clear(); } }
Java
package com.onpositive.plugin.ui.model; public interface IPageFactory { IPage getPage(Object o); }
Java
package com.onpositive.plugin.ui.model; public interface Performable { public Object perform(Object obj); }
Java
package com.onpositive.plugin.ui.model; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; public interface IWidgetFactory { public Control create(Composite parent, Object rowInput, Actions action); public void clean(); }
Java
package com.onpositive.plugin.ui.model; public class Actions { public Performable performableBack; public Performable performableUpdate; public Performable performableEdit; public Performable performableNext; public Performable performableAdd; public Performable performableRemove; public Performable performableRefresh; public Performable performableUndo; public Performable performableRedo; public void performBack() { if(performableBack != null) performableBack.perform(null); } public void performUpdate() { if(performableUpdate != null) performableUpdate.perform(null); } public void performEdit(Object obj) { if(performableEdit != null) performableEdit.perform(obj); } public void performRefresh() { if(performableRefresh != null) performableRefresh.perform(null); } public Object performNext(Object object) { if(performableNext != null) return performableNext.perform(object); return null; } public Object performAdd(Object object) { if(performableAdd != null) return performableAdd.perform(object); return null; } public Object performRemove(Object object) { if(performableRemove != null) return performableRemove.perform(object); return null; } public Object performUndo(Object object) { if(performableUndo != null) return performableUndo.perform(object); return null; } public Object performRedo(Object object) { if(performableRedo != null) return performableRedo.perform(object); return null; } }
Java
package com.onpositive.plugin.ui.model; import java.util.ArrayList; import java.util.List; import java.util.Stack; import org.eclipse.core.commands.operations.IOperationHistory; import org.eclipse.jdt.core.IJavaElement; import com.onpositive.plugin.model.defenition.AnnotationDefinitionModel; import com.onpositive.plugin.model.store.Annotation; import com.onpositive.plugin.model.store.Entity; import com.onpositive.plugin.model.store.IModelController; import com.onpositive.plugin.model.store.PrimaryList; import com.onpositive.plugin.model.store.SecondaryList; public class PageFactory implements IPageFactory { IModelController modelController = null; public PageFactory(IModelController modelController, IOperationHistory history) { this.modelController = modelController; } @Override public IPage getPage(Object o) { return getPageForOwner((IJavaElement) o); } private IPage getPageForAnnotation(final Annotation annotation, final Stack<IPage> stack) { return new IPage() { public PageFactory factory = PageFactory.this; final Actions action = new Actions(); AnnotationDefinitionModel def = modelController.getAnnotationDefenition(annotation); @Override public String getLeftTitle() { return "Annotation:"; } @Override public String getRightTitle() { return def.name; } @Override public String getLeftSubTitle() { return "Target Type:"; } @Override public String getRightSubTitle() { String target = "All"; if (def.target != null) target = def.target.name(); return target; } @Override public List<Object> getInputList() { ArrayList<Object> result = new ArrayList<Object>(); for(Entity e: annotation.attributes) { result.add(e); } if(result.isEmpty()); return result; } @Override public IPage getPrevious() { return stack.pop(); } @Override public IPage getNext(Object o) { stack.push(this); if(o instanceof Annotation) return factory.getPageForAnnotation((Annotation) o, stack); if(o instanceof SecondaryList) return factory.getPageForSecondaryList((SecondaryList) o, stack); return null; } @Override public Actions getAction() { return action; } @Override public void refresh() { // TODO Auto-generated method stub } }; } private IPage getPageForSecondaryList(final SecondaryList list, final Stack<IPage> stack) { final Actions action = new Actions(); final IPage result = new IPage() { public PageFactory factory = PageFactory.this; @Override public String getLeftTitle() { return "List"; } @Override public String getRightTitle() { return ""; } @Override public String getLeftSubTitle() { return null; } @Override public String getRightSubTitle() { return null; } @Override public List<Object> getInputList() { ArrayList<Object> result = new ArrayList<Object>(); for(Object obj: list.list) result.add(obj); return result; } @Override public IPage getPrevious() { return stack.pop(); } @Override public IPage getNext(Object o) { stack.push(this); if(o instanceof Annotation) return factory.getPageForAnnotation((Annotation) o, stack); if(o instanceof SecondaryList) return factory.getPageForSecondaryList((SecondaryList) o, stack); return null; } @Override public Actions getAction() { return action; } @Override public void refresh() { action.performRefresh(); } }; action.performableAdd = new Performable() { @Override public Object perform(Object obj) { modelController.addEntityToList(list); modelController.setDirty(true); result.refresh(); return null; } }; return result; } private IPage getPageForOwner(final IJavaElement element) { final PrimaryList primaryList = modelController.getPrimaryList(element); final Stack<IPage> stack = new Stack<IPage>(); final Actions action = new Actions(); IPage result = new IPage() { public PageFactory factory = PageFactory.this; @Override public String getLeftTitle() { // TODO Auto-generated method stub return "Owner:"; } @Override public String getRightTitle() { // TODO Auto-generated method stub return element.getElementName(); } @Override public String getLeftSubTitle() { return null; } @Override public String getRightSubTitle() { return null; } @Override public List<Object> getInputList() { ArrayList<Object> result = new ArrayList<Object>(); if(primaryList != null) for(Object obj: primaryList.list) result.add(obj); return result; } @Override public IPage getPrevious() { return stack.pop(); } @Override public IPage getNext(Object o) { stack.push(this); IPage result = null; if(o instanceof Annotation) result = factory.getPageForAnnotation((Annotation) o, stack); if(o instanceof SecondaryList) result = factory.getPageForSecondaryList((SecondaryList) o, stack); return result; } @Override public Actions getAction() { return action; } @Override public void refresh() { // TODO Auto-generated method stub } }; return result; } }
Java
package com.onpositive.plugin.ui.model; import java.util.List; public interface IPage { public String getLeftTitle(); public String getRightTitle(); public String getLeftSubTitle(); public String getRightSubTitle(); public List<Object> getInputList(); public IPage getPrevious(); public IPage getNext(Object o); public void refresh(); public Actions getAction(); }
Java
package com.onpositive.plugin.ui; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import com.onpositive.plugin.contentproviders.PackageContentProvider; public class PackageViewer extends TreeViewer { public PackageViewer(Composite parent, Object input) { super(parent, SWT.SINGLE | SWT.BORDER); setContentProvider(new PackageContentProvider()); setLabelProvider(new JavaElementLabelProvider()); setInput(input); } }
Java
package com.onpositive.plugin.ui; import java.util.List; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import com.onpositive.plugin.model.defenition.AnnotationDefinitionModel; public class AnnotationsViewer extends TableViewer { public AnnotationsViewer(Composite parent) { super(parent, SWT.SINGLE); setContentProvider(new AnnotationsContentProvider()); setLabelProvider(new AnnotationsLabelProvider()); } private class AnnotationsContentProvider implements IStructuredContentProvider { @Override public void dispose() { // TODO Auto-generated method stub } @Override public void inputChanged(Viewer arg0, Object arg1, Object arg2) { // TODO Auto-generated method stub } @Override public Object[] getElements(Object arg0) { @SuppressWarnings("rawtypes") List list = (List) arg0; Object res[] = new Object[list.size()]; int i = 0; for(Object o: list) res[i++] = o; return res; } } private class AnnotationsLabelProvider extends LabelProvider { @Override public String getText(Object element) { return ((AnnotationDefinitionModel)element).name; } } }
Java
package com.onpositive.plugin.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.jface.viewers.ContentViewer; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.internal.C; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Widget; import com.onpositive.plugin.model.defenition.AnnotationDefinitionModel; import com.onpositive.plugin.model.defenition.AttributeDefinitionModel; import com.onpositive.plugin.model.store.Entity; import com.onpositive.plugin.ui.model.Actions; import com.onpositive.plugin.ui.model.IPage; import com.onpositive.plugin.ui.model.IPageFactory; import com.onpositive.plugin.ui.model.IWidgetFactory; import com.onpositive.plugin.ui.model.Performable; import com.onpositive.plugin.ui.model.WidgetFactory; public class EditViewer extends ContentViewer { private Composite editor = null; private IWidgetFactory widgetFactory = null; public EditViewer(Composite parent, IWidgetFactory widgetFactory) { this.editor = new Composite(parent, SWT.BORDER); this.widgetFactory = widgetFactory; GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 1; editor.setLayout(gridLayout); editor.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); setContentProvider(new EditorContentProvider()); setLabelProvider(new EditorLabelProvider()); } @Override public Control getControl() { return editor; } @Override public ISelection getSelection() { int a = 1; return null; } @Override public void refresh() { int a = 1; } @Override public void setSelection(ISelection selection, boolean reveal) { int a = 1; } private class EditorContentProvider implements IContentProvider { ArrayList<Actions> actions = new ArrayList<Actions>(); ArrayList<Control> controls = new ArrayList<Control>(); private GridData labelLayoutData = new GridData(GridData.FILL_BOTH); public EditorContentProvider() { labelLayoutData.verticalAlignment = SWT.CENTER; labelLayoutData.horizontalAlignment = SWT.BEGINNING; labelLayoutData.horizontalAlignment = SWT.FILL; } @Override public void dispose() { actions.clear(); for(Control c: controls) c.dispose(); controls.clear(); widgetFactory.clean(); } @Override public void inputChanged(final Viewer viewer, Object oldInput, Object newInput) { dispose(); final IPage page = (IPage)newInput; if(page != null) { setNextPerformable(viewer, page); if(page.getLeftTitle()!=null) { Control header = getHeader((Composite)viewer.getControl(), page.getLeftTitle(), page.getRightTitle()); header.setLayoutData(getGridLayoutData()); controls.add(header); } if(page.getLeftSubTitle()!=null) { Control header = getHeader((Composite)viewer.getControl(), page.getLeftSubTitle(), page.getRightSubTitle()); header.setLayoutData(getGridLayoutData()); controls.add(header); } List<Object> list = (List<Object>)page.getInputList(); for(final Object item: list) { Actions action = new Actions(); Control row = widgetFactory.create((Composite)viewer.getControl(), item, action); action.performableEdit = new Performable() { @Override public Object perform(Object obj) { page.getAction().performNext(obj); return null; } }; actions.add(action); row.setLayoutData(getGridLayoutData()); controls.add(row); } page.getAction().performableRefresh = new Performable() { @Override public Object perform(Object obj) { viewer.setInput(null); viewer.setInput(page); return null; } }; Control buttonPanel = getButtonPanel((Composite)viewer.getControl(), page.getAction()); buttonPanel.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_BACKGROUND)); buttonPanel.setLayoutData(getGridLayoutData()); controls.add(buttonPanel); } editor.layout(true, true); } private Object getGridLayoutData() { GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; gridData.heightHint = 35; return gridData; } private void setNextPerformable(final Viewer v, final IPage p) { p.getAction().performableNext = new Performable() { @Override public Object perform(Object obj) { final IPage nextPage = p.getNext(obj); nextPage.getAction().performableBack = new Performable() { @Override public Object perform(Object obj) { v.setInput(nextPage.getPrevious()); return null; } }; v.setInput(nextPage); return null; } }; } private Control getHeader(Control parent, String leftTitle, String rightTitle) { Composite result = new Composite((Composite)parent, SWT.BORDER); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.makeColumnsEqualWidth = true; result.setLayout(gridLayout); Label leftLabel = new Label(result, SWT.NONE); if(leftTitle != null) { leftLabel.setText(leftTitle); leftLabel.setLayoutData(labelLayoutData); leftLabel.pack(); } Label rightLabel = new Label(result, SWT.NONE); if(rightTitle != null) { rightLabel.setText(rightTitle); rightLabel.setLayoutData(labelLayoutData); rightLabel.pack(); } result.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_BACKGROUND)); result.layout(true,true); return result; } private Control getButtonPanel(Control parent, final Actions action) { Composite result = new Composite((Composite)parent, SWT.BORDER); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 0; gridLayout.makeColumnsEqualWidth = true; result.setLayout(gridLayout); GridData layoutData = new GridData(GridData.FILL_BOTH); layoutData.verticalAlignment = SWT.CENTER; layoutData.horizontalAlignment = SWT.FILL; if(action.performableBack != null) { Button button = new Button(result, SWT.PUSH); button.setText("Back"); button.setLayoutData(layoutData); button.pack(); button.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { action.performBack(); } }); gridLayout.numColumns++; } if(action.performableUpdate != null) { Button button = new Button(result, SWT.PUSH); button.setText("Update"); button.setLayoutData(layoutData); button.pack(); button.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { action.performUpdate(); } }); gridLayout.numColumns++; } if(action.performableAdd != null) { Button button = new Button(result, SWT.PUSH); button.setText("Add"); button.setLayoutData(layoutData); button.pack(); button.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { action.performAdd(null); } }); gridLayout.numColumns++; } result.layout(true,true); return result; } } private class EditorLabelProvider implements ILabelProvider { @Override public void addListener(ILabelProviderListener listener) { } @Override public void dispose() { int a = 1; } @Override public boolean isLabelProperty(Object element, String property) { int a = 1; return false; } @Override public void removeListener(ILabelProviderListener listener) { int a = 1; } @Override public Image getImage(Object element) { int a = 1; return null; } @Override public String getText(Object element) { int a = 1; return null; } } }
Java
package pl.polidea.treeview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; /** * Tree view, expandable multi-level. * * <pre> * attr ref pl.polidea.treeview.R.styleable#TreeViewList_collapsible * attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_expanded * attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_collapsed * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indent_width * attr ref pl.polidea.treeview.R.styleable#TreeViewList_handle_trackball_press * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_gravity * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_background * attr ref pl.polidea.treeview.R.styleable#TreeViewList_row_background * </pre> */ public class TreeViewList extends ListView { private static final int DEFAULT_COLLAPSED_RESOURCE = R.drawable.collapsed; private static final int DEFAULT_EXPANDED_RESOURCE = R.drawable.expanded; private static final int DEFAULT_INDENT = 0; private static final int DEFAULT_GRAVITY = Gravity.LEFT | Gravity.CENTER_VERTICAL; private Drawable expandedDrawable; private Drawable collapsedDrawable; private Drawable rowBackgroundDrawable; private Drawable indicatorBackgroundDrawable; private int indentWidth = 0; private int indicatorGravity = 0; private AbstractTreeViewAdapter< ? > treeAdapter; private boolean collapsible; private boolean handleTrackballPress; public TreeViewList(final Context context, final AttributeSet attrs) { this(context, attrs, R.style.treeViewListStyle); } public TreeViewList(final Context context) { this(context, null); } public TreeViewList(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); parseAttributes(context, attrs); } private void parseAttributes(final Context context, final AttributeSet attrs) { final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TreeViewList); expandedDrawable = a.getDrawable(R.styleable.TreeViewList_src_expanded); if (expandedDrawable == null) { expandedDrawable = context.getResources().getDrawable( DEFAULT_EXPANDED_RESOURCE); } collapsedDrawable = a .getDrawable(R.styleable.TreeViewList_src_collapsed); if (collapsedDrawable == null) { collapsedDrawable = context.getResources().getDrawable( DEFAULT_COLLAPSED_RESOURCE); } indentWidth = a.getDimensionPixelSize( R.styleable.TreeViewList_indent_width, DEFAULT_INDENT); indicatorGravity = a.getInteger( R.styleable.TreeViewList_indicator_gravity, DEFAULT_GRAVITY); indicatorBackgroundDrawable = a .getDrawable(R.styleable.TreeViewList_indicator_background); rowBackgroundDrawable = a .getDrawable(R.styleable.TreeViewList_row_background); collapsible = a.getBoolean(R.styleable.TreeViewList_collapsible, true); handleTrackballPress = a.getBoolean( R.styleable.TreeViewList_handle_trackball_press, true); } @Override public void setAdapter(final ListAdapter adapter) { if (!(adapter instanceof AbstractTreeViewAdapter)) { throw new TreeConfigurationException( "The adapter is not of TreeViewAdapter type"); } treeAdapter = (AbstractTreeViewAdapter< ? >) adapter; syncAdapter(); super.setAdapter(treeAdapter); } private void syncAdapter() { treeAdapter.setCollapsedDrawable(collapsedDrawable); treeAdapter.setExpandedDrawable(expandedDrawable); treeAdapter.setIndicatorGravity(indicatorGravity); treeAdapter.setIndentWidth(indentWidth); treeAdapter.setIndicatorBackgroundDrawable(indicatorBackgroundDrawable); treeAdapter.setRowBackgroundDrawable(rowBackgroundDrawable); treeAdapter.setCollapsible(collapsible); if (handleTrackballPress) { setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(final AdapterView< ? > parent, final View view, final int position, final long id) { treeAdapter.handleItemClick(view, view.getTag()); } }); } else { setOnClickListener(null); } } public void setExpandedDrawable(final Drawable expandedDrawable) { this.expandedDrawable = expandedDrawable; syncAdapter(); treeAdapter.refresh(); } public void setCollapsedDrawable(final Drawable collapsedDrawable) { this.collapsedDrawable = collapsedDrawable; syncAdapter(); treeAdapter.refresh(); } public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) { this.rowBackgroundDrawable = rowBackgroundDrawable; syncAdapter(); treeAdapter.refresh(); } public void setIndicatorBackgroundDrawable( final Drawable indicatorBackgroundDrawable) { this.indicatorBackgroundDrawable = indicatorBackgroundDrawable; syncAdapter(); treeAdapter.refresh(); } public void setIndentWidth(final int indentWidth) { this.indentWidth = indentWidth; syncAdapter(); treeAdapter.refresh(); } public void setIndicatorGravity(final int indicatorGravity) { this.indicatorGravity = indicatorGravity; syncAdapter(); treeAdapter.refresh(); } public void setCollapsible(final boolean collapsible) { this.collapsible = collapsible; syncAdapter(); treeAdapter.refresh(); } public void setHandleTrackballPress(final boolean handleTrackballPress) { this.handleTrackballPress = handleTrackballPress; syncAdapter(); treeAdapter.refresh(); } public Drawable getExpandedDrawable() { return expandedDrawable; } public Drawable getCollapsedDrawable() { return collapsedDrawable; } public Drawable getRowBackgroundDrawable() { return rowBackgroundDrawable; } public Drawable getIndicatorBackgroundDrawable() { return indicatorBackgroundDrawable; } public int getIndentWidth() { return indentWidth; } public int getIndicatorGravity() { return indicatorGravity; } public boolean isCollapsible() { return collapsible; } public boolean isHandleTrackballPress() { return handleTrackballPress; } }
Java
package pl.polidea.treeview; import android.util.Log; /** * Allows to build tree easily in sequential mode (you have to know levels of * all the tree elements upfront). You should rather use this class rather than * manager if you build initial tree from some external data source. * * @param <T> */ public class TreeBuilder<T> { private static final String TAG = TreeBuilder.class.getSimpleName(); private final TreeStateManager<T> manager; private T lastAddedId = null; private int lastLevel = -1; public TreeBuilder(final TreeStateManager<T> manager) { this.manager = manager; } public void clear() { manager.clear(); } /** * Adds new relation to existing tree. Child is set as the last child of the * parent node. Parent has to already exist in the tree, child cannot yet * exist. This method is mostly useful in case you add entries layer by * layer - i.e. first top level entries, then children for all parents, then * grand-children and so on. * * @param parent * parent id * @param child * child id */ public synchronized void addRelation(final T parent, final T child) { Log.d(TAG, "Adding relation parent:" + parent + " -> child: " + child); manager.addAfterChild(parent, child, null); lastAddedId = child; lastLevel = manager.getLevel(child); } /** * Adds sequentially new node. Using this method is the simplest way of * building tree - if you have all the elements in the sequence as they * should be displayed in fully-expanded tree. You can combine it with add * relation - for example you can add information about few levels using * {@link addRelation} and then after the right level is added as parent, * you can continue adding them using sequential operation. * * @param id * id of the node * @param level * its level */ public synchronized void sequentiallyAddNextNode(final T id, final int level) { Log.d(TAG, "Adding sequentiall node " + id + " at level " + level); if (lastAddedId == null) { addNodeToParentOneLevelDown(null, id, level); } else { if (level <= lastLevel) { final T parent = findParentAtLevel(lastAddedId, level - 1); addNodeToParentOneLevelDown(parent, id, level); } else { addNodeToParentOneLevelDown(lastAddedId, id, level); } } } /** * Find parent of the node at the level specified. * * @param node * node from which we start * @param levelToFind * level which we are looking for * @return the node found (null if it is topmost node). */ private T findParentAtLevel(final T node, final int levelToFind) { T parent = manager.getParent(node); while (parent != null) { if (manager.getLevel(parent) == levelToFind) { break; } parent = manager.getParent(parent); } return parent; } /** * Adds note to parent at the level specified. But it verifies that the * level is one level down than the parent! * * @param parent * parent parent * @param id * new node id * @param level * should always be parent's level + 1 */ private void addNodeToParentOneLevelDown(final T parent, final T id, final int level) { if (parent == null && level != 0) { throw new TreeConfigurationException("Trying to add new id " + id + " to top level with level != 0 (" + level + ")"); } if (parent != null && manager.getLevel(parent) != level - 1) { throw new TreeConfigurationException("Trying to add new id " + id + " <" + level + "> to " + parent + " <" + manager.getLevel(parent) + ">. The difference in levels up is bigger than 1."); } manager.addAfterChild(parent, id, null); setLastAdded(id, level); } private void setLastAdded(final T id, final int level) { lastAddedId = id; lastLevel = level; } }
Java
package pl.polidea.treeview; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import android.database.DataSetObserver; /** * In-memory manager of tree state. * * @param <T> * type of identifier */ public class InMemoryTreeStateManager<T> implements TreeStateManager<T> { private static final long serialVersionUID = 1L; private final Map<T, InMemoryTreeNode<T>> allNodes = new HashMap<T, InMemoryTreeNode<T>>(); private final InMemoryTreeNode<T> topSentinel = new InMemoryTreeNode<T>( null, null, -1, true); private transient List<T> visibleListCache = null; // lasy initialised private transient List<T> unmodifiableVisibleList = null; private boolean visibleByDefault = true; private final transient Set<DataSetObserver> observers = new HashSet<DataSetObserver>(); private synchronized void internalDataSetChanged() { visibleListCache = null; unmodifiableVisibleList = null; for (final DataSetObserver observer : observers) { observer.onChanged(); } } /** * If true new nodes are visible by default. * * @param visibleByDefault * if true, then newly added nodes are expanded by default */ public void setVisibleByDefault(final boolean visibleByDefault) { this.visibleByDefault = visibleByDefault; } private InMemoryTreeNode<T> getNodeFromTreeOrThrow(final T id) { if (id == null) { throw new NodeNotInTreeException("(null)"); } final InMemoryTreeNode<T> node = allNodes.get(id); if (node == null) { throw new NodeNotInTreeException(id.toString()); } return node; } private InMemoryTreeNode<T> getNodeFromTreeOrThrowAllowRoot(final T id) { if (id == null) { return topSentinel; } return getNodeFromTreeOrThrow(id); } private void expectNodeNotInTreeYet(final T id) { final InMemoryTreeNode<T> node = allNodes.get(id); if (node != null) { throw new NodeAlreadyInTreeException(id.toString(), node.toString()); } } @Override public synchronized TreeNodeInfo<T> getNodeInfo(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrow(id); final List<InMemoryTreeNode<T>> children = node.getChildren(); boolean expanded = false; if (!children.isEmpty() && children.get(0).isVisible()) { expanded = true; } return new TreeNodeInfo<T>(id, node.getLevel(), !children.isEmpty(), node.isVisible(), expanded); } @Override public synchronized List<T> getChildren(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); return node.getChildIdList(); } @Override public synchronized T getParent(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); return node.getParent(); } private boolean getChildrenVisibility(final InMemoryTreeNode<T> node) { boolean visibility; final List<InMemoryTreeNode<T>> children = node.getChildren(); if (children.isEmpty()) { visibility = visibleByDefault; } else { visibility = children.get(0).isVisible(); } return visibility; } @Override public synchronized void addBeforeChild(final T parent, final T newChild, final T beforeChild) { expectNodeNotInTreeYet(newChild); final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent); final boolean visibility = getChildrenVisibility(node); // top nodes are always expanded. if (beforeChild == null) { final InMemoryTreeNode<T> added = node.add(0, newChild, visibility); allNodes.put(newChild, added); } else { final int index = node.indexOf(beforeChild); final InMemoryTreeNode<T> added = node.add(index == -1 ? 0 : index, newChild, visibility); allNodes.put(newChild, added); } if (visibility) { internalDataSetChanged(); } } @Override public synchronized void addAfterChild(final T parent, final T newChild, final T afterChild) { expectNodeNotInTreeYet(newChild); final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent); final boolean visibility = getChildrenVisibility(node); if (afterChild == null) { final InMemoryTreeNode<T> added = node.add( node.getChildrenListSize(), newChild, visibility); allNodes.put(newChild, added); } else { final int index = node.indexOf(afterChild); final InMemoryTreeNode<T> added = node.add( index == -1 ? node.getChildrenListSize() : index, newChild, visibility); allNodes.put(newChild, added); } if (visibility) { internalDataSetChanged(); } } @Override public synchronized void removeNodeRecursively(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); final boolean visibleNodeChanged = removeNodeRecursively(node); final T parent = node.getParent(); final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent); parentNode.removeChild(id); if (visibleNodeChanged) { internalDataSetChanged(); } } private boolean removeNodeRecursively(final InMemoryTreeNode<T> node) { boolean visibleNodeChanged = false; for (final InMemoryTreeNode<T> child : node.getChildren()) { if (removeNodeRecursively(child)) { visibleNodeChanged = true; } } node.clearChildren(); if (node.getId() != null) { allNodes.remove(node.getId()); if (node.isVisible()) { visibleNodeChanged = true; } } return visibleNodeChanged; } private void setChildrenVisibility(final InMemoryTreeNode<T> node, final boolean visible, final boolean recursive) { for (final InMemoryTreeNode<T> child : node.getChildren()) { child.setVisible(visible); if (recursive) { setChildrenVisibility(child, visible, true); } } } @Override public synchronized void expandDirectChildren(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); setChildrenVisibility(node, true, false); internalDataSetChanged(); } @Override public synchronized void expandEverythingBelow(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); setChildrenVisibility(node, true, true); internalDataSetChanged(); } @Override public synchronized void collapseChildren(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); if (node == topSentinel) { for (final InMemoryTreeNode<T> n : topSentinel.getChildren()) { setChildrenVisibility(n, false, true); } } else { setChildrenVisibility(node, false, true); } internalDataSetChanged(); } @Override public synchronized T getNextSibling(final T id) { final T parent = getParent(id); final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent); boolean returnNext = false; for (final InMemoryTreeNode<T> child : parentNode.getChildren()) { if (returnNext) { return child.getId(); } if (child.getId().equals(id)) { returnNext = true; } } return null; } @Override public synchronized T getPreviousSibling(final T id) { final T parent = getParent(id); final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent); final T previousSibling = null; for (final InMemoryTreeNode<T> child : parentNode.getChildren()) { if (child.getId().equals(id)) { return previousSibling; } } return null; } @Override public synchronized boolean isInTree(final T id) { return allNodes.containsKey(id); } @Override public synchronized int getVisibleCount() { return getVisibleList().size(); } @Override public synchronized List<T> getVisibleList() { T currentId = null; if (visibleListCache == null) { visibleListCache = new ArrayList<T>(allNodes.size()); do { currentId = getNextVisible(currentId); if (currentId == null) { break; } else { visibleListCache.add(currentId); } } while (true); } if (unmodifiableVisibleList == null) { unmodifiableVisibleList = Collections .unmodifiableList(visibleListCache); } return unmodifiableVisibleList; } public synchronized T getNextVisible(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); if (!node.isVisible()) { return null; } final List<InMemoryTreeNode<T>> children = node.getChildren(); if (!children.isEmpty()) { final InMemoryTreeNode<T> firstChild = children.get(0); if (firstChild.isVisible()) { return firstChild.getId(); } } final T sibl = getNextSibling(id); if (sibl != null) { return sibl; } T parent = node.getParent(); do { if (parent == null) { return null; } final T parentSibling = getNextSibling(parent); if (parentSibling != null) { return parentSibling; } parent = getNodeFromTreeOrThrow(parent).getParent(); } while (true); } @Override public synchronized void registerDataSetObserver( final DataSetObserver observer) { observers.add(observer); } @Override public synchronized void unregisterDataSetObserver( final DataSetObserver observer) { observers.remove(observer); } @Override public int getLevel(final T id) { return getNodeFromTreeOrThrow(id).getLevel(); } @Override public Integer[] getHierarchyDescription(final T id) { final int level = getLevel(id); final Integer[] hierarchy = new Integer[level + 1]; int currentLevel = level; T currentId = id; T parent = getParent(currentId); while (currentLevel >= 0) { hierarchy[currentLevel--] = getChildren(parent).indexOf(currentId); currentId = parent; parent = getParent(parent); } return hierarchy; } private void appendToSb(final StringBuilder sb, final T id) { if (id != null) { final TreeNodeInfo<T> node = getNodeInfo(id); final int indent = node.getLevel() * 4; final char[] indentString = new char[indent]; Arrays.fill(indentString, ' '); sb.append(indentString); sb.append(node.toString()); sb.append(Arrays.asList(getHierarchyDescription(id)).toString()); sb.append("\n"); } final List<T> children = getChildren(id); for (final T child : children) { appendToSb(sb, child); } } @Override public synchronized String toString() { final StringBuilder sb = new StringBuilder(); appendToSb(sb, null); return sb.toString(); } @Override public synchronized void clear() { allNodes.clear(); topSentinel.clearChildren(); internalDataSetChanged(); } @Override public void refresh() { internalDataSetChanged(); } }
Java
package pl.polidea.treeview; /** * The node being added is already in the tree. * */ public class NodeAlreadyInTreeException extends RuntimeException { private static final long serialVersionUID = 1L; public NodeAlreadyInTreeException(final String id, final String oldNode) { super("The node has already been added to the tree: " + id + ". Old node is:" + oldNode); } }
Java
/** * Provides expandable Tree View implementation. */ package pl.polidea.treeview;
Java
package pl.polidea.treeview; import android.app.Activity; import android.content.Context; import android.database.DataSetObserver; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.ListAdapter; /** * Adapter used to feed the table view. * * @param <T> * class for ID of the tree */ public abstract class AbstractTreeViewAdapter<T> extends BaseAdapter implements ListAdapter { private final TreeStateManager<T> treeStateManager; private final int numberOfLevels; private final LayoutInflater layoutInflater; private int indentWidth = 0; private int indicatorGravity = 0; private Drawable collapsedDrawable; private Drawable expandedDrawable; private Drawable indicatorBackgroundDrawable; private Drawable rowBackgroundDrawable; private final OnClickListener indicatorClickListener = new OnClickListener() { @Override public void onClick(final View v) { @SuppressWarnings("unchecked") final T id = (T) v.getTag(); expandCollapse(id); } }; private boolean collapsible; private final Activity activity; public Activity getActivity() { return activity; } protected TreeStateManager<T> getManager() { return treeStateManager; } protected void expandCollapse(final T id) { final TreeNodeInfo<T> info = treeStateManager.getNodeInfo(id); if (!info.isWithChildren()) { // ignore - no default action return; } if (info.isExpanded()) { treeStateManager.collapseChildren(id); } else { treeStateManager.expandDirectChildren(id); } } private void calculateIndentWidth() { if (expandedDrawable != null) { indentWidth = Math.max(getIndentWidth(), expandedDrawable.getIntrinsicWidth()); } if (collapsedDrawable != null) { indentWidth = Math.max(getIndentWidth(), collapsedDrawable.getIntrinsicWidth()); } } public AbstractTreeViewAdapter(final Activity activity, final TreeStateManager<T> treeStateManager, final int numberOfLevels) { this.activity = activity; this.treeStateManager = treeStateManager; this.layoutInflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.numberOfLevels = numberOfLevels; this.collapsedDrawable = null; this.expandedDrawable = null; this.rowBackgroundDrawable = null; this.indicatorBackgroundDrawable = null; } @Override public void registerDataSetObserver(final DataSetObserver observer) { treeStateManager.registerDataSetObserver(observer); } @Override public void unregisterDataSetObserver(final DataSetObserver observer) { treeStateManager.unregisterDataSetObserver(observer); } @Override public int getCount() { return treeStateManager.getVisibleCount(); } @Override public Object getItem(final int position) { return getItemId(position); } public T getTreeId(final int position) { return treeStateManager.getVisibleList().get(position); } public TreeNodeInfo<T> getTreeNodeInfo(final int position) { return treeStateManager.getNodeInfo(getTreeId(position)); } @Override public boolean hasStableIds() { // NOPMD return true; } @Override public int getItemViewType(final int position) { return getTreeNodeInfo(position).getLevel(); } @Override public int getViewTypeCount() { return numberOfLevels; } @Override public boolean isEmpty() { return getCount() == 0; } @Override public boolean areAllItemsEnabled() { // NOPMD return true; } @Override public boolean isEnabled(final int position) { // NOPMD return true; } protected int getTreeListItemWrapperId() { return R.layout.tree_list_item_wrapper; } @Override public final View getView(final int position, final View convertView, final ViewGroup parent) { final TreeNodeInfo<T> nodeInfo = getTreeNodeInfo(position); if (convertView == null) { final LinearLayout layout = (LinearLayout) layoutInflater.inflate( getTreeListItemWrapperId(), null); return populateTreeItem(layout, getNewChildView(nodeInfo), nodeInfo, true); } else { final LinearLayout linear = (LinearLayout) convertView; final FrameLayout frameLayout = (FrameLayout) linear .findViewById(R.id.treeview_list_item_frame); final View childView = frameLayout.getChildAt(0); updateView(childView, nodeInfo); return populateTreeItem(linear, childView, nodeInfo, false); } } /** * Called when new view is to be created. * * @param treeNodeInfo * node info * @return view that should be displayed as tree content */ public abstract View getNewChildView(TreeNodeInfo<T> treeNodeInfo); /** * Called when new view is going to be reused. You should update the view * and fill it in with the data required to display the new information. You * can also create a new view, which will mean that the old view will not be * reused. * * @param view * view that should be updated with the new values * @param treeNodeInfo * node info used to populate the view * @return view to used as row indented content */ public abstract View updateView(View view, TreeNodeInfo<T> treeNodeInfo); /** * Retrieves background drawable for the node. * * @param treeNodeInfo * node info * @return drawable returned as background for the whole row. Might be null, * then default background is used */ public Drawable getBackgroundDrawable(final TreeNodeInfo<T> treeNodeInfo) { // NOPMD return null; } private Drawable getDrawableOrDefaultBackground(final Drawable r) { if (r == null) { return activity.getResources() .getDrawable(R.drawable.list_selector_background).mutate(); } else { return r; } } public final LinearLayout populateTreeItem(final LinearLayout layout, final View childView, final TreeNodeInfo<T> nodeInfo, final boolean newChildView) { final Drawable individualRowDrawable = getBackgroundDrawable(nodeInfo); layout.setBackgroundDrawable(individualRowDrawable == null ? getDrawableOrDefaultBackground(rowBackgroundDrawable) : individualRowDrawable); final LinearLayout.LayoutParams indicatorLayoutParams = new LinearLayout.LayoutParams( calculateIndentation(nodeInfo), LayoutParams.FILL_PARENT); final LinearLayout indicatorLayout = (LinearLayout) layout .findViewById(R.id.treeview_list_item_image_layout); indicatorLayout.setGravity(indicatorGravity); indicatorLayout.setLayoutParams(indicatorLayoutParams); final ImageView image = (ImageView) layout .findViewById(R.id.treeview_list_item_image); image.setImageDrawable(getDrawable(nodeInfo)); image.setBackgroundDrawable(getDrawableOrDefaultBackground(indicatorBackgroundDrawable)); image.setScaleType(ScaleType.CENTER); image.setTag(nodeInfo.getId()); if (nodeInfo.isWithChildren() && collapsible) { image.setOnClickListener(indicatorClickListener); } else { image.setOnClickListener(null); } layout.setTag(nodeInfo.getId()); final FrameLayout frameLayout = (FrameLayout) layout .findViewById(R.id.treeview_list_item_frame); final FrameLayout.LayoutParams childParams = new FrameLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); if (newChildView) { frameLayout.addView(childView, childParams); } frameLayout.setTag(nodeInfo.getId()); return layout; } protected int calculateIndentation(final TreeNodeInfo<T> nodeInfo) { return getIndentWidth() * (nodeInfo.getLevel() + (collapsible ? 1 : 0)); } private Drawable getDrawable(final TreeNodeInfo<T> nodeInfo) { if (!nodeInfo.isWithChildren() || !collapsible) { return getDrawableOrDefaultBackground(indicatorBackgroundDrawable); } if (nodeInfo.isExpanded()) { return expandedDrawable; } else { return collapsedDrawable; } } public void setIndicatorGravity(final int indicatorGravity) { this.indicatorGravity = indicatorGravity; } public void setCollapsedDrawable(final Drawable collapsedDrawable) { this.collapsedDrawable = collapsedDrawable; calculateIndentWidth(); } public void setExpandedDrawable(final Drawable expandedDrawable) { this.expandedDrawable = expandedDrawable; calculateIndentWidth(); } public void setIndentWidth(final int indentWidth) { this.indentWidth = indentWidth; calculateIndentWidth(); } public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) { this.rowBackgroundDrawable = rowBackgroundDrawable; } public void setIndicatorBackgroundDrawable( final Drawable indicatorBackgroundDrawable) { this.indicatorBackgroundDrawable = indicatorBackgroundDrawable; } public void setCollapsible(final boolean collapsible) { this.collapsible = collapsible; } public void refresh() { treeStateManager.refresh(); } private int getIndentWidth() { return indentWidth; } @SuppressWarnings("unchecked") public void handleItemClick(final View view, final Object id) { expandCollapse((T) id); } }
Java
package pl.polidea.treeview; /** * Exception thrown when there is a problem with configuring tree. * */ public class TreeConfigurationException extends RuntimeException { private static final long serialVersionUID = 1L; public TreeConfigurationException(final String detailMessage) { super(detailMessage); } }
Java
package pl.polidea.treeview; import java.io.Serializable; import java.util.LinkedList; import java.util.List; /** * Node. It is package protected so that it cannot be used outside. * * @param <T> * type of the identifier used by the tree */ class InMemoryTreeNode<T> implements Serializable { private static final long serialVersionUID = 1L; private final T id; private final T parent; private final int level; private boolean visible = true; private final List<InMemoryTreeNode<T>> children = new LinkedList<InMemoryTreeNode<T>>(); private List<T> childIdListCache = null; public InMemoryTreeNode(final T id, final T parent, final int level, final boolean visible) { super(); this.id = id; this.parent = parent; this.level = level; this.visible = visible; } public int indexOf(final T id) { return getChildIdList().indexOf(id); } /** * Cache is built lasily only if needed. The cache is cleaned on any * structure change for that node!). * * @return list of ids of children */ public synchronized List<T> getChildIdList() { if (childIdListCache == null) { childIdListCache = new LinkedList<T>(); for (final InMemoryTreeNode<T> n : children) { childIdListCache.add(n.getId()); } } return childIdListCache; } public boolean isVisible() { return visible; } public void setVisible(final boolean visible) { this.visible = visible; } public int getChildrenListSize() { return children.size(); } public synchronized InMemoryTreeNode<T> add(final int index, final T child, final boolean visible) { childIdListCache = null; // Note! top levell children are always visible (!) final InMemoryTreeNode<T> newNode = new InMemoryTreeNode<T>(child, getId(), getLevel() + 1, getId() == null ? true : visible); children.add(index, newNode); return newNode; } /** * Note. This method should technically return unmodifiable collection, but * for performance reason on small devices we do not do it. * * @return children list */ public List<InMemoryTreeNode<T>> getChildren() { return children; } public synchronized void clearChildren() { children.clear(); childIdListCache = null; } public synchronized void removeChild(final T child) { final int childIndex = indexOf(child); if (childIndex != -1) { children.remove(childIndex); childIdListCache = null; } } @Override public String toString() { return "InMemoryTreeNode [id=" + getId() + ", parent=" + getParent() + ", level=" + getLevel() + ", visible=" + visible + ", children=" + children + ", childIdListCache=" + childIdListCache + "]"; } T getId() { return id; } T getParent() { return parent; } int getLevel() { return level; } }
Java
package pl.polidea.treeview; import java.io.Serializable; import java.util.List; import android.database.DataSetObserver; /** * Manages information about state of the tree. It only keeps information about * tree elements, not the elements themselves. * * @param <T> * type of the identifier for nodes in the tree */ public interface TreeStateManager<T> extends Serializable { /** * Returns array of integers showing the location of the node in hierarchy. * It corresponds to heading numbering. {0,0,0} in 3 level node is the first * node {0,0,1} is second leaf (assuming that there are two leaves in first * subnode of the first node). * * @param id * id of the node * @return textual description of the hierarchy in tree for the node. */ Integer[] getHierarchyDescription(T id); /** * Returns level of the node. * * @param id * id of the node * @return level in the tree */ int getLevel(T id); /** * Returns information about the node. * * @param id * node id * @return node info */ TreeNodeInfo<T> getNodeInfo(T id); /** * Returns children of the node. * * @param id * id of the node or null if asking for top nodes * @return children of the node */ List<T> getChildren(T id); /** * Returns parent of the node. * * @param id * id of the node * @return parent id or null if no parent */ T getParent(T id); /** * Adds the node before child or at the beginning. * * @param parent * id of the parent node. If null - adds at the top level * @param newChild * new child to add if null - adds at the beginning. * @param beforeChild * child before which to add the new child */ void addBeforeChild(T parent, T newChild, T beforeChild); /** * Adds the node after child or at the end. * * @param parent * id of the parent node. If null - adds at the top level. * @param newChild * new child to add. If null - adds at the end. * @param afterChild * child after which to add the new child */ void addAfterChild(T parent, T newChild, T afterChild); /** * Removes the node and all children from the tree. * * @param id * id of the node to remove or null if all nodes are to be * removed. */ void removeNodeRecursively(T id); /** * Expands all children of the node. * * @param id * node which children should be expanded. cannot be null (top * nodes are always expanded!). */ void expandDirectChildren(T id); /** * Expands everything below the node specified. Might be null - then expands * all. * * @param id * node which children should be expanded or null if all nodes * are to be expanded. */ void expandEverythingBelow(T id); /** * Collapse children. * * @param id * id collapses everything below node specified. If null, * collapses everything but top-level nodes. */ void collapseChildren(T id); /** * Returns next sibling of the node (or null if no further sibling). * * @param id * node id * @return the sibling (or null if no next) */ T getNextSibling(T id); /** * Returns previous sibling of the node (or null if no previous sibling). * * @param id * node id * @return the sibling (or null if no previous) */ T getPreviousSibling(T id); /** * Checks if given node is already in tree. * * @param id * id of the node * @return true if node is already in tree. */ boolean isInTree(T id); /** * Count visible elements. * * @return number of currently visible elements. */ int getVisibleCount(); /** * Returns visible node list. * * @return return the list of all visible nodes in the right sequence */ List<T> getVisibleList(); /** * Registers observers with the manager. * * @param observer * observer */ void registerDataSetObserver(final DataSetObserver observer); /** * Unregisters observers with the manager. * * @param observer * observer */ void unregisterDataSetObserver(final DataSetObserver observer); /** * Cleans tree stored in manager. After this operation the tree is empty. * */ void clear(); /** * Refreshes views connected to the manager. */ void refresh(); }
Java
package pl.polidea.treeview; /** * This exception is thrown when the tree does not contain node requested. * */ public class NodeNotInTreeException extends RuntimeException { private static final long serialVersionUID = 1L; public NodeNotInTreeException(final String id) { super("The tree does not contain the node specified: " + id); } }
Java
package pl.polidea.treeview; /** * Information about the node. * * @param <T> * type of the id for the tree */ public class TreeNodeInfo<T> { private final T id; private final int level; private final boolean withChildren; private final boolean visible; private final boolean expanded; /** * Creates the node information. * * @param id * id of the node * @param level * level of the node * @param withChildren * whether the node has children. * @param visible * whether the tree node is visible. * @param expanded * whether the tree node is expanded * */ public TreeNodeInfo(final T id, final int level, final boolean withChildren, final boolean visible, final boolean expanded) { super(); this.id = id; this.level = level; this.withChildren = withChildren; this.visible = visible; this.expanded = expanded; } public T getId() { return id; } public boolean isWithChildren() { return withChildren; } public boolean isVisible() { return visible; } public boolean isExpanded() { return expanded; } public int getLevel() { return level; } @Override public String toString() { return "TreeNodeInfo [id=" + id + ", level=" + level + ", withChildren=" + withChildren + ", visible=" + visible + ", expanded=" + expanded + "]"; } }
Java
/** * Provides just demo of the TreeView widget. */ package pl.polidea.treeview.demo;
Java
package pl.polidea.treeview.demo; import java.util.Arrays; import java.util.Set; import pl.polidea.treeview.AbstractTreeViewAdapter; import pl.polidea.treeview.R; import pl.polidea.treeview.TreeNodeInfo; import pl.polidea.treeview.TreeStateManager; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import android.widget.TextView; /** * This is a very simple adapter that provides very basic tree view with a * checkboxes and simple item description. * */ class SimpleStandardAdapter extends AbstractTreeViewAdapter<Long> { private final Set<Long> selected; private final OnCheckedChangeListener onCheckedChange = new OnCheckedChangeListener() { @Override public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) { final Long id = (Long) buttonView.getTag(); changeSelected(isChecked, id); } }; private void changeSelected(final boolean isChecked, final Long id) { if (isChecked) { selected.add(id); } else { selected.remove(id); } } public SimpleStandardAdapter(final TreeViewListDemo treeViewListDemo, final Set<Long> selected, final TreeStateManager<Long> treeStateManager, final int numberOfLevels) { super(treeViewListDemo, treeStateManager, numberOfLevels); this.selected = selected; } private String getDescription(final long id) { final Integer[] hierarchy = getManager().getHierarchyDescription(id); return "Node " + id + Arrays.asList(hierarchy); } @Override public View getNewChildView(final TreeNodeInfo<Long> treeNodeInfo) { final LinearLayout viewLayout = (LinearLayout) getActivity() .getLayoutInflater().inflate(R.layout.demo_list_item, null); return updateView(viewLayout, treeNodeInfo); } @Override public LinearLayout updateView(final View view, final TreeNodeInfo<Long> treeNodeInfo) { final LinearLayout viewLayout = (LinearLayout) view; final TextView descriptionView = (TextView) viewLayout .findViewById(R.id.demo_list_item_description); final TextView levelView = (TextView) viewLayout .findViewById(R.id.demo_list_item_level); descriptionView.setText(getDescription(treeNodeInfo.getId())); levelView.setText(Integer.toString(treeNodeInfo.getLevel())); final CheckBox box = (CheckBox) viewLayout .findViewById(R.id.demo_list_checkbox); box.setTag(treeNodeInfo.getId()); if (treeNodeInfo.isWithChildren()) { box.setVisibility(View.GONE); } else { box.setVisibility(View.VISIBLE); box.setChecked(selected.contains(treeNodeInfo.getId())); } box.setOnCheckedChangeListener(onCheckedChange); return viewLayout; } @Override public void handleItemClick(final View view, final Object id) { final Long longId = (Long) id; final TreeNodeInfo<Long> info = getManager().getNodeInfo(longId); if (info.isWithChildren()) { super.handleItemClick(view, id); } else { final ViewGroup vg = (ViewGroup) view; final CheckBox cb = (CheckBox) vg .findViewById(R.id.demo_list_checkbox); cb.performClick(); } } @Override public long getItemId(final int position) { return getTreeId(position); } }
Java
package pl.polidea.treeview.demo; import java.util.Set; import pl.polidea.treeview.R; import pl.polidea.treeview.TreeNodeInfo; import pl.polidea.treeview.TreeStateManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; final class FancyColouredVariousSizesAdapter extends SimpleStandardAdapter { public FancyColouredVariousSizesAdapter(final TreeViewListDemo activity, final Set<Long> selected, final TreeStateManager<Long> treeStateManager, final int numberOfLevels) { super(activity, selected, treeStateManager, numberOfLevels); } @Override public LinearLayout updateView(final View view, final TreeNodeInfo<Long> treeNodeInfo) { final LinearLayout viewLayout = super.updateView(view, treeNodeInfo); final TextView descriptionView = (TextView) viewLayout .findViewById(R.id.demo_list_item_description); final TextView levelView = (TextView) viewLayout .findViewById(R.id.demo_list_item_level); descriptionView.setTextSize(20 - 2 * treeNodeInfo.getLevel()); levelView.setTextSize(20 - 2 * treeNodeInfo.getLevel()); return viewLayout; } @Override public Drawable getBackgroundDrawable(final TreeNodeInfo<Long> treeNodeInfo) { switch (treeNodeInfo.getLevel()) { case 0: return new ColorDrawable(Color.WHITE); case 1: return new ColorDrawable(Color.GRAY); case 2: return new ColorDrawable(Color.YELLOW); default: return null; } } }
Java
package pl.polidea.treeview.demo; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import pl.polidea.treeview.InMemoryTreeStateManager; import pl.polidea.treeview.R; import pl.polidea.treeview.TreeBuilder; import pl.polidea.treeview.TreeNodeInfo; import pl.polidea.treeview.TreeStateManager; import pl.polidea.treeview.TreeViewList; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; /** * Demo activity showing how the tree view can be used. * */ public class TreeViewListDemo extends Activity { private enum TreeType implements Serializable { SIMPLE, FANCY } private final Set<Long> selected = new HashSet<Long>(); private static final String TAG = TreeViewListDemo.class.getSimpleName(); private TreeViewList treeView; private static final int[] DEMO_NODES = new int[] { 0, 0, 1, 1, 1, 2, 2, 1, 1, 2, 1, 0, 0, 0, 1, 2, 3, 2, 0, 0, 1, 2, 0, 1, 2, 0, 1 }; private static final int LEVEL_NUMBER = 4; private TreeStateManager<Long> manager = null; private FancyColouredVariousSizesAdapter fancyAdapter; private SimpleStandardAdapter simpleAdapter; private TreeType treeType; private boolean collapsible; @SuppressWarnings("unchecked") @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); TreeType newTreeType = null; boolean newCollapsible; if (savedInstanceState == null) { manager = new InMemoryTreeStateManager<Long>(); TreeBuilder<Long> treeBuilder = new TreeBuilder<Long>(manager); for (int i = 0; i < DEMO_NODES.length; i++) { treeBuilder.sequentiallyAddNextNode((long) i, DEMO_NODES[i]); } Log.d(TAG, manager.toString()); newTreeType = TreeType.SIMPLE; newCollapsible = true; } else { manager = (TreeStateManager<Long>) savedInstanceState .getSerializable("treeManager"); newTreeType = (TreeType) savedInstanceState .getSerializable("treeType"); newCollapsible = savedInstanceState.getBoolean("collapsible"); } setContentView(R.layout.main_demo); treeView = (TreeViewList) findViewById(R.id.mainTreeView); fancyAdapter = new FancyColouredVariousSizesAdapter(this, selected, manager, LEVEL_NUMBER); simpleAdapter = new SimpleStandardAdapter(this, selected, manager, LEVEL_NUMBER); setTreeAdapter(newTreeType); setCollapsible(newCollapsible); registerForContextMenu(treeView); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putSerializable("treeManager", manager); outState.putSerializable("treeType", treeType); outState.putBoolean("collapsible", this.collapsible); super.onSaveInstanceState(outState); } protected final void setTreeAdapter(TreeType newTreeType) { this.treeType = newTreeType; switch (newTreeType) { case SIMPLE: treeView.setAdapter(simpleAdapter); break; case FANCY: treeView.setAdapter(fancyAdapter); break; default: treeView.setAdapter(simpleAdapter); } } protected final void setCollapsible(boolean newCollapsible) { this.collapsible = newCollapsible; treeView.setCollapsible(this.collapsible); } @Override public boolean onCreateOptionsMenu(final Menu menu) { final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onPrepareOptionsMenu(final Menu menu) { final MenuItem collapsibleMenu = menu .findItem(R.id.collapsible_menu_item); if (collapsible) { collapsibleMenu.setTitle(R.string.collapsible_menu_disable); collapsibleMenu.setTitleCondensed(getResources().getString( R.string.collapsible_condensed_disable)); } else { collapsibleMenu.setTitle(R.string.collapsible_menu_enable); collapsibleMenu.setTitleCondensed(getResources().getString( R.string.collapsible_condensed_enable)); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.simple_menu_item: setTreeAdapter(TreeType.SIMPLE); break; case R.id.fancy_menu_item: setTreeAdapter(TreeType.FANCY); break; case R.id.collapsible_menu_item: setCollapsible(!this.collapsible); break; case R.id.expand_all_menu_item: manager.expandEverythingBelow(null); break; case R.id.collapse_all_menu_item: manager.collapseChildren(null); break; default: return false; } return true; } @Override public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) { final AdapterContextMenuInfo adapterInfo = (AdapterContextMenuInfo) menuInfo; final long id = adapterInfo.id; final TreeNodeInfo<Long> info = manager.getNodeInfo(id); final MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.context_menu, menu); if (info.isWithChildren()) { if (info.isExpanded()) { menu.findItem(R.id.context_menu_expand_item).setVisible(false); menu.findItem(R.id.context_menu_expand_all).setVisible(false); } else { menu.findItem(R.id.context_menu_collapse).setVisible(false); } } else { menu.findItem(R.id.context_menu_expand_item).setVisible(false); menu.findItem(R.id.context_menu_expand_all).setVisible(false); menu.findItem(R.id.context_menu_collapse).setVisible(false); } super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(final MenuItem item) { final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); final long id = info.id; switch (item.getItemId()) { case R.id.context_menu_collapse: manager.collapseChildren(id); return true; case R.id.context_menu_expand_all: manager.expandEverythingBelow(id); return true; case R.id.context_menu_expand_item: manager.expandDirectChildren(id); return true; case R.id.context_menu_delete: manager.removeNodeRecursively(id); return true; default: return super.onContextItemSelected(item); } } }
Java
package ArchiveClasses; import java.io.File; import java.util.ArrayList; import java.util.Scanner; public class ArchiveOperations { private static ArrayList<Integer> NodesVector = new ArrayList<Integer>(); private static ArrayList<ArrayList<Integer>> ListsVector = new ArrayList<ArrayList<Integer>>(); private static int NUMBER_OF_EDGES = 0; private static int lastCase = 0; private static int pointer = 0; private static void createNodesVector(String archive) { Scanner arc = null; try { arc = new Scanner(new File(archive)); int aux = pointer; while (aux != 0) { arc.nextInt(); aux--; } NUMBER_OF_EDGES = arc.nextInt(); aux = 2 * NUMBER_OF_EDGES; while (aux != 0) { int node = arc.nextInt(); if (!NodesVector.contains(node)) NodesVector.add(node); aux--; } } catch (Exception e) { System.out.println("Error on creating nodes' vector!\n" + e); } finally { if (arc != null) arc.close(); } } private static void createListsVector(String archive) { Scanner arc = null; for (int i = 0; i < NodesVector.size(); i++) ListsVector.add(i, new ArrayList<Integer>()); try { arc = new Scanner(new File(archive)); int aux = pointer; while (aux != 0) { arc.nextInt(); aux--; } arc.nextInt(); aux = NUMBER_OF_EDGES; while (aux != 0) { int first_node = arc.nextInt(), second_node = arc.nextInt(), index = NodesVector .indexOf(first_node); ListsVector.get(index).add(second_node); aux--; } } catch (Exception e) { System.out.println("Error on creating lists' vector!\n" + e); } finally { if (arc != null) arc.close(); } try { arc = new Scanner(new File(archive)); int aux = pointer; while (aux != 0) { arc.nextInt(); aux--; } arc.nextInt(); aux = NUMBER_OF_EDGES; while (aux != 0) { int first_node = arc.nextInt(), second_node = arc.nextInt(), index = NodesVector .indexOf(second_node); ListsVector.get(index).add(first_node); aux--; } } catch (Exception e) { System.out.println("Error on creating lists' vector!" + e); } finally { if (arc != null) arc.close(); } } private static void auxFinder(ArrayList<Integer> list, int TTL, ArrayList<Integer> ReachableNodes, ArrayList<Integer> excludedNodes) { for (Integer node : list) { if (TTL == 0) return; else { if (!ReachableNodes.contains(node) && !excludedNodes.contains(node)) { ReachableNodes.add(node); excludedNodes.add(node); } auxFinder(ListsVector.get(NodesVector.indexOf(node)), TTL - 1, ReachableNodes, excludedNodes); } } } private static void findUnreachableNodes(String archive) { Scanner arc = null; try { arc = new Scanner(new File(archive)); pointer += 2 * NUMBER_OF_EDGES + 1; int aux = pointer; while (aux != 0) { arc.nextInt(); aux--; } boolean flag = true; do { int node = arc.nextInt(); int TTL = arc.nextInt(); if (node == 0 && TTL == 0) { flag = false; } else { ArrayList<Integer> list = ListsVector.get(NodesVector .indexOf(node)); ArrayList<Integer> excludedNodes = new ArrayList<Integer>(); ArrayList<Integer> ReachableNodes = new ArrayList<Integer>(); ArrayList<Integer> UnreachableNodes = new ArrayList<Integer>(); excludedNodes.add(node); auxFinder(list, TTL, ReachableNodes, excludedNodes); for (Integer element : NodesVector) if (!ReachableNodes.contains(element) && element != node) UnreachableNodes.add(element); System.out.println("\n\nCase " + ++lastCase + ": Unreachable Nodes from node " + node + " with TTL " + TTL + ":\n" + UnreachableNodes); } } while (flag); if (!flag && arc.hasNext()) { if (arc.nextInt() != 0) { pointer += 2 * (lastCase + 1); NodesVector = new ArrayList<Integer>(); ListsVector = new ArrayList<ArrayList<Integer>>(); NUMBER_OF_EDGES = 0; read(archive); } } } catch (Exception e) { System.out.println("Error on finding reachable nodes!\n" + e); } finally { if (arc != null) arc.close(); } } public static void read(String archive) { createNodesVector(archive); createListsVector(archive); findUnreachableNodes(archive); } }
Java
package GraphClasses; public class Main { public static void main(String[] args) { ArchiveClasses.ArchiveOperations.read("archive"); } }
Java
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.walkaround.slob.client; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.waveprotocol.wave.model.document.indexed.IndexedDocument; import org.waveprotocol.wave.model.document.operation.Automatons; import org.waveprotocol.wave.model.document.operation.DocOp; import org.waveprotocol.wave.model.document.operation.algorithm.DocOpCollector; import org.waveprotocol.wave.model.document.operation.algorithm.DocOpInverter; import org.waveprotocol.wave.model.document.operation.algorithm.Transformer; import org.waveprotocol.wave.model.document.operation.automaton.AutomatonDocument; import org.waveprotocol.wave.model.document.operation.impl.DocOpUtil; import org.waveprotocol.wave.model.document.raw.impl.Element; import org.waveprotocol.wave.model.document.raw.impl.Node; import org.waveprotocol.wave.model.document.raw.impl.Text; import org.waveprotocol.wave.model.document.util.DocProviders; import org.waveprotocol.wave.model.operation.OperationException; import org.waveprotocol.wave.model.operation.OperationPair; import org.waveprotocol.wave.model.operation.OperationRuntimeException; import org.waveprotocol.wave.model.operation.TransformException; import org.waveprotocol.wave.model.testing.RandomDocOpGenerator; import org.waveprotocol.wave.model.testing.RandomDocOpGenerator.Parameters; import org.waveprotocol.wave.model.testing.RandomDocOpGenerator.RandomProvider; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; /** * @author danilatos@google.com (Daniel Danilatos) */ public final class ChannelTestUtil { private ChannelTestUtil(){} private static final TransformQueue.Transformer<DocOp> transformer = new TransformQueue.Transformer<DocOp>() { @Override public OperationPair<DocOp> transform(DocOp clientOp, DocOp serverOp) { try { return Transformer.transform(clientOp, serverOp); } catch (TransformException e) { throw new RuntimeException(e); } } @Override public List<DocOp> compact(List<DocOp> clientOps) { if (clientOps.isEmpty()) { return clientOps; } DocOpCollector c = new DocOpCollector(); for (DocOp op : clientOps) { c.add(op); } return ImmutableList.of(c.composeAll()); } }; public static class SometimesCompactingTransformer implements TransformQueue.Transformer<DocOp> { /** Set this to control compacting behaviour */ public boolean compact = true; @Override public OperationPair<DocOp> transform(DocOp clientOp, DocOp serverOp) { return transformer.transform(clientOp, serverOp); } @Override public List<DocOp> compact(List<DocOp> clientOps) { if (compact) { return transformer.compact(clientOps); } else { return clientOps; } } } public static final TransformQueue.Transformer<DocOp> randomlyCompactingTransformer( final int seed) { return new TransformQueue.Transformer<DocOp>() { final Random r = new Random(seed); @Override public OperationPair<DocOp> transform(DocOp clientOp, DocOp serverOp) { return transformer.transform(clientOp, serverOp); } @Override public List<DocOp> compact(List<DocOp> clientOps) { if (r.nextBoolean()) { return clientOps; } else { return transformer.compact(clientOps); } } }; } /** * Convenience wrapper around a document */ static class Doc { final IndexedDocument<Node, Element, Text> doc = DocProviders.POJO.parse(""); final AutomatonDocument autoDoc = Automatons.fromReadable(doc); void consume(DocOp op) throws OperationException { doc.consume(op); } Doc copy() { Doc copy = new Doc(); try { copy.consume(doc.asOperation()); return copy; } catch (OperationException e) { throw new OperationRuntimeException("Invalid other document", e); } } String repr() { return DocOpUtil.toXmlString(doc.asOperation()); } } /** * Represents a message on the wire. */ static class Package { /** * Whether the op originated from the client. This can be true even after * the op has gone through the server and been transformed, and sent back * to the client from the server. */ final boolean clientSourced; final int appliesToRevision; final int resultingRevision; final ImmutableList<DocOp> ops; public Package(int appliesToRevision, boolean clientSourced, List<DocOp> ops) { this.appliesToRevision = appliesToRevision; this.resultingRevision = appliesToRevision + 1; this.clientSourced = clientSourced; this.ops = ImmutableList.copyOf(ops); } @Override public String toString() { return "[" + (clientSourced ? "C" : "S") + appliesToRevision + ", " + ops.size() + ops + "]"; } } /** Restricts to one op in the package */ static class UnitPackage extends Package { public UnitPackage(int appliesToRevision, boolean clientSourced, DocOp op) { super(appliesToRevision, clientSourced, Collections.singletonList(op)); } DocOp onlyOp() { assert ops.size() == 1; return ops.get(0); } } /** * Simulation of the server and the internet between the client and server. */ static class FakeServer { private final RandomProvider r; private final Parameters p; FakeServer(RandomProvider r, Parameters p) { this.r = r; this.p = p; } Doc doc = new Doc(); int nextSendAppliesAtRevision = 0; int lastClientAppliedAtRevision = 0; /** Start of the history log */ int baseVersion = 0; /** Current server revision */ int endRevision = 0; /** Recent operation history */ ArrayList<UnitPackage> history = new ArrayList<UnitPackage>(); /** Operations in flight down the browserchannel to the client */ LinkedList<UnitPackage> browserchannel = new LinkedList<UnitPackage>(); /** Operations in flight on an xhr to the server */ Package xhr; @Override public String toString() { return "Server{ " + baseVersion + " - " + endRevision + "\n " + doc + "\n h:" + history + "\n b:" + browserchannel.size() + browserchannel + "\n x:" + xhr + "\n}"; } void sendToServer(int revision, List<DocOp> ops) { xhr = new Package(revision, true, Lists.newArrayList(ops)); } /** * @return true if there was an op to send */ boolean sendToClient() { assert nextSendAppliesAtRevision <= endRevision; if (nextSendAppliesAtRevision == endRevision) { return false; } browserchannel.add(opAppliedAt(nextSendAppliesAtRevision)); nextSendAppliesAtRevision++; return true; } boolean channelPending() { return !browserchannel.isEmpty(); } UnitPackage clientReceive() { return browserchannel.remove(); } /** * @return true if there was a pending xhr request */ boolean serverReceive() { if (xhr == null) { return false; } int appliesToRev = xhr.appliesToRevision; assert xhr.clientSourced; lastClientAppliedAtRevision = appliesToRev; List<DocOp> ops = Lists.newArrayList(xhr.ops); assert ops.size() > 0; xhr = null; for (int i = appliesToRev; i < endRevision; i++) { DocOp serverOp = opAppliedAt(i).onlyOp(); for (int j = 0; j < ops.size(); j++) { OperationPair<DocOp> pair = transformer.transform(ops.get(j), serverOp); serverOp = pair.serverOp(); ops.set(j, pair.clientOp()); } } for (DocOp op : ops) { apply(op, true); } return true; } UnitPackage opAppliedAt(int revision) { return history.get(revision - baseVersion); } void randomServerOp() { apply(RandomDocOpGenerator.generate(r, p, doc.autoDoc), false); } void apply(DocOp op, boolean clientSourced) { try { doc.consume(op); } catch (OperationException e) { throw new RuntimeException(e); } history.add(new UnitPackage(endRevision, clientSourced, op)); endRevision++; while (sendToClient()){} if (endRevision % 50 == 0) { discardOldHistory(); } checkState(); } Doc at(int historicalRevision) { assert historicalRevision >= 0 && historicalRevision <= endRevision; Doc copy = doc.copy(); int rev = endRevision - 1; for (rev = endRevision - 1; rev >= historicalRevision; rev--) { try { copy.consume(DocOpInverter.invert(opAppliedAt(rev).onlyOp())); } catch (OperationException e) { throw new RuntimeException(e); } } return copy; } void discardOldHistory() { int opsToDiscard = Math.min(lastClientAppliedAtRevision, nextSendAppliesAtRevision) - baseVersion; baseVersion += opsToDiscard; history = Lists.newArrayList(history.subList(opsToDiscard, history.size())); } void checkState() { assert endRevision == history.size() + baseVersion; } int revision() { return endRevision; } boolean xhrInFlight() { return xhr != null; } } }
Java
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.walkaround.slob.client; import org.waveprotocol.wave.client.scheduler.Scheduler.IncrementalTask; import org.waveprotocol.wave.client.scheduler.Scheduler.Schedulable; import org.waveprotocol.wave.client.scheduler.Scheduler.Task; import org.waveprotocol.wave.client.scheduler.TimerService; /** * Convenience class that stubs out all methods of {@link TimerService}. * * @author danilatos@google.com (Daniel Danilatos) */ // TODO(danilatos): Move this class into the scheduler.testing package // once the dust has settled with the open source jars? public class StubTimerService implements TimerService { @Override public void cancel(Schedulable job) { throw new AssertionError("Not implemented"); } @Override public double currentTimeMillis() { throw new AssertionError("Not implemented"); } @Override public int elapsedMillis() { throw new AssertionError("Not implemented"); } @Override public boolean isScheduled(Schedulable job) { throw new AssertionError("Not implemented"); } @Override public void schedule(Task task) { throw new AssertionError("Not implemented"); } @Override public void schedule(IncrementalTask process) { throw new AssertionError("Not implemented"); } @Override public void scheduleDelayed(Task task, int minimumTime) { throw new AssertionError("Not implemented"); } @Override public void scheduleDelayed(IncrementalTask process, int minimumTime) { throw new AssertionError("Not implemented"); } @Override public void scheduleRepeating(IncrementalTask process, int minimumTime, int interval) { throw new AssertionError("Not implemented"); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.escape; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; /** * An object that converts literal text into a format safe for inclusion in a particular context * (such as an XML document). Typically (but not always), the inverse process of "unescaping" the * text is performed automatically by the relevant parser. * * <p>For example, an XML escaper would convert the literal string {@code "Foo<Bar>"} into {@code * "Foo&lt;Bar&gt;"} to prevent {@code "<Bar>"} from being confused with an XML tag. When the * resulting XML document is parsed, the parser API will return this text as the original literal * string {@code "Foo<Bar>"}. * * <p>An {@code Escaper} instance is required to be stateless, and safe when used concurrently by * multiple threads. * * <p>The two primary implementations of this interface are {@link CharEscaper} and {@link * UnicodeEscaper}. They are heavily optimized for performance and greatly simplify the task of * implementing new escapers. It is strongly recommended that when implementing a new escaper you * extend one of these classes. If you find that you are unable to achieve the desired behavior * using either of these classes, please contact the Java libraries team for advice. * * <p>Several popular escapers are defined as constants in classes like {@link * com.google.common.html.HtmlEscapers}, {@link com.google.common.xml.XmlEscapers}, and {@link * SourceCodeEscapers}. To create your own escapers, use {@link CharEscaperBuilder}, or extend * {@link CharEscaper} or {@code UnicodeEscaper}. * * @author David Beaumont * @since 11.0 */ @Beta @GwtCompatible public abstract class Escaper { // TODO(user): If there are no custom implementations, add a package private constructor. /** * Returns the escaped form of a given literal string. * * <p>Note that this method may treat input characters differently depending on the specific * escaper implementation. * * <ul> * <li>{@link UnicodeEscaper} handles <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> * correctly, including surrogate character pairs. If the input is badly formed the escaper * should throw {@link IllegalArgumentException}. * <li>{@link CharEscaper} handles Java characters independently and does not verify the input * for well formed characters. A CharEscaper should not be used in situations where input is * not guaranteed to be restricted to the Basic Multilingual Plane (BMP). * </ul> * * @param string the literal string to be escaped * @return the escaped form of {@code string} * @throws NullPointerException if {@code string} is null * @throws IllegalArgumentException if {@code string} contains badly formed UTF-16 or cannot be * escaped for any other reason */ public abstract String escape(String string); private final Function<String, String> asFunction = new Function<String, String>() { @Override public String apply(String from) { return escape(from); } }; /** * Returns a {@link Function} that invokes {@link #escape(String)} on this escaper. */ public Function<String, String> asFunction() { return asFunction; } }
Java
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.escape; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; /** * An object that converts literal text into a format safe for inclusion in a particular context * (such as an XML document). Typically (but not always), the inverse process of "unescaping" the * text is performed automatically by the relevant parser. * * <p>For example, an XML escaper would convert the literal string {@code "Foo<Bar>"} into {@code * "Foo&lt;Bar&gt;"} to prevent {@code "<Bar>"} from being confused with an XML tag. When the * resulting XML document is parsed, the parser API will return this text as the original literal * string {@code "Foo<Bar>"}. * * <p>A {@code CharEscaper} instance is required to be stateless, and safe when used concurrently by * multiple threads. * * <p>Several popular escapers are defined as constants in classes like {@link * com.google.common.html.HtmlEscapers}, {@link com.google.common.xml.XmlEscapers}, and {@link * SourceCodeEscapers}. To create your own escapers extend this class and implement the {@link * #escape(char)} method. * * @author Sven Mawson * @since 11.0 */ @Beta @GwtCompatible public abstract class CharEscaper extends Escaper { /** * Returns the escaped form of a given literal string. * * @param string the literal string to be escaped * @return the escaped form of {@code string} * @throws NullPointerException if {@code string} is null */ @Override public String escape(String string) { checkNotNull(string); // GWT specific check (do not optimize) // Inlineable fast-path loop which hands off to escapeSlow() only if needed int length = string.length(); for (int index = 0; index < length; index++) { if (escape(string.charAt(index)) != null) { return escapeSlow(string, index); } } return string; } /** * Returns the escaped form of a given literal string, starting at the given index. This method is * called by the {@link #escape(String)} method when it discovers that escaping is required. It is * protected to allow subclasses to override the fastpath escaping function to inline their * escaping test. See {@link CharEscaperBuilder} for an example usage. * * @param s the literal string to be escaped * @param index the index to start escaping from * @return the escaped form of {@code string} * @throws NullPointerException if {@code string} is null */ protected String escapeSlow(String s, int index) { int slen = s.length(); // Get a destination buffer and setup some loop variables. char[] dest = Platform.charBufferFromThreadLocal(); int destSize = dest.length; int destIndex = 0; int lastEscape = 0; // Loop through the rest of the string, replacing when needed into the // destination buffer, which gets grown as needed as well. for (; index < slen; index++) { // Get a replacement for the current character. char[] r = escape(s.charAt(index)); // If no replacement is needed, just continue. if (r == null) continue; int rlen = r.length; int charsSkipped = index - lastEscape; // This is the size needed to add the replacement, not the full size // needed by the string. We only regrow when we absolutely must. int sizeNeeded = destIndex + charsSkipped + rlen; if (destSize < sizeNeeded) { destSize = sizeNeeded + (slen - index) + DEST_PAD; dest = growBuffer(dest, destIndex, destSize); } // If we have skipped any characters, we need to copy them now. if (charsSkipped > 0) { s.getChars(lastEscape, index, dest, destIndex); destIndex += charsSkipped; } // Copy the replacement string into the dest buffer as needed. if (rlen > 0) { System.arraycopy(r, 0, dest, destIndex, rlen); destIndex += rlen; } lastEscape = index + 1; } // Copy leftover characters if there are any. int charsLeft = slen - lastEscape; if (charsLeft > 0) { int sizeNeeded = destIndex + charsLeft; if (destSize < sizeNeeded) { // Regrow and copy, expensive! No padding as this is the final copy. dest = growBuffer(dest, destIndex, sizeNeeded); } s.getChars(lastEscape, slen, dest, destIndex); destIndex = sizeNeeded; } return new String(dest, 0, destIndex); } /** * Returns the escaped form of the given character, or {@code null} if this character does not * need to be escaped. If an empty array is returned, this effectively strips the input character * from the resulting text. * * <p>If the character does not need to be escaped, this method should return {@code null}, rather * than a one-character array containing the character itself. This enables the escaping algorithm * to perform more efficiently. * * <p>An escaper is expected to be able to deal with any {@code char} value, so this method should * not throw any exceptions. * * @param c the character to escape if necessary * @return the replacement characters, or {@code null} if no escaping was needed */ protected abstract char[] escape(char c); /** * Helper method to grow the character buffer as needed, this only happens once in a while so it's * ok if it's in a method call. If the index passed in is 0 then no copying will be done. */ private static char[] growBuffer(char[] dest, int index, int size) { char[] copy = new char[size]; if (index > 0) { System.arraycopy(dest, 0, copy, 0, index); } return copy; } /** * The amount of padding to use when growing the escape buffer. */ private static final int DEST_PAD = 32; }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.escape; import com.google.common.annotations.GwtCompatible; /** * Methods factored out so that they can be emulated differently in GWT. * * @author Jesse Wilson */ @GwtCompatible(emulated = true) final class Platform { private Platform() {} /** Returns a thread-local 1024-char array. */ static char[] charBufferFromThreadLocal() { return DEST_TL.get(); } /** * A thread-local destination buffer to keep us from creating new buffers. * The starting size is 1024 characters. If we grow past this we don't * put it back in the threadlocal, we just keep going and grow as needed. */ private static final ThreadLocal<char[]> DEST_TL = new ThreadLocal<char[]>() { @Override protected char[] initialValue() { return new char[1024]; } }; }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.escape; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; /** * An {@link Escaper} that converts literal text into a format safe for * inclusion in a particular context (such as an XML document). Typically (but * not always), the inverse process of "unescaping" the text is performed * automatically by the relevant parser. * * <p>For example, an XML escaper would convert the literal string {@code * "Foo<Bar>"} into {@code "Foo&lt;Bar&gt;"} to prevent {@code "<Bar>"} from * being confused with an XML tag. When the resulting XML document is parsed, * the parser API will return this text as the original literal string {@code * "Foo<Bar>"}. * * <p><b>Note:</b> This class is similar to {@link CharEscaper} but with one * very important difference. A CharEscaper can only process Java * <a href="http://en.wikipedia.org/wiki/UTF-16">UTF16</a> characters in * isolation and may not cope when it encounters surrogate pairs. This class * facilitates the correct escaping of all Unicode characters. * * <p>As there are important reasons, including potential security issues, to * handle Unicode correctly if you are considering implementing a new escaper * you should favor using UnicodeEscaper wherever possible. * * <p>A {@code UnicodeEscaper} instance is required to be stateless, and safe * when used concurrently by multiple threads. * * <p>Several popular escapers are defined as constants in classes like {@link * com.google.common.html.HtmlEscapers}, {@link * com.google.common.xml.XmlEscapers}, and {@link SourceCodeEscapers}. To create * your own escapers extend this class and implement the {@link #escape(int)} * method. * * @author David Beaumont * @since 11.0 */ @Beta @GwtCompatible public abstract class UnicodeEscaper extends Escaper { /** The amount of padding (chars) to use when growing the escape buffer. */ private static final int DEST_PAD = 32; /** * Returns the escaped form of the given Unicode code point, or {@code null} * if this code point does not need to be escaped. When called as part of an * escaping operation, the given code point is guaranteed to be in the range * {@code 0 <= cp <= Character#MAX_CODE_POINT}. * * <p>If an empty array is returned, this effectively strips the input * character from the resulting text. * * <p>If the character does not need to be escaped, this method should return * {@code null}, rather than an array containing the character representation * of the code point. This enables the escaping algorithm to perform more * efficiently. * * <p>If the implementation of this method cannot correctly handle a * particular code point then it should either throw an appropriate runtime * exception or return a suitable replacement character. It must never * silently discard invalid input as this may constitute a security risk. * * @param cp the Unicode code point to escape if necessary * @return the replacement characters, or {@code null} if no escaping was * needed */ protected abstract char[] escape(int cp); /** * Scans a sub-sequence of characters from a given {@link CharSequence}, * returning the index of the next character that requires escaping. * * <p><b>Note:</b> When implementing an escaper, it is a good idea to override * this method for efficiency. The base class implementation determines * successive Unicode code points and invokes {@link #escape(int)} for each of * them. If the semantics of your escaper are such that code points in the * supplementary range are either all escaped or all unescaped, this method * can be implemented more efficiently using {@link CharSequence#charAt(int)}. * * <p>Note however that if your escaper does not escape characters in the * supplementary range, you should either continue to validate the correctness * of any surrogate characters encountered or provide a clear warning to users * that your escaper does not validate its input. * * <p>See {@link com.google.common.net.PercentEscaper} for an example. * * @param csq a sequence of characters * @param start the index of the first character to be scanned * @param end the index immediately after the last character to be scanned * @throws IllegalArgumentException if the scanned sub-sequence of {@code csq} * contains invalid surrogate pairs */ protected int nextEscapeIndex(CharSequence csq, int start, int end) { int index = start; while (index < end) { int cp = codePointAt(csq, index, end); if (cp < 0 || escape(cp) != null) { break; } index += Character.isSupplementaryCodePoint(cp) ? 2 : 1; } return index; } /** * Returns the escaped form of a given literal string. * * <p>If you are escaping input in arbitrary successive chunks, then it is not * generally safe to use this method. If an input string ends with an * unmatched high surrogate character, then this method will throw * {@link IllegalArgumentException}. You should ensure your input is valid <a * href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> before calling this * method. * * <p><b>Note:</b> When implementing an escaper it is a good idea to override * this method for efficiency by inlining the implementation of * {@link #nextEscapeIndex(CharSequence, int, int)} directly. Doing this for * {@link com.google.common.net.PercentEscaper} more than doubled the * performance for unescaped strings (as measured by {@link * CharEscapersBenchmark}). * * @param string the literal string to be escaped * @return the escaped form of {@code string} * @throws NullPointerException if {@code string} is null * @throws IllegalArgumentException if invalid surrogate characters are * encountered */ @Override public String escape(String string) { checkNotNull(string); int end = string.length(); int index = nextEscapeIndex(string, 0, end); return index == end ? string : escapeSlow(string, index); } /** * Returns the escaped form of a given literal string, starting at the given * index. This method is called by the {@link #escape(String)} method when it * discovers that escaping is required. It is protected to allow subclasses * to override the fastpath escaping function to inline their escaping test. * See {@link CharEscaperBuilder} for an example usage. * * <p>This method is not reentrant and may only be invoked by the top level * {@link #escape(String)} method. * * @param s the literal string to be escaped * @param index the index to start escaping from * @return the escaped form of {@code string} * @throws NullPointerException if {@code string} is null * @throws IllegalArgumentException if invalid surrogate characters are * encountered */ protected final String escapeSlow(String s, int index) { int end = s.length(); // Get a destination buffer and setup some loop variables. char[] dest = Platform.charBufferFromThreadLocal(); int destIndex = 0; int unescapedChunkStart = 0; while (index < end) { int cp = codePointAt(s, index, end); if (cp < 0) { throw new IllegalArgumentException( "Trailing high surrogate at end of input"); } // It is possible for this to return null because nextEscapeIndex() may // (for performance reasons) yield some false positives but it must never // give false negatives. char[] escaped = escape(cp); int nextIndex = index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1); if (escaped != null) { int charsSkipped = index - unescapedChunkStart; // This is the size needed to add the replacement, not the full // size needed by the string. We only regrow when we absolutely must. int sizeNeeded = destIndex + charsSkipped + escaped.length; if (dest.length < sizeNeeded) { int destLength = sizeNeeded + (end - index) + DEST_PAD; dest = growBuffer(dest, destIndex, destLength); } // If we have skipped any characters, we need to copy them now. if (charsSkipped > 0) { s.getChars(unescapedChunkStart, index, dest, destIndex); destIndex += charsSkipped; } if (escaped.length > 0) { System.arraycopy(escaped, 0, dest, destIndex, escaped.length); destIndex += escaped.length; } // If we dealt with an escaped character, reset the unescaped range. unescapedChunkStart = nextIndex; } index = nextEscapeIndex(s, nextIndex, end); } // Process trailing unescaped characters - no need to account for escaped // length or padding the allocation. int charsSkipped = end - unescapedChunkStart; if (charsSkipped > 0) { int endIndex = destIndex + charsSkipped; if (dest.length < endIndex) { dest = growBuffer(dest, destIndex, endIndex); } s.getChars(unescapedChunkStart, end, dest, destIndex); destIndex = endIndex; } return new String(dest, 0, destIndex); } /** * Returns the Unicode code point of the character at the given index. * * <p>Unlike {@link Character#codePointAt(CharSequence, int)} or * {@link String#codePointAt(int)} this method will never fail silently when * encountering an invalid surrogate pair. * * <p>The behaviour of this method is as follows: * <ol> * <li>If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown. * <li><b>If the character at the specified index is not a surrogate, it is * returned.</b> * <li>If the first character was a high surrogate value, then an attempt is * made to read the next character. * <ol> * <li><b>If the end of the sequence was reached, the negated value of * the trailing high surrogate is returned.</b> * <li><b>If the next character was a valid low surrogate, the code point * value of the high/low surrogate pair is returned.</b> * <li>If the next character was not a low surrogate value, then * {@link IllegalArgumentException} is thrown. * </ol> * <li>If the first character was a low surrogate value, * {@link IllegalArgumentException} is thrown. * </ol> * * @param seq the sequence of characters from which to decode the code point * @param index the index of the first character to decode * @param end the index beyond the last valid character to decode * @return the Unicode code point for the given index or the negated value of * the trailing high surrogate character at the end of the sequence */ protected static final int codePointAt(CharSequence seq, int index, int end) { if (index < end) { char c1 = seq.charAt(index++); if (c1 < Character.MIN_HIGH_SURROGATE || c1 > Character.MAX_LOW_SURROGATE) { // Fast path (first test is probably all we need to do) return c1; } else if (c1 <= Character.MAX_HIGH_SURROGATE) { // If the high surrogate was the last character, return its inverse if (index == end) { return -c1; } // Otherwise look for the low surrogate following it char c2 = seq.charAt(index); if (Character.isLowSurrogate(c2)) { return Character.toCodePoint(c1, c2); } throw new IllegalArgumentException( "Expected low surrogate but got char '" + c2 + "' with value " + (int) c2 + " at index " + index); } else { throw new IllegalArgumentException( "Unexpected low surrogate character '" + c1 + "' with value " + (int) c1 + " at index " + (index - 1)); } } throw new IndexOutOfBoundsException("Index exceeds specified range"); } /** * Helper method to grow the character buffer as needed, this only happens * once in a while so it's ok if it's in a method call. If the index passed * in is 0 then no copying will be done. */ private static char[] growBuffer(char[] dest, int index, int size) { char[] copy = new char[size]; if (index > 0) { System.arraycopy(dest, 0, copy, 0, index); } return copy; } }
Java
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.escape; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.HashMap; import java.util.Map; /** * Simple helper class to build a "sparse" array of objects based on the indexes that were added to * it. The array will be from 0 to the maximum index given. All non-set indexes will contain null * (so it's not really a sparse array, just a pseudo sparse array). The builder can also return a * CharEscaper based on the generated array. * * @author Sven Mawson * @since 11.0 */ @Beta @GwtCompatible public final class CharEscaperBuilder { /** * Simple decorator that turns an array of replacement char[]s into a CharEscaper, this results in * a very fast escape method. */ private static class CharArrayDecorator extends CharEscaper { private final char[][] replacements; private final int replaceLength; CharArrayDecorator(char[][] replacements) { this.replacements = replacements; this.replaceLength = replacements.length; } /* * Overriding escape method to be slightly faster for this decorator. We test the replacements * array directly, saving a method call. */ @Override public String escape(String s) { int slen = s.length(); for (int index = 0; index < slen; index++) { char c = s.charAt(index); if (c < replacements.length && replacements[c] != null) { return escapeSlow(s, index); } } return s; } @Override protected char[] escape(char c) { return c < replaceLength ? replacements[c] : null; } } // Replacement mappings. private final Map<Character, String> map; // The highest index we've seen so far. private int max = -1; /** * Construct a new sparse array builder. */ public CharEscaperBuilder() { this.map = new HashMap<Character, String>(); } /** * Add a new mapping from an index to an object to the escaping. */ public CharEscaperBuilder addEscape(char c, String r) { map.put(c, r); if (c > max) { max = c; } return this; } /** * Add multiple mappings at once for a particular index. */ public CharEscaperBuilder addEscapes(char[] cs, String r) { for (char c : cs) { addEscape(c, r); } return this; } /** * Convert this builder into an array of char[]s where the maximum index is the value of the * highest character that has been seen. The array will be sparse in the sense that any unseen * index will default to null. * * @return a "sparse" array that holds the replacement mappings. */ public char[][] toArray() { char[][] result = new char[max + 1][]; for (Map.Entry<Character, String> entry : map.entrySet()) { result[entry.getKey()] = entry.getValue().toCharArray(); } return result; } /** * Convert this builder into a char escaper which is just a decorator around the underlying array * of replacement char[]s. * * @return an escaper that escapes based on the underlying array. */ public CharEscaper toEscaper() { return new CharArrayDecorator(toArray()); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.net; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.escape.UnicodeEscaper; /** * A {@code UnicodeEscaper} that escapes some set of Java characters using a * UTF-8 based percent enconding scheme. The set of safe characters (those which * remain unescaped) can be specified on construction. * * <p>This class is primarily used for creating URI escapers in * {@link com.google.common.net.UriEscapers} but can be used directly if * required. While URI escapers impose specific semantics on which characters * are considered 'safe', this class has a minimal set of restrictions. * * <p>When escaping a String, the following rules apply: * <ul> * <li>All specified safe characters remain unchanged. * <li>If {@code plusForSpace} was specified, the space character " " is * converted into a plus sign {@code "+"}. * <li>All other characters are converted into one or more bytes using UTF-8 * encoding and each byte is then represented by the 3-character string * "%XX", where "XX" is the two-digit, uppercase, hexadecimal representation * of the byte value. * </ul> * * <p>For performance reasons the only currently supported character encoding of * this class is UTF-8. * * <p><b>Note</b>: This escaper produces uppercase hexadecimal sequences. From * <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>:<br> * <i>"URI producers and normalizers should use uppercase hexadecimal digits * for all percent-encodings."</i> * * @author David Beaumont * @since 11.0 */ @GwtCompatible public final class PercentEscaper extends UnicodeEscaper { // In some escapers spaces are escaped to '+' private static final char[] PLUS_SIGN = { '+' }; // Percent escapers output upper case hex digits (uri escapers require this). private static final char[] UPPER_HEX_DIGITS = "0123456789ABCDEF".toCharArray(); /** * If true we should convert space to the {@code +} character. */ private final boolean plusForSpace; /** * An array of flags where for any {@code char c} if {@code safeOctets[c]} is * true then {@code c} should remain unmodified in the output. If * {@code c > safeOctets.length} then it should be escaped. */ private final boolean[] safeOctets; /** * Constructs a percent escaper with the specified safe characters and * optional handling of the space character. * * <p>Not that it is allowed, but not necessarily desirable to specify {@code %} * as a safe character. This has the effect of creating an escaper which has no * well defined inverse but it can be useful when escaping additional characters. * * @param safeChars a non null string specifying additional safe characters * for this escaper (the ranges 0..9, a..z and A..Z are always safe and * should not be specified here) * @param plusForSpace true if ASCII space should be escaped to {@code +} * rather than {@code %20} * @throws IllegalArgumentException if any of the parameters were invalid */ public PercentEscaper(String safeChars, boolean plusForSpace) { // TODO(user): Switch to static factory methods for creation now that class is final. // TODO(user): Support escapers where alphanumeric chars are not safe. checkNotNull(safeChars); // eager for GWT. // Avoid any misunderstandings about the behavior of this escaper if (safeChars.matches(".*[0-9A-Za-z].*")) { throw new IllegalArgumentException( "Alphanumeric characters are always 'safe' and should not be " + "explicitly specified"); } safeChars += "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"; // Avoid ambiguous parameters. Safe characters are never modified so if // space is a safe character then setting plusForSpace is meaningless. if (plusForSpace && safeChars.contains(" ")) { throw new IllegalArgumentException( "plusForSpace cannot be specified when space is a 'safe' character"); } this.plusForSpace = plusForSpace; this.safeOctets = createSafeOctets(safeChars); } /** * Creates a boolean array with entries corresponding to the character values * specified in safeChars set to true. The array is as small as is required to * hold the given character information. */ private static boolean[] createSafeOctets(String safeChars) { int maxChar = -1; char[] safeCharArray = safeChars.toCharArray(); for (char c : safeCharArray) { maxChar = Math.max(c, maxChar); } boolean[] octets = new boolean[maxChar + 1]; for (char c : safeCharArray) { octets[c] = true; } return octets; } /* * Overridden for performance. For unescaped strings this improved the * performance of the uri escaper from ~760ns to ~400ns as measured by * {@link CharEscapersBenchmark}. */ @Override protected int nextEscapeIndex(CharSequence csq, int index, int end) { for (; index < end; index++) { char c = csq.charAt(index); if (c >= safeOctets.length || !safeOctets[c]) { break; } } return index; } /* * Overridden for performance. For unescaped strings this improved the * performance of the uri escaper from ~400ns to ~170ns as measured by * {@link CharEscapersBenchmark}. */ @Override public String escape(String s) { checkNotNull(s); int slen = s.length(); for (int index = 0; index < slen; index++) { char c = s.charAt(index); if (c >= safeOctets.length || !safeOctets[c]) { return escapeSlow(s, index); } } return s; } /** * Escapes the given Unicode code point in UTF-8. */ @Override protected char[] escape(int cp) { // We should never get negative values here but if we do it will throw an // IndexOutOfBoundsException, so at least it will get spotted. if (cp < safeOctets.length && safeOctets[cp]) { return null; } else if (cp == ' ' && plusForSpace) { return PLUS_SIGN; } else if (cp <= 0x7F) { // Single byte UTF-8 characters // Start with "%--" and fill in the blanks char[] dest = new char[3]; dest[0] = '%'; dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; dest[1] = UPPER_HEX_DIGITS[cp >>> 4]; return dest; } else if (cp <= 0x7ff) { // Two byte UTF-8 characters [cp >= 0x80 && cp <= 0x7ff] // Start with "%--%--" and fill in the blanks char[] dest = new char[6]; dest[0] = '%'; dest[3] = '%'; dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; cp >>>= 2; dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[1] = UPPER_HEX_DIGITS[0xC | cp]; return dest; } else if (cp <= 0xffff) { // Three byte UTF-8 characters [cp >= 0x800 && cp <= 0xffff] // Start with "%E-%--%--" and fill in the blanks char[] dest = new char[9]; dest[0] = '%'; dest[1] = 'E'; dest[3] = '%'; dest[6] = '%'; dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; cp >>>= 2; dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; cp >>>= 2; dest[2] = UPPER_HEX_DIGITS[cp]; return dest; } else if (cp <= 0x10ffff) { char[] dest = new char[12]; // Four byte UTF-8 characters [cp >= 0xffff && cp <= 0x10ffff] // Start with "%F-%--%--%--" and fill in the blanks dest[0] = '%'; dest[1] = 'F'; dest[3] = '%'; dest[6] = '%'; dest[9] = '%'; dest[11] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[10] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; cp >>>= 2; dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[7] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; cp >>>= 2; dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; cp >>>= 4; dest[4] = UPPER_HEX_DIGITS[0x8 | (cp & 0x3)]; cp >>>= 2; dest[2] = UPPER_HEX_DIGITS[cp & 0x7]; return dest; } else { // If this ever happens it is due to bug in UnicodeEscaper, not bad input. throw new IllegalArgumentException( "Invalid unicode character value " + cp); } } }
Java