code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.reactor; import java.io.IOException; /** * HttpCore NIO is based on the Reactor pattern as described by Doug Lea. * The purpose of I/O reactors is to react to I/O events and to dispatch event * notifications to individual I/O sessions. The main idea of I/O reactor * pattern is to break away from the one thread per connection model imposed * by the classic blocking I/O model. * <p> * The IOReactor interface represents an abstract object implementing * the Reactor pattern. * <p> * I/O reactors usually employ a small number of dispatch threads (often as * few as one) to dispatch I/O event notifications to a much greater number * (often as many as several thousands) of I/O sessions or connections. It is * generally recommended to have one dispatch thread per CPU core. * * @since 4.0 */ public interface IOReactor { /** * Returns the current status of the reactor. * * @return reactor status. */ IOReactorStatus getStatus(); /** * Starts the reactor and initiates the dispatch of I/O event notifications * to the given {@link IOEventDispatch}. * * @param eventDispatch the I/O event dispatch. * @throws IOException in case of an I/O error. */ void execute(IOEventDispatch eventDispatch) throws IOException; /** * Initiates shutdown of the reactor and blocks approximately for the given * period of time in milliseconds waiting for the reactor to terminate all * active connections, to shut down itself and to release system resources * it currently holds. * * @param waitMs wait time in milliseconds. * @throws IOException in case of an I/O error. */ void shutdown(long waitMs) throws IOException; /** * Initiates shutdown of the reactor and blocks for a default period of * time waiting for the reactor to terminate all active connections, to shut * down itself and to release system resources it currently holds. It is * up to individual implementations to decide for how long this method can * remain blocked. * * @throws IOException in case of an I/O error. */ void shutdown() throws IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.reactor; /** * IOReactorStatus represents an internal status of an I/O reactor. * * @since 4.0 */ public enum IOReactorStatus { /** * The reactor is inactive / has not been started */ INACTIVE, /** * The reactor is active / processing I/O events. */ ACTIVE, /** * Shutdown of the reactor has been requested. */ SHUTDOWN_REQUEST, /** * The reactor is shutting down. */ SHUTTING_DOWN, /** * The reactor has shut down. */ SHUT_DOWN; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.reactor; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.CharacterCodingException; import org.apache.http.util.CharArrayBuffer; /** * Session input buffer for non-blocking connections. This interface facilitates * intermediate buffering of input data streamed from a source channel and * reading buffered data to a destination, usually {@link ByteBuffer} or * {@link WritableByteChannel}. This interface also provides methods for reading * lines of text. * * @since 4.0 */ public interface SessionInputBuffer { /** * Determines if the buffer contains data. * * @return <code>true</code> if there is data in the buffer, * <code>false</code> otherwise. */ boolean hasData(); /** * Returns the length of this buffer. * * @return buffer length. */ int length(); /** * Makes an attempt to fill the buffer with data from the given * {@link ReadableByteChannel}. * * @param src the source channel * @return The number of bytes read, possibly zero, or <tt>-1</tt> if the * channel has reached end-of-stream. * @throws IOException in case of an I/O error. */ int fill(ReadableByteChannel src) throws IOException; /** * Reads one byte from the buffer. If the buffer is empty this method can * throw a runtime exception. The exact type of runtime exception thrown * by this method depends on implementation. * * @return one byte */ int read(); /** * Reads a sequence of bytes from this buffer into the destination buffer, * up to the given maximum limit. The exact number of bytes transferred * depends on availability of data in this buffer and capacity of the * destination buffer, but cannot be more than <code>maxLen</code> value. * * @param dst the destination buffer. * @param maxLen the maximum number of bytes to be read. * @return The number of bytes read, possibly zero. */ int read(ByteBuffer dst, int maxLen); /** * Reads a sequence of bytes from this buffer into the destination buffer. * The exact number of bytes transferred depends on availability of data * in this buffer and capacity of the destination buffer. * * @param dst the destination buffer. * @return The number of bytes read, possibly zero. */ int read(ByteBuffer dst); /** * Reads a sequence of bytes from this buffer into the destination channel, * up to the given maximum limit. The exact number of bytes transferred * depends on availability of data in this buffer, but cannot be more than * <code>maxLen</code> value. * * @param dst the destination channel. * @param maxLen the maximum number of bytes to be read. * @return The number of bytes read, possibly zero. * @throws IOException in case of an I/O error. */ int read(WritableByteChannel dst, int maxLen) throws IOException; /** * Reads a sequence of bytes from this buffer into the destination channel. * The exact number of bytes transferred depends on availability of data in * this buffer. * * @param dst the destination channel. * @return The number of bytes read, possibly zero. * @throws IOException in case of an I/O error. */ int read(WritableByteChannel dst) throws IOException; /** * Attempts to transfer a complete line of characters up to a line delimiter * from this buffer to the destination buffer. If a complete line is * available in the buffer, the sequence of chars is transferred to the * destination buffer the method returns <code>true</code>. The line * delimiter itself is discarded. If a complete line is not available in * the buffer, this method returns <code>false</code> without transferring * anything to the destination buffer. If <code>endOfStream</code> parameter * is set to <code>true</code> this method assumes the end of stream has * been reached and the content currently stored in the buffer should be * treated as a complete line. * <p> * The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param dst the destination buffer. * @param endOfStream * @return <code>true</code> if a sequence of chars representing a complete * line has been transferred to the destination buffer, <code>false</code> * otherwise. * * @throws CharacterCodingException in case a character encoding or decoding * error occurs. */ boolean readLine(CharArrayBuffer dst, boolean endOfStream) throws CharacterCodingException; /** * Attempts to transfer a complete line of characters up to a line delimiter * from this buffer to a newly created string. If a complete line is * available in the buffer, the sequence of chars is transferred to a newly * created string. The line delimiter itself is discarded. If a complete * line is not available in the buffer, this method returns * <code>null</code>. If <code>endOfStream</code> parameter * is set to <code>true</code> this method assumes the end of stream has * been reached and the content currently stored in the buffer should be * treated as a complete line. * <p> * The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param endOfStream * @return a string representing a complete line, if available. * <code>null</code> otherwise. * * @throws CharacterCodingException in case a character encoding or decoding * error occurs. */ String readLine(boolean endOfStream) throws CharacterCodingException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.reactor; import java.io.IOException; import java.net.SocketAddress; /** * SessionRequest interface represents a request to establish a new connection * (or session) to a remote host. It can be used to monitor the status of the * request, to block waiting for its completion, or to cancel the request. * <p> * Implementations of this interface are expected to be threading safe. * * @since 4.0 */ public interface SessionRequest { /** * Returns socket address of the remote host. * * @return socket address of the remote host */ SocketAddress getRemoteAddress(); /** * Returns local socket address. * * @return local socket address. */ SocketAddress getLocalAddress(); /** * Returns attachment object will be added to the session's context upon * initialization. This object can be used to pass an initial processing * state to the protocol handler. * * @return attachment object. */ Object getAttachment(); /** * Determines whether the request has been completed (either successfully * or unsuccessfully). * * @return <code>true</true> if the request has been completed, * <code>false</true> if still pending. */ boolean isCompleted(); /** * Returns {@link IOSession} instance created as a result of this request * or <code>null</code> if the request is still pending. * * @return I/O session or <code>null</code> if the request is still pending. */ IOSession getSession(); /** * Returns {@link IOException} instance if the request could not be * successfully executed due to an I/O error or <code>null</code> if no * error occurred to this point. * * @return I/O exception or <code>null</code> if no error occurred to * this point. */ IOException getException(); /** * Waits for completion of this session request. * * @throws InterruptedException in case the execution process was * interrupted. */ void waitFor() throws InterruptedException; /** * Sets connect timeout value in milliseconds. * * @param timeout connect timeout value in milliseconds. */ void setConnectTimeout(int timeout); /** * Returns connect timeout value in milliseconds. * * @return connect timeout value in milliseconds. */ int getConnectTimeout(); /** * Cancels the request. Invocation of this method will set the status of * the request to completed and will unblock threads blocked in * the {{@link #waitFor()}} method. */ void cancel(); }
Java
/* * $Date: * * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.reactor; /** * SessionBufferStatus interface is intended to query the status of session * I/O buffers. * * @since 4.0 */ public interface SessionBufferStatus { /** * Determines if the session input buffer contains data. * * @return <code>true</code> if the session input buffer contains data, * <code>false</code> otherwise. */ boolean hasBufferedInput(); /** * Determines if the session output buffer contains data. * * @return <code>true</code> if the session output buffer contains data, * <code>false</code> otherwise. */ boolean hasBufferedOutput(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.reactor; import java.io.IOException; /** * Abstract exception handler intended to deal with potentially recoverable * I/O exceptions thrown by an I/O reactor. * * @since 4.0 */ public interface IOReactorExceptionHandler { /** * This method is expected to examine the I/O exception passed as * a parameter and decide whether it is safe to continue execution of * the I/O reactor. * * @param ex potentially recoverable I/O exception * @return <code>true</code> if it is safe to ignore the exception * and continue execution of the I/O reactor; <code>false</code> if the * I/O reactor must throw {@link IOReactorException} and terminate */ boolean handle(IOException ex); /** * This method is expected to examine the runtime exception passed as * a parameter and decide whether it is safe to continue execution of * the I/O reactor. * * @param ex potentially recoverable runtime exception * @return <code>true</code> if it is safe to ignore the exception * and continue execution of the I/O reactor; <code>false</code> if the * I/O reactor must throw {@link RuntimeException} and terminate */ boolean handle(RuntimeException ex); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.reactor; import java.net.SocketAddress; /** * ConnectingIOReactor represents an I/O reactor capable of establishing * connections to remote hosts. * * @since 4.0 */ public interface ConnectingIOReactor extends IOReactor { /** * Requests a connection to a remote host. * <p> * Opening a connection to a remote host usually tends to be a time * consuming process and may take a while to complete. One can monitor and * control the process of session initialization by means of the * {@link SessionRequest} interface. * <p> * There are several parameters one can use to exert a greater control over * the process of session initialization: * <p> * A non-null local socket address parameter can be used to bind the socket * to a specific local address. * <p> * An attachment object can added to the new session's context upon * initialization. This object can be used to pass an initial processing * state to the protocol handler. * <p> * It is often desirable to be able to react to the completion of a session * request asynchronously without having to wait for it, blocking the * current thread of execution. One can optionally provide an implementation * {@link SessionRequestCallback} instance to get notified of events related * to session requests, such as request completion, cancellation, failure or * timeout. * * @param remoteAddress the socket address of the remote host. * @param localAddress the local socket address. Can be <code>null</code>, * in which can the default local address and a random port will be used. * @param attachment the attachment object. Can be <code>null</code>. * @param callback interface. Can be <code>null</code>. * @return session request object. */ SessionRequest connect( SocketAddress remoteAddress, SocketAddress localAddress, Object attachment, SessionRequestCallback callback); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.reactor; /** * IOEventDispatch interface is used by I/O reactors to notify clients of I/O * events pending for a particular session. All methods of this interface are * executed on a dispatch thread of the I/O reactor. Therefore, it is important * that processing that takes place in the event methods will not block the * dispatch thread for too long, as the I/O reactor will be unable to react to * other events. * * @since 4.0 */ public interface IOEventDispatch { /** * Triggered after the given session has been just created. * * @param session the I/O session. */ void connected(IOSession session); /** * Triggered when the given session has input pending. * * @param session the I/O session. */ void inputReady(IOSession session); /** * Triggered when the given session is ready for output. * * @param session the I/O session. */ void outputReady(IOSession session); /** * Triggered when the given session as timed out. * * @param session the I/O session. */ void timeout(IOSession session); /** * Triggered when the given session has been terminated. * * @param session the I/O session. */ void disconnected(IOSession session); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.reactor; import java.io.IOException; /** * I/O exception that can be thrown by an I/O reactor. Usually exceptions * of this type are fatal and are not recoverable. * * @since 4.0 */ public class IOReactorException extends IOException { private static final long serialVersionUID = -4248110651729635749L; public IOReactorException(final String message, final Exception cause) { super(message); if (cause != null) { initCause(cause); } } public IOReactorException(final String message) { super(message); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.reactor; import java.net.SocketAddress; import java.util.Set; import java.io.IOException; /** * ListeningIOReactor represents an I/O reactor capable of listening for * incoming connections on one or several ports. * * @since 4.0 */ public interface ListeningIOReactor extends IOReactor { /** * Opens a new listener endpoint with the given socket address. Once * the endpoint is fully initialized it starts accepting incoming * connections and propagates I/O activity notifications to the I/O event * dispatcher. * <p> * {@link ListenerEndpoint#waitFor()} can be used to wait for the * listener to be come ready to accept incoming connections. * <p> * {@link ListenerEndpoint#close()} can be used to shut down * the listener even before it is fully initialized. * * @param address the socket address to listen on. * @return listener endpoint. */ ListenerEndpoint listen(SocketAddress address); /** * Suspends the I/O reactor preventing it from accepting new connections on * all active endpoints. * * @throws IOException in case of an I/O error. */ void pause() throws IOException; /** * Resumes the I/O reactor restoring its ability to accept incoming * connections on all active endpoints. * * @throws IOException in case of an I/O error. */ void resume() throws IOException; /** * Returns a set of endpoints for this I/O reactor. * * @return set of endpoints. */ Set<ListenerEndpoint> getEndpoints(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.reactor; import java.io.IOException; import java.net.SocketAddress; /** * ListenerEndpoint interface represents an endpoint used by an I/O reactor * to listen for incoming connection from remote clients. * * @since 4.0 */ public interface ListenerEndpoint { /** * Returns the socket address of this endpoint. * * @return socket address. */ SocketAddress getAddress(); /** * Returns an instance of {@link IOException} thrown during initialization * of this endpoint or <code>null</code>, if initialization was successful. * * @return I/O exception object or <code>null</code>. */ IOException getException(); /** * Waits for completion of initialization process of this endpoint. * * @throws InterruptedException in case the initialization process was * interrupted. */ void waitFor() throws InterruptedException; /** * Determines if this endpoint has been closed and is no longer listens * for incoming connections. * * @return <code>true</code> if the endpoint has been closed, * <code>false</code> otherwise. */ boolean isClosed(); /** * Closes this endpoint. The endpoint will stop accepting incoming * connection. */ void close(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.reactor; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.CharacterCodingException; import org.apache.http.util.CharArrayBuffer; /** * Session output buffer for non-blocking connections. This interface * facilitates intermediate buffering of output data streamed out to * a destination channel and writing data to the buffer from a source, usually * {@link ByteBuffer} or {@link ReadableByteChannel}. This interface also * provides methods for writing lines of text. * * @since 4.0 */ public interface SessionOutputBuffer { /** * Determines if the buffer contains data. * * @return <code>true</code> if there is data in the buffer, * <code>false</code> otherwise. */ boolean hasData(); /** * Returns the length of this buffer. * * @return buffer length. */ int length(); /** * Makes an attempt to flush the content of this buffer to the given * destination {@link WritableByteChannel}. * * @param channel the destination channel. * @return The number of bytes written, possibly zero. * @throws IOException in case of an I/O error. */ int flush(WritableByteChannel channel) throws IOException; /** * Copies content of the source buffer into this buffer. The capacity of * the destination will be expanded in order to accommodate the entire * content of the source buffer. * * @param src the source buffer. */ void write(ByteBuffer src); /** * Reads a sequence of bytes from the source channel into this buffer. * * @param src the source channel. */ void write(ReadableByteChannel src) throws IOException; /** * Copies content of the source buffer into this buffer as one line of text * including a line delimiter. The capacity of the destination will be * expanded in order to accommodate the entire content of the source buffer. * <p> * The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param src the source buffer. */ void writeLine(CharArrayBuffer src) throws CharacterCodingException; /** * Copies content of the given string into this buffer as one line of text * including a line delimiter. * The capacity of the destination will be expanded in order to accommodate * the entire string. * <p> * The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param s the string. */ void writeLine(String s) throws IOException; }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.activity; import android.content.SharedPreferences; import android.location.Location; import org.opentraces.metatracker.Constants; public class TrackingState { public int loggingState; public boolean newRoadRating; public int roadRating; public float distance; public Track track = new Track(); public Segment segment = new Segment(); public Waypoint waypoint = new Waypoint(); private SharedPreferences sharedPreferences; public TrackingState(SharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; reset(); } public void load() { distance = sharedPreferences.getFloat("distance", 0.0f); track.load(); waypoint.load(); } public void save() { sharedPreferences.edit().putFloat("distance", distance).commit(); track.save(); waypoint.save(); } public void reset() { loggingState = Constants.DOWN; distance = 0.0f; waypoint.reset(); track.reset(); } public class Track { public int id = -1; public String name = "NO TRACK"; public long creationTime; public void load() { id = sharedPreferences.getInt("track.id", -1); name = sharedPreferences.getString("track.name", "NO TRACK"); } public void save() { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("track.id", id); editor.putString("track.name", name); editor.commit(); } public void reset() { name = "NO TRACK"; id = -1; } } public static class Segment { public int id = -1; } public class Waypoint { public int id = -1; public Location location; public float speed; public float accuracy; public int count; public void load() { id = sharedPreferences.getInt("waypoint.id", -1); count = sharedPreferences.getInt("waypoint.count", 0); } public void save() { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("waypoint.id", id); editor.putInt("waypoint.count", count); editor.commit(); } public void reset() { count = 0; id = -1; location = null; } } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.activity; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.opentraces.metatracker.Constants; import org.opentraces.metatracker.R; import org.opentraces.metatracker.net.OpenTracesClient; public class UploadTrackActivity extends Activity { protected static final int DIALOG_FILENAME = 11; protected static final int PROGRESS_STEPS = 10; private static final int DIALOG_INSTALL_FILEMANAGER = 34; private static final String TAG = "MT.UploadTrack"; private String filePath; private TextView fileNameView; private SharedPreferences sharedPreferences; private final DialogInterface.OnClickListener mFileManagerDownloadDialogListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Uri oiDownload = Uri.parse("market://details?id=org.openintents.filemanager"); Intent oiFileManagerDownloadIntent = new Intent(Intent.ACTION_VIEW, oiDownload); try { startActivity(oiFileManagerDownloadIntent); } catch (ActivityNotFoundException e) { oiDownload = Uri.parse("http://openintents.googlecode.com/files/FileManager-1.1.3.apk"); oiFileManagerDownloadIntent = new Intent(Intent.ACTION_VIEW, oiDownload); startActivity(oiFileManagerDownloadIntent); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); setContentView(R.layout.uploaddialog); fileNameView = (TextView) findViewById(R.id.filename); filePath = null; pickFile(); Button okay = (Button) findViewById(R.id.okayupload_button); okay.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (filePath == null) { return; } uploadFile(filePath); } }); } /* * (non-Javadoc) * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; Builder builder = null; switch (id) { case DIALOG_INSTALL_FILEMANAGER: builder = new AlertDialog.Builder(this); builder .setTitle(R.string.dialog_nofilemanager) .setMessage(R.string.dialog_nofilemanager_message) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_install, mFileManagerDownloadDialogListener) .setNegativeButton(R.string.btn_cancel, null); dialog = builder.create(); break; default: dialog = super.onCreateDialog(id); break; } return dialog; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); // Bundle extras = intent.getExtras(); switch (requestCode) { case Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY: if (resultCode == RESULT_OK && intent != null) { // obtain the filename filePath = intent.getDataString(); if (filePath != null) { // Get rid of URI prefix: if (filePath.startsWith("file://")) { filePath = filePath.substring(7); } fileNameView.setText(filePath); } } break; } } /* http://edwards.sdsu.edu/labsite/index.php/josh/179-android-nuts-and-bolts-vii http://code.google.com/p/openintents/source/browse/trunk/samples/TestFileManager/src/org/openintents/samples/TestFileManager/TestFileManager.java */ private void pickFile() { Intent intent = new Intent(Constants.ACTION_PICK_FILE); intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory() + Constants.EXTERNAL_DIR)); try { startActivityForResult(intent, Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY); } catch (ActivityNotFoundException e) { // No compatible file manager was found: install openintents filemanager. showDialog(DIALOG_INSTALL_FILEMANAGER); } } /* http://edwards.sdsu.edu/labsite/index.php/josh/179-android-nuts-and-bolts-vii http://code.google.com/p/openintents/source/browse/trunk/samples/TestFileManager/src/org/openintents/samples/TestFileManager/TestFileManager.java */ private void uploadFile(String aFilePath) { Intent intent = new Intent(Constants.ACTION_PICK_FILE); intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory() + Constants.EXTERNAL_DIR)); try { ; OpenTracesClient openTracesClient = new OpenTracesClient(sharedPreferences.getString(Constants.PREF_SERVER_URL, "http://geotracing.com/tland")); openTracesClient.createSession(); openTracesClient.login(sharedPreferences.getString(Constants.PREF_SERVER_USER, "no_user"), sharedPreferences.getString(Constants.PREF_SERVER_PASSWORD, "no_passwd")); openTracesClient.uploadFile(aFilePath); openTracesClient.logout(); } catch (Throwable e) { Log.e(TAG, "Error uploading file : ", e); } } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.activity; import org.opentraces.metatracker.R; import android.os.Bundle; import android.preference.PreferenceActivity; /** * Dialog for setting preferences. * * @author Just van den Broecke */ public class SettingsActivity extends PreferenceActivity { @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); addPreferencesFromResource( R.layout.settings ); } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.activity; import android.app.*; import android.content.*; import android.database.ContentObserver; import android.database.Cursor; import android.location.Location; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.opentraces.metatracker.*; import org.opentraces.metatracker.logger.GPSLoggerServiceManager; import java.text.DecimalFormat; public class MainActivity extends Activity { // MENU'S private static final int MENU_SETTINGS = 1; private static final int MENU_TRACKING = 2; private static final int MENU_UPLOAD = 3; private static final int MENU_HELP = 4; private static final int MENU_ABOUT = 5; private static final int DIALOG_INSTALL_OPENGPSTRACKER = 1; private static final int DIALOG_INSTALL_ABOUT = 2; private static DecimalFormat REAL_FORMATTER1 = new DecimalFormat("0.#"); private static DecimalFormat REAL_FORMATTER2 = new DecimalFormat("0.##"); private static final String TAG = "MetaTracker.Main"; private TextView waypointCountView, timeView, distanceView, speedView, roadRatingView, accuracyView; private GPSLoggerServiceManager loggerServiceManager; private TrackingState trackingState; private MediaPlayer mediaPlayer; // private PowerManager.WakeLock wakeLock = null; private static final int COLOR_WHITE = 0xFFFFFFFF; private static final int[] ROAD_RATING_COLORS = {0xFF808080, 0xFFCC0099, 0xFFEE0000, 0xFFFF6600, 0xFFFFCC00, 0xFF33CC33}; private SharedPreferences sharedPreferences; private Button[] roadRatingButtons = new Button[6]; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate()"); super.onCreate(savedInstanceState); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); trackingState = new TrackingState(sharedPreferences); trackingState.load(); setContentView(R.layout.main); getLastTrackingState(); getApplicationContext().getContentResolver().registerContentObserver(Constants.Tracks.CONTENT_URI, true, trackingObserver); // mUnits = new UnitsI18n(this, mUnitsChangeListener); speedView = (TextView) findViewById(R.id.currentSpeed); timeView = (TextView) findViewById(R.id.currentTime); distanceView = (TextView) findViewById(R.id.totalDist); waypointCountView = (TextView) findViewById(R.id.waypointCount); accuracyView = (TextView) findViewById(R.id.currentAccuracy); roadRatingView = (TextView) findViewById(R.id.currentRoadRating); // Capture our button from layout roadRatingButtons[0] = (Button) findViewById(R.id.road_qual_none); roadRatingButtons[1] = (Button) findViewById(R.id.road_qual_nogo); roadRatingButtons[2] = (Button) findViewById(R.id.road_qual_bad); roadRatingButtons[3] = (Button) findViewById(R.id.road_qual_poor); roadRatingButtons[4] = (Button) findViewById(R.id.road_qual_good); roadRatingButtons[5] = (Button) findViewById(R.id.road_qual_best); for (Button button : roadRatingButtons) { button.setOnClickListener(roadRatingButtonListener); } bindGPSLoggingService(); } /** * Called when the activity is started. */ @Override public void onStart() { Log.d(TAG, "onStart()"); super.onStart(); } /** * Called when the activity is started. */ @Override public void onRestart() { Log.d(TAG, "onRestart()"); super.onRestart(); } /** * Called when the activity is resumed. */ @Override public void onResume() { Log.d(TAG, "onResume()"); getLastTrackingState(); // updateBlankingBehavior(); drawScreen(); super.onResume(); } /** * Called when the activity is paused. */ @Override public void onPause() { trackingState.save(); /* if (this.wakeLock != null && this.wakeLock.isHeld()) { this.wakeLock.release(); Log.w(TAG, "onPause(): Released lock to keep screen on!"); } */ Log.d(TAG, "onPause()"); super.onPause(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy()"); trackingState.save(); /* if (wakeLock != null && wakeLock.isHeld()) { wakeLock.release(); Log.w(TAG, "onDestroy(): Released lock to keep screen on!"); } */ getApplicationContext().getContentResolver().unregisterContentObserver(trackingObserver); sharedPreferences.unregisterOnSharedPreferenceChangeListener(this.sharedPreferenceChangeListener); unbindGPSLoggingService(); super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); menu.add(ContextMenu.NONE, MENU_TRACKING, ContextMenu.NONE, R.string.menu_tracking).setIcon(R.drawable.ic_menu_movie).setAlphabeticShortcut('T'); menu.add(ContextMenu.NONE, MENU_UPLOAD, ContextMenu.NONE, R.string.menu_upload).setIcon(R.drawable.ic_menu_upload).setAlphabeticShortcut('I'); menu.add(ContextMenu.NONE, MENU_SETTINGS, ContextMenu.NONE, R.string.menu_settings).setIcon(R.drawable.ic_menu_preferences).setAlphabeticShortcut('C'); menu.add(ContextMenu.NONE, MENU_HELP, ContextMenu.NONE, R.string.menu_help).setIcon(R.drawable.ic_menu_help).setAlphabeticShortcut('I'); menu.add(ContextMenu.NONE, MENU_ABOUT, ContextMenu.NONE, R.string.menu_about).setIcon(R.drawable.ic_menu_info_details).setAlphabeticShortcut('A'); return result; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_TRACKING: startOpenGPSTrackerActivity(); break; case MENU_UPLOAD: startActivityForClass("org.opentraces.metatracker", "org.opentraces.metatracker.activity.UploadTrackActivity"); break; case MENU_SETTINGS: startActivity(new Intent(this, SettingsActivity.class)); break; case MENU_ABOUT: try { startActivityForResult(new Intent(Constants.OI_ACTION_SHOW_ABOUT_DIALOG), MENU_ABOUT); } catch (ActivityNotFoundException e) { showDialog(DIALOG_INSTALL_ABOUT); } break; default: showAlert(R.string.menu_message_unsupported); break; } return true; } /* * (non-Javadoc) * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; AlertDialog.Builder builder = null; switch (id) { case DIALOG_INSTALL_OPENGPSTRACKER: builder = new AlertDialog.Builder(this); builder .setTitle(R.string.dialog_noopengpstracker) .setMessage(R.string.dialog_noopengpstracker_message) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_install, mOpenGPSTrackerDownloadDialogListener) .setNegativeButton(R.string.btn_cancel, null); dialog = builder.create(); break; case DIALOG_INSTALL_ABOUT: builder = new AlertDialog.Builder(this); builder .setTitle(R.string.dialog_nooiabout) .setMessage(R.string.dialog_nooiabout_message) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_install, mOiAboutDialogListener) .setNegativeButton(R.string.btn_cancel, null); dialog = builder.create(); return dialog; default: dialog = super.onCreateDialog(id); break; } return dialog; } private void drawTitleBar(String s) { this.setTitle(s); } /** * Called on any update to Tracks table. */ private void onTrackingUpdate() { getLastTrackingState(); if (trackingState.waypoint.count == 1) { sendRoadRating(); } drawScreen(); } /** * Called on any update to Tracks table. */ private synchronized void playPingSound() { if (!sharedPreferences.getBoolean(Constants.PREF_ENABLE_SOUND, false)) { return; } try { if (mediaPlayer == null) { mediaPlayer = MediaPlayer.create(this, R.raw.ping_short); } else { mediaPlayer.stop(); mediaPlayer.prepare(); } mediaPlayer.start(); } catch (Throwable t) { Log.e(TAG, "Error playing sound", t); } } /** * Retrieve the last point of the current track */ private void getLastWaypoint() { Cursor waypoint = null; try { ContentResolver resolver = this.getContentResolver(); waypoint = resolver.query(Uri.withAppendedPath(Constants.Tracks.CONTENT_URI, trackingState.track.id + "/" + Constants.Waypoints.TABLE), new String[]{"max(" + Constants.Waypoints.TABLE + "." + Constants.Waypoints._ID + ")", Constants.Waypoints.LONGITUDE, Constants.Waypoints.LATITUDE, Constants.Waypoints.SPEED, Constants.Waypoints.ACCURACY, Constants.Waypoints.SEGMENT }, null, null, null); if (waypoint != null && waypoint.moveToLast()) { // New point: increase pointcount int waypointId = waypoint.getInt(0); if (waypointId > 0 && trackingState.waypoint.id != waypointId) { trackingState.waypoint.count++; trackingState.waypoint.id = waypoint.getInt(0); // Increase total distance Location newLocation = new Location(this.getClass().getName()); newLocation.setLongitude(waypoint.getDouble(1)); newLocation.setLatitude(waypoint.getDouble(2)); if (trackingState.waypoint.location != null) { float delta = trackingState.waypoint.location.distanceTo(newLocation); // Log.d(TAG, "trackingState.distance=" + trackingState.distance + " delta=" + delta + " ll=" + waypoint.getDouble(1) + ", " +waypoint.getDouble(2)); trackingState.distance += delta; } trackingState.waypoint.location = newLocation; trackingState.waypoint.speed = waypoint.getFloat(3); trackingState.waypoint.accuracy = waypoint.getFloat(4); trackingState.segment.id = waypoint.getInt(5); playPingSound(); } } } finally { if (waypoint != null) { waypoint.close(); } } } private void getLastTrack() { Cursor cursor = null; try { ContentResolver resolver = this.getApplicationContext().getContentResolver(); cursor = resolver.query(Constants.Tracks.CONTENT_URI, new String[]{"max(" + Constants.Tracks._ID + ")", Constants.Tracks.NAME, Constants.Tracks.CREATION_TIME}, null, null, null); if (cursor != null && cursor.moveToLast()) { int trackId = cursor.getInt(0); // Check if new track created if (trackId != trackingState.track.id) { trackingState.reset(); trackingState.save(); } trackingState.track.id = trackId; trackingState.track.name = cursor.getString(1); trackingState.track.creationTime = cursor.getLong(2); } } finally { if (cursor != null) { cursor.close(); } } } private void getLastTrackingState() { getLastTrack(); getLoggingState(); getLastWaypoint(); } private void sendRoadRating() { if (trackingState.roadRating > 0 && trackingState.newRoadRating && loggerServiceManager != null) { Uri media = Uri.withAppendedPath(Constants.NAME_URI, Uri.encode(trackingState.roadRating + "")); loggerServiceManager.storeMediaUri(media); trackingState.newRoadRating = false; } } private void startOpenGPSTrackerActivity() { try { startActivityForClass("nl.sogeti.android.gpstracker", "nl.sogeti.android.gpstracker.viewer.LoggerMap"); } catch (ActivityNotFoundException e) { Log.i(TAG, "Cannot find activity for open-gpstracker"); // No compatible file manager was found: install openintents filemanager. showDialog(DIALOG_INSTALL_OPENGPSTRACKER); } sendRoadRating(); } private void startActivityForClass(String aPackageName, String aClassName) throws ActivityNotFoundException { Intent intent = new Intent(); intent.setClassName(aPackageName, aClassName); startActivity(intent); } private void bindGPSLoggingService() { unbindGPSLoggingService(); ServiceConnection serviceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { getLoggingState(); drawTitleBar(); } public void onServiceDisconnected(ComponentName className) { trackingState.loggingState = Constants.DOWN; } }; loggerServiceManager = new GPSLoggerServiceManager(this); loggerServiceManager.startup(serviceConnection); } private void unbindGPSLoggingService() { if (loggerServiceManager == null) { return; } try { loggerServiceManager.shutdown(); } finally { loggerServiceManager = null; trackingState.loggingState = Constants.DOWN; } } private void getLoggingState() { // Get state from logger if bound trackingState.loggingState = loggerServiceManager == null ? Constants.DOWN : loggerServiceManager.getLoggingState(); // protect for values outside array bounds (set to unknown) if (trackingState.loggingState < 0 || trackingState.loggingState > Constants.LOGGING_STATES.length - 1) { trackingState.loggingState = Constants.UNKNOWN; } } private String getLoggingStateStr() { return Constants.LOGGING_STATES[trackingState.loggingState]; } private void drawTitleBar() { drawTitleBar("MT : " + trackingState.track.name + " : " + getLoggingStateStr()); } private void drawScreen() { drawTitleBar(); drawTripStats(); drawRoadRating(); } /** * Retrieves the numbers of the measured speed and altitude * from the most recent waypoint and * updates UI components with this latest bit of information. */ private void drawTripStats() { try { waypointCountView.setText(trackingState.waypoint.count + ""); long secsDelta = 0L; long hours = 0L; long mins = 0L; long secs = 0L; if (trackingState.track.creationTime != 0) { secsDelta = (System.currentTimeMillis() - trackingState.track.creationTime) / 1000; hours = secsDelta / 3600L; mins = (secsDelta % 3600L) / 60L; secs = ((secsDelta % 3600L) % 60); } timeView.setText(formatTimeNum(hours) + ":" + formatTimeNum(mins) + ":" + formatTimeNum(secs)); speedView.setText(REAL_FORMATTER1.format(3.6f * trackingState.waypoint.speed)); accuracyView.setText(REAL_FORMATTER1.format(trackingState.waypoint.accuracy)); distanceView.setText(REAL_FORMATTER2.format(trackingState.distance / 1000f)); } finally { } } private String formatTimeNum(long n) { return n < 10 ? ("0" + n) : (n + ""); } private void drawRoadRating() { for (int i = 0; i < roadRatingButtons.length; i++) { roadRatingButtons[i].setBackgroundColor(COLOR_WHITE); } if (trackingState.roadRating >= 0) { roadRatingButtons[trackingState.roadRating].setBackgroundColor(ROAD_RATING_COLORS[trackingState.roadRating]); } String roadRatingStr = trackingState.roadRating + ""; roadRatingView.setText(roadRatingStr); } private void showAlert(int aMessage) { new AlertDialog.Builder(this) .setMessage(aMessage) .setPositiveButton("Ok", null) .show(); } private void updateBlankingBehavior() { boolean disableblanking = sharedPreferences.getBoolean(Constants.DISABLEBLANKING, false); if (disableblanking) { /* if (wakeLock == null) { PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG); } wakeLock.acquire(); Log.w(TAG, "Acquired lock to keep screen on!"); */ } } private final DialogInterface.OnClickListener mOiAboutDialogListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Uri oiDownload = Uri.parse("market://details?id=org.openintents.about"); Intent oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload); try { startActivity(oiAboutIntent); } catch (ActivityNotFoundException e) { oiDownload = Uri.parse("http://openintents.googlecode.com/files/AboutApp-1.0.0.apk"); oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload); startActivity(oiAboutIntent); } } }; private final DialogInterface.OnClickListener mOpenGPSTrackerDownloadDialogListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Uri marketUri = Uri.parse("market://details?id=nl.sogeti.android.gpstracker"); Intent downloadIntent = new Intent(Intent.ACTION_VIEW, marketUri); try { startActivity(downloadIntent); } catch (ActivityNotFoundException e) { showAlert(R.string.dialog_failinstallopengpstracker_message); } } }; // Create an anonymous implementation of OnClickListener private View.OnClickListener roadRatingButtonListener = new View.OnClickListener() { public void onClick(View v) { for (int i = 0; i < roadRatingButtons.length; i++) { if (v.getId() == roadRatingButtons[i].getId()) { trackingState.roadRating = i; } } trackingState.newRoadRating = true; drawRoadRating(); sendRoadRating(); } }; private final ContentObserver trackingObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (!selfUpdate) { onTrackingUpdate(); Log.d(TAG, "trackingObserver onTrackingUpdate lastWaypointId=" + trackingState.waypoint.id); } else { Log.w(TAG, "trackingObserver skipping change"); } } }; private final SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Constants.DISABLEBLANKING)) { updateBlankingBehavior(); } } }; }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.xml; /** * Implements a Visitor that does nothin' * $Id: DefaultVisitor.java,v 1.4 2003/01/06 00:23:49 just Exp $ * * @author $Author: just $ - Just van den Broecke - Just Objects B.V. &copy; */ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; public class DefaultVisitor implements Visitor { public void visitDocumentPre(Document document) { } public void visitDocumentPost(Document document) { } public void visitElementPre(Element element) { } public void visitElementPost(Element element) { } public void visitText(Text element) { } } /* * $Log: DefaultVisitor.java,v $ * Revision 1.4 2003/01/06 00:23:49 just * moved devenv to linux * * Revision 1.3 2002/11/14 20:25:20 just * reformat of code only * * Revision 1.2 2000/08/10 19:26:58 just * changes for comments only * * */
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.xml; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; /** * Makes deep copy of an Element for another Document. * $Id: ElementCopyVisitor.java,v 1.4 2003/01/06 00:23:49 just Exp $ * * @author $Author: just $ - Just van den Broecke - Just Objects B.V. &copy; */ public class ElementCopyVisitor extends DefaultVisitor { Document ownerDocument; Element elementOrig; Element elementCopy; Element elementPointer; int level = 0; public ElementCopyVisitor(Document theOwnerDocument, Element theElement) { ownerDocument = theOwnerDocument; elementOrig = theElement; } public Element getCopy() { new TreeWalker(this).traverse(elementOrig); return elementCopy; } public void visitDocumentPre(Document document) { p("visitDocumentPre: level=" + level); } public void visitDocumentPost(Document document) { p("visitDocumentPost: level=" + level); } public void visitElementPre(Element element) { p("visitElementPre: " + element.getTagName() + " level=" + level); // Create the copy; must use target document as factory Element newElement = ownerDocument.createElement(element.getTagName()); // If first time we need to create the copy if (elementCopy == null) { elementCopy = newElement; } else { elementPointer.appendChild(newElement); } // Always point to the last created and appended element elementPointer = newElement; level++; } public void visitElementPost(Element element) { p("visitElementPost: " + element.getTagName() + " level=" + level); DOMUtil.copyAttributes(element, elementPointer); level--; if (level == 0) return; // Always transfer attributes if any if (level > 0) { elementPointer = (Element) elementPointer.getParentNode(); } } public void visitText(Text element) { // Create the copy; must use target document as factory Text newText = ownerDocument.createTextNode(element.getData()); // If first time we need to create the copy if (elementPointer == null) { p("ERROR no element copy"); return; } else { elementPointer.appendChild(newText); } } private void p(String s) { //System.out.println("ElementCopyVisitor: "+s); } } /* * $Log: ElementCopyVisitor.java,v $ * Revision 1.4 2003/01/06 00:23:49 just * moved devenv to linux * * Revision 1.3 2002/11/14 20:25:20 just * reformat of code only * * Revision 1.2 2000/08/10 19:26:58 just * changes for comments only * * */
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.xml; import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; /** * Utility methods for working with a DOM tree. * $Id: DOMUtil.java,v 1.18 2004/09/10 14:20:50 just Exp $ * * @author $Author: just $ - Just van den Broecke - Just Objects B.V. &copy; */ public class DOMUtil { /** * Clears all childnodes in document */ public static void clearDocument(Document document) { NodeList nodeList = document.getChildNodes(); if (nodeList == null) { return; } int len = nodeList.getLength(); for (int i = 0; i < len; i++) { document.removeChild(nodeList.item(i)); } } /** * Create empty document TO BE DEBUGGED!. */ public static Document createDocument() { DocumentBuilder documentBuilder = null; // System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); try { documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException pce) { warn("ParserConfigurationException: " + pce); return null; } return documentBuilder.newDocument(); } /** * Copies all attributes from one element to another in the official way. */ public static void copyAttributes(Element elementFrom, Element elementTo) { NamedNodeMap nodeList = elementFrom.getAttributes(); if (nodeList == null) { // No attributes to copy: just return return; } Attr attrFrom = null; Attr attrTo = null; // Needed as factory to create attrs Document documentTo = elementTo.getOwnerDocument(); int len = nodeList.getLength(); // Copy each attr by making/setting a new one and // adding to the target element. for (int i = 0; i < len; i++) { attrFrom = (Attr) nodeList.item(i); // Create an set value attrTo = documentTo.createAttribute(attrFrom.getName()); attrTo.setValue(attrFrom.getValue()); // Set in target element elementTo.setAttributeNode(attrTo); } } public static Element getFirstElementByTagName(Document document, String tag) { // Get all elements matching the tagname NodeList nodeList = document.getElementsByTagName(tag); if (nodeList == null) { p("no list of elements with tag=" + tag); return null; } // Get the first if any. Element element = (Element) nodeList.item(0); if (element == null) { p("no element for tag=" + tag); return null; } return element; } public static Element getElementById(Document document, String id) { return getElementById(document.getDocumentElement(), id); } public static Element getElementById(Element element, String id) { return getElementById(element.getChildNodes(), id); } /** * Get Element that has attribute id="xyz". */ public static Element getElementById(NodeList nodeList, String id) { // Note we should really use the Query here !! Element element = null; int len = nodeList.getLength(); for (int i = 0; i < len; i++) { Node node = (Node) nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { element = (Element) node; if (((Element) node).getAttribute("id").equals(id)) { // found it ! break; } } } // returns found element or null return element; } public static Document parse(InputStream anInputStream) { Document document; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(anInputStream); } catch (Exception e) { throw new RuntimeException(e); } return document; } /** * Prints an XML DOM. */ public static void printAsXML(Document document, PrintWriter printWriter) { new TreeWalker(new XMLPrintVisitor(printWriter)).traverse(document); } /** * Prints an XML DOM. */ public static String dom2String(Document document) { StringWriter sw = new StringWriter(); DOMUtil.printAsXML(document, new PrintWriter(sw)); return sw.toString(); } /** * Replaces an element in document. */ public static void replaceElement(Element newElement, Element oldElement) { // Must be 1 Node parent = oldElement.getParentNode(); if (parent == null) { warn("replaceElement: no parent of oldElement found"); return; } // Create a copy owned by the document ElementCopyVisitor ecv = new ElementCopyVisitor(oldElement.getOwnerDocument(), newElement); Element newElementCopy = ecv.getCopy(); // Replace the old element with the new copy parent.replaceChild(newElementCopy, oldElement); } /** * Write Document structure to XML file. */ static public void document2File(Document document, String fileName) { new TreeWalker(new XMLPrintVisitor(fileName)).traverse(document); } public static void warn(String s) { p("DOMUtil: WARNING " + s); } public static void p(String s) { // System.out.println("DOMUtil: "+s); } } /* * $Log: DOMUtil.java,v $ * Revision 1.18 2004/09/10 14:20:50 just * expandIncludes() tab to 2 spaces * * Revision 1.17 2004/09/10 12:48:11 just * ok * * Revision 1.16 2003/01/06 00:23:49 just * moved devenv to linux * * Revision 1.15 2002/11/14 20:25:20 just * reformat of code only * * Revision 1.14 2002/06/18 10:30:02 just * no rel change * * Revision 1.13 2001/08/01 15:20:23 kstroke * fix for expand includes (added rootDir) * * Revision 1.12 2001/02/17 14:28:16 just * added comments and changed interface for expandIds() * * Revision 1.11 2000/12/09 14:35:35 just * added parse() method with optional DTD validation * * Revision 1.10 2000/09/21 22:37:20 just * removed print statements * * Revision 1.9 2000/08/28 00:07:46 just * changes for introduction of EntityResolverImpl * * Revision 1.8 2000/08/24 10:11:12 just * added XML file verfication * * Revision 1.7 2000/08/10 19:26:58 just * changes for comments only * * */
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.xml; /** * This interface specifies the callbacks from the TreeWalker. * $Id: Visitor.java,v 1.4 2003/01/06 00:23:49 just Exp $ * * @author $Author: just $ - Just van den Broecke - Just Objects B.V. &copy; */ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; /** * Callback methods from the TreeWalker. */ public interface Visitor { public void visitDocumentPre(Document document); public void visitDocumentPost(Document document); public void visitElementPre(Element element); public void visitElementPost(Element element); public void visitText(Text element); } /* * $Log: Visitor.java,v $ * Revision 1.4 2003/01/06 00:23:49 just * moved devenv to linux * * Revision 1.3 2002/11/14 20:25:20 just * reformat of code only * * Revision 1.2 2000/08/10 19:26:58 just * changes for comments only * * */
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.xml; /** * This class does a pre-order walk of a DOM tree or Node, calling an ElementVisitor * interface as it goes. * <p>The numbered nodes in the trees below indicate the order of traversal given * the specified <code>startNode</code> of &quot;1&quot;. * <pre> * * 1 x x * / \ / \ / \ * 2 6 1 x x x * /|\ \ /|\ \ /|\ \ * 3 4 5 7 2 3 4 x x 1 x x * * </pre> * $Id: TreeWalker.java,v 1.5 2003/01/06 00:23:49 just Exp $ * * @author $Author: just $ - Just van den Broecke - Just Objects B.V. &copy; */ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; public class TreeWalker { private Visitor visitor; private Node topNode; /** * Constructor. * * @param */ public TreeWalker(Visitor theVisitor) { visitor = theVisitor; } /** * Disabled default constructor. */ private TreeWalker() { } /** * Perform a pre-order traversal non-recursive style. */ public void traverse(Node node) { // Remember the top node if (topNode == null) { topNode = node; } while (node != null) { visitPre(node); Node nextNode = node.getFirstChild(); while (nextNode == null) { visitPost(node); // We are ready after post-visiting the topnode if (node == topNode) { return; } try { nextNode = node.getNextSibling(); } catch (IndexOutOfBoundsException e) { nextNode = null; } if (nextNode == null) { node = node.getParentNode(); if (node == null) { nextNode = node; break; } } } node = nextNode; } } protected void visitPre(Node node) { switch (node.getNodeType()) { case Node.DOCUMENT_NODE: visitor.visitDocumentPre((Document) node); break; case Node.ELEMENT_NODE: visitor.visitElementPre((Element) node); break; case Node.TEXT_NODE: visitor.visitText((Text) node); break; // Not yet case Node.ENTITY_REFERENCE_NODE: System.out.println("ENTITY_REFERENCE_NODE"); default: break; } } protected void visitPost(Node node) { switch (node.getNodeType()) { case Node.DOCUMENT_NODE: visitor.visitDocumentPost((Document) node); break; case Node.ELEMENT_NODE: visitor.visitElementPost((Element) node); break; case Node.TEXT_NODE: break; default: break; } } } /* * $Log: TreeWalker.java,v $ * Revision 1.5 2003/01/06 00:23:49 just * moved devenv to linux * * Revision 1.4 2002/11/14 20:25:20 just * reformat of code only * * Revision 1.3 2000/08/10 19:26:58 just * changes for comments only * * */
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.xml; import org.w3c.dom.*; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; /** * XMLPrintVisitor implements the Visitor interface in the visitor design pattern for the * purpose of printing in HTML-like format the various DOM-Nodes. * <p>In HTML-like printing, only the following Nodes are printed: * <DL> * <DT>Document</DT> * <DD>Only the doctype provided on this constructor is written (i.e. no XML declaration, &lt;!DOCTYPE&gt;, or internal DTD).</DD> * <DT>Element</DT> * <DD>All element names are uppercased.</DD> * <DD>Empty elements are written as <code>&lt;BR&gt;</code> instead of <code>&lt;BR/&gt;</code>.</DD> * <DT>Attr</DT> * <DD>All attribute names are lowercased.</DD> * <DT>Text</DT> * </DL> * <p/> * <p>The following sample code uses the XMLPrintVisitor on a hierarchy of nodes: * <pre> * <p/> * PrintWriter printWriter = new PrintWriter(); * Visitor htmlPrintVisitor = new XMLPrintVisitor(printWriter); * TreeWalker treeWalker = new TreeWalker(htmlPrintVisitor); * treeWalker.traverse(document); * printWriter.close(); * <p/> * </pre> * <p/> * <P>By default, this doesn't print non-specified attributes.</P> * * @author $Author: just $ - Just van den Broecke - Just Objects B.V. &copy; * @version $Id: XMLPrintVisitor.java,v 1.8 2003/01/06 00:23:49 just Exp $ * @see Visitor * @see TreeWalker */ public class XMLPrintVisitor implements Visitor { protected Writer writer = null; protected int level = 0; protected String doctype = null; /** * Constructor for customized encoding and doctype. * * @param writer The character output stream to use. * @param encoding Java character encoding in use by <VAR>writer</VAR>. * @param doctype String to be printed at the top of the document. */ public XMLPrintVisitor(Writer writer, String encoding, String doctype) { this.writer = writer; this.doctype = doctype; // this.isPrintNonSpecifiedAttributes = false; } /** * Constructor for customized encoding. * * @param writer The character output stream to use. * @param encoding Java character encoding in use by <VAR>writer</VAR>. */ public XMLPrintVisitor(Writer writer, String encoding) { this(writer, encoding, null); } /** * Constructor for default encoding. * * @param writer The character output stream to use. */ public XMLPrintVisitor(Writer writer) { this(writer, null, null); } /** * Constructor for default encoding. * * @param fileName the filepath to write to */ public XMLPrintVisitor(String fileName) { try { writer = new FileWriter(fileName); } catch (IOException ioe) { } } /** * Writes the <var>doctype</var> from the constructor (if any). * * @param document Node print as HTML. */ public void visitDocumentPre(Document document) { } /** * Flush the writer. * * @param document Node to print as HTML. */ public void visitDocumentPost(Document document) { write("\n"); flush(); } /** * Creates a formatted string representation of the start of the specified <var>element</var> Node * and its associated attributes, and directs it to the print writer. * * @param element Node to print as XML. */ public void visitElementPre(Element element) { this.level++; write("<" + element.getTagName()); NamedNodeMap attributes = element.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Attr attr = (Attr) attributes.item(i); visitAttributePre(attr); } write(">\n"); } /** * Creates a formatted string representation of the end of the specified <var>element</var> Node, * and directs it to the print writer. * * @param element Node to print as XML. */ public void visitElementPost(Element element) { String tagName = element.getTagName(); // if (element.hasChildNodes()) { write("</" + tagName + ">\n"); // } level--; } /** * Creates a formatted string representation of the specified <var>attribute</var> Node * and its associated attributes, and directs it to the print writer. * <p>Note that TXAttribute Nodes are not parsed into the document object hierarchy by the * XML4J parser; attributes exist as part of a Element Node. * * @param attr attr to print. */ public void visitAttributePre(Attr attr) { write(" " + attr.getName() + "=\"" + attr.getValue() + "\""); } /** * Creates a formatted string representation of the specified <var>text</var> Node, * and directs it to the print writer. CDATASections are respected. * * @param text Node to print with format. */ public void visitText(Text text) { if (this.level > 0) { write(text.getData()); } } private void write(String s) { try { writer.write(s); } catch (IOException e) { } } private void flush() { try { writer.flush(); } catch (IOException e) { } } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker; import android.net.Uri; /** * Various application wide constants * * @author Just van den Broecke * @version $Id:$ */ public class Constants { /** * The authority of the track data provider */ public static final String AUTHORITY = "nl.sogeti.android.gpstracker"; /** * The content:// style URL for the track data provider */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY); /** * Logging states, slightly adapted from GPSService states */ public static final int DOWN = 0; public static final int LOGGING = 1; public static final int PAUSED = 2; public static final int STOPPED = 3; public static final int UNKNOWN = 4; public static String[] LOGGING_STATES = {"down", "logging", "paused", "stopped", "unknown"}; public static final String DISABLEBLANKING = "disableblanking"; public static final String PREF_ENABLE_SOUND = "pref_enablesound"; public static final String PREF_SERVER_URL = "pref_server_url"; public static final String PREF_SERVER_USER = "pref_server_user"; public static final String PREF_SERVER_PASSWORD = "pref_server_password"; public static final String SERVICE_GPS_LOGGING = "nl.sogeti.android.gpstracker.intent.action.GPSLoggerService"; public static final String EXTERNAL_DIR = "/OpenGPSTracker/"; public static final Uri NAME_URI = Uri.parse("content://" + AUTHORITY + ".string"); /** * Activity Action: Pick a file through the file manager, or let user * specify a custom file name. * Data is the current file name or file name suggestion. * Returns a new file name as file URI in data. * <p/> * <p>Constant Value: "org.openintents.action.PICK_FILE"</p> */ public static final String ACTION_PICK_FILE = "org.openintents.action.PICK_FILE"; public static final int REQUEST_CODE_PICK_FILE_OR_DIRECTORY = 1; /** * Activity Action: Show an about dialog to display * information about the application. * <p/> * The application information is retrieved from the * application's manifest. In order to send the package * you have to launch this activity through * startActivityForResult(). * <p/> * Alternatively, you can specify the package name * manually through the extra EXTRA_PACKAGE. * <p/> * All data can be replaced using optional intent extras. * <p/> * <p> * Constant Value: "org.openintents.action.SHOW_ABOUT_DIALOG" * </p> */ public static final String OI_ACTION_SHOW_ABOUT_DIALOG = "org.openintents.action.SHOW_ABOUT_DIALOG"; /** * Definitions for tracks. * */ public static final class Tracks implements android.provider.BaseColumns { /** * The name of this table */ static final String TABLE = "tracks"; /** * The end time */ public static final String NAME = "name"; public static final String CREATION_TIME = "creationtime"; /** * The MIME type of a CONTENT_URI subdirectory of a single track. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.track"; /** * The content:// style URL for this provider */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE); } /** * Definitions for segments. */ public static final class Segments implements android.provider.BaseColumns { /** * The name of this table */ static final String TABLE = "segments"; /** * The track _id to which this segment belongs */ public static final String TRACK = "track"; static final String TRACK_TYPE = "INTEGER NOT NULL"; static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT"; /** * The MIME type of a CONTENT_URI subdirectory of a single segment. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.segment"; /** * The MIME type of CONTENT_URI providing a directory of segments. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.segment"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE); } /** * Definitions for media URI's. * */ public static final class Media implements android.provider.BaseColumns { /** * The track _id to which this segment belongs */ public static final String TRACK = "track"; public static final String SEGMENT = "segment"; public static final String WAYPOINT = "waypoint"; public static final String URI = "uri"; /** * The name of this table */ public static final String TABLE = "media"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE); } /** * Definitions for waypoints. * */ public static final class Waypoints implements android.provider.BaseColumns { /** * The name of this table */ public static final String TABLE = "waypoints"; /** * The latitude */ public static final String LATITUDE = "latitude"; /** * The longitude */ public static final String LONGITUDE = "longitude"; /** * The recorded time */ public static final String TIME = "time"; /** * The speed in meters per second */ public static final String SPEED = "speed"; /** * The segment _id to which this segment belongs */ public static final String SEGMENT = "tracksegment"; /** * The accuracy of the fix */ public static final String ACCURACY = "accuracy"; /** * The altitude */ public static final String ALTITUDE = "altitude"; /** * the bearing of the fix */ public static final String BEARING = "bearing"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE); } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.logger; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.net.Uri; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import nl.sogeti.android.gpstracker.logger.IGPSLoggerServiceRemote; import org.opentraces.metatracker.Constants; /** * Class to interact with the service that tracks and logs the locations * * @author rene (c) Jan 18, 2009, Sogeti B.V. adapted by Just van den Broecke * @version $Id: GPSLoggerServiceManager.java 455 2010-03-14 08:16:44Z rcgroot $ */ public class GPSLoggerServiceManager { private static final String TAG = "MT.GPSLoggerServiceManager"; private static final String REMOTE_EXCEPTION = "REMOTE_EXCEPTION"; private Context mCtx; private IGPSLoggerServiceRemote mGPSLoggerRemote; private final Object mStartLock = new Object(); private boolean mStarted = false; /** * Class for interacting with the main interface of the service. */ private ServiceConnection mServiceConnection = null; public GPSLoggerServiceManager(Context ctx) { this.mCtx = ctx; } public boolean isStarted() { synchronized (mStartLock) { return mStarted; } } public int getLoggingState() { synchronized (mStartLock) { int logging = Constants.UNKNOWN; try { if (this.mGPSLoggerRemote != null) { logging = this.mGPSLoggerRemote.loggingState(); Log.d(TAG, "mGPSLoggerRemote tells state to be " + logging); } else { Log.w(TAG, "Remote interface to logging service not found. Started: " + mStarted); } } catch (RemoteException e) { Log.e(TAG, "Could stat GPSLoggerService.", e); } return logging; } } public boolean isMediaPrepared() { synchronized (mStartLock) { boolean prepared = false; try { if (this.mGPSLoggerRemote != null) { prepared = this.mGPSLoggerRemote.isMediaPrepared(); } else { Log.w(TAG, "Remote interface to logging service not found. Started: " + mStarted); } } catch (RemoteException e) { Log.e(TAG, "Could stat GPSLoggerService.", e); } return prepared; } } public long startGPSLogging(String name) { synchronized (mStartLock) { if (mStarted) { try { if (this.mGPSLoggerRemote != null) { return this.mGPSLoggerRemote.startLogging(); } } catch (RemoteException e) { Log.e(TAG, "Could not start GPSLoggerService.", e); } } return -1; } } public void pauseGPSLogging() { synchronized (mStartLock) { if (mStarted) { try { if (this.mGPSLoggerRemote != null) { this.mGPSLoggerRemote.pauseLogging(); } } catch (RemoteException e) { Log.e(TAG, "Could not start GPSLoggerService.", e); } } } } public long resumeGPSLogging() { synchronized (mStartLock) { if (mStarted) { try { if (this.mGPSLoggerRemote != null) { return this.mGPSLoggerRemote.resumeLogging(); } } catch (RemoteException e) { Log.e(TAG, "Could not start GPSLoggerService.", e); } } return -1; } } public void stopGPSLogging() { synchronized (mStartLock) { if (mStarted) { try { if (this.mGPSLoggerRemote != null) { this.mGPSLoggerRemote.stopLogging(); } } catch (RemoteException e) { Log.e(GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not stop GPSLoggerService.", e); } } else { Log.e(TAG, "No GPSLoggerRemote service connected to this manager"); } } } public void storeMediaUri(Uri mediaUri) { synchronized (mStartLock) { if (mStarted) { try { if (this.mGPSLoggerRemote != null) { this.mGPSLoggerRemote.storeMediaUri(mediaUri); } } catch (RemoteException e) { Log.e(GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not send media to GPSLoggerService.", e); } } else { Log.e(TAG, "No GPSLoggerRemote service connected to this manager"); } } } /** * Means by which an Activity lifecycle aware object hints about binding and unbinding */ public void startup(final ServiceConnection observer) { Log.d(TAG, "connectToGPSLoggerService()"); if (!mStarted) { this.mServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { synchronized (mStartLock) { Log.d(TAG, "onServiceConnected()"); GPSLoggerServiceManager.this.mGPSLoggerRemote = IGPSLoggerServiceRemote.Stub.asInterface(service); mStarted = true; if (observer != null) { observer.onServiceConnected(className, service); } } } public void onServiceDisconnected(ComponentName className) { synchronized (mStartLock) { Log.e(TAG, "onServiceDisconnected()"); GPSLoggerServiceManager.this.mGPSLoggerRemote = null; mStarted = false; if (observer != null) { observer.onServiceDisconnected(className); } } } }; this.mCtx.bindService(new Intent(Constants.SERVICE_GPS_LOGGING), this.mServiceConnection, Context.BIND_AUTO_CREATE); } else { Log.w(TAG, "Attempting to connect whilst connected"); } } /** * Means by which an Activity lifecycle aware object hints about binding and unbinding */ public void shutdown() { Log.d(TAG, "disconnectFromGPSLoggerService()"); try { this.mCtx.unbindService(this.mServiceConnection); } catch (IllegalArgumentException e) { Log.e(TAG, "Failed to unbind a service, prehaps the service disapeared?", e); } } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.net; /** * Generic exception wrapper. $Id: ClientException.java,v 1.2 2005/07/22 22:25:20 just Exp $ * * @author $Author: Just van den Broecke$ * @version $Revision: $ */ public class ClientException extends Exception { private int errorId; String error; protected ClientException() { } public ClientException(String aMessage, Throwable t) { super(aMessage + "\n embedded exception=" + t.toString()); } public ClientException(String aMessage) { super(aMessage); } public ClientException(int anErrorId, String anError, String someDetails) { super(someDetails); errorId = anErrorId; error = anError; } public ClientException(Throwable t) { this("ClientException: ", t); } public String toString() { return "ClientException: " + getMessage(); } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.net; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * Constants and utilities for the KW protocol. * * @author $Author: $ * @version $Id: Protocol.java,v 1.2 2005/07/22 22:25:20 just Exp $ */ public class Protocol { /** * AMUSE Protocol version. */ public static final String PROTOCOL_VERSION = "4.0"; /** * Postfixes */ public static final String POSTFIX_REQ = "-req"; public static final String POSTFIX_RSP = "-rsp"; public static final String POSTFIX_NRSP = "-nrsp"; public static final String POSTFIX_IND = "-ind"; /** * Service id's */ public static final String SERVICE_SESSION_CREATE = "ses-create"; public static final String SERVICE_LOGIN = "ses-login"; public static final String SERVICE_LOGOUT = "ses-logout"; public static final String SERVICE_SESSION_PING = "ses-ping"; public static final String SERVICE_QUERY_STORE = "query-store"; public static final String SERVICE_MAP_AVAIL = "map-avail"; public static final String SERVICE_MULTI_REQ = "multi-req"; /** * Common Attributes * */ public static final String ATTR_DEVID = "devid"; public static final String ATTR_USER = "user"; public static final String ATTR_AGENT = "agent"; public static final String ATTR_AGENTKEY = "agentkey"; public static final String ATTR_SECTIONS = "sections"; public static final String ATTR_ID = "id"; public static final String ATTR_CMD = "cmd"; public static final String ATTR_ERROR = "error"; public static final String ATTR_ERRORID = "errorId"; // yes id must be Id !! public static final String ATTR_PASSWORD = "password"; public static final String ATTR_PROTOCOLVERSION = "protocolversion"; public static final String ATTR_STOPONERROR = "stoponerror"; public static final String ATTR_T = "t"; public static final String ATTR_TIME = "time"; public static final String ATTR_DETAILS = "details"; public static final String ATTR_NAME = "name"; /** * Error ids returned in -nrsp as attribute ATTR_ERRORID */ public final static int // 4000-4999 are "user-correctable" errors (user sends wrong input) // 5000-5999 are server failures ERR4004_ILLEGAL_COMMAND_FOR_STATE = 4003, ERR4004_INVALID_ATTR_VALUE = 4004, ERR4007_AGENT_LEASE_EXPIRED = 4007, //_Portal/Application_error_codes_(4100-4199) ERR4100_INVALID_USERNAME = 4100, ERR4101_INVALID_PASSWORD = 4101, ERR4102_MAX_LOGIN_ATTEMPTS_EXCEEDED = 4102, //_General_Server_Error_Codes ERR5000_INTERNAL_SERVER_ERROR = 5000; /** * Create login protocol request. */ public static Element createLoginRequest(String aName, String aPassword) { Element request = createRequest(SERVICE_LOGIN); request.setAttribute(ATTR_NAME, aName); request.setAttribute(ATTR_PASSWORD, aPassword); request.setAttribute(ATTR_PROTOCOLVERSION, PROTOCOL_VERSION); return request; } /** * Create create-session protocol request. */ public static Element createSessionCreateRequest() { return createRequest(SERVICE_SESSION_CREATE); } /** * Create a positive response element. */ public static Element createRequest(String aService) { Element element = null; try { DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance(); DocumentBuilder build = dFact.newDocumentBuilder(); Document doc = build.newDocument(); element = doc.createElement(aService + POSTFIX_REQ); doc.appendChild(element); } catch (Throwable t) { } return element; } /** * Return service name for a message tag. * * @param aMessageTag * @return */ public static String getServiceName(String aMessageTag) { try { return aMessageTag.substring(0, aMessageTag.lastIndexOf('-')); } catch (Throwable t) { throw new IllegalArgumentException("getServiceName: invalid tag: " + aMessageTag); } } /** * Is message a (negative) response.. * * @param message * @return */ public static boolean isResponse(Element message) { String tag = message.getTagName(); return tag.endsWith(POSTFIX_RSP) || tag.endsWith(POSTFIX_NRSP); } /** * Is message a positive response.. * * @param message * @return */ public static boolean isPositiveResponse(Element message) { return message.getTagName().endsWith(POSTFIX_RSP); } /** * Is message a negative response.. * * @param message * @return */ public static boolean isNegativeResponse(Element message) { return message.getTagName().endsWith(POSTFIX_NRSP); } public static boolean isPositiveServiceResponse(Element message, String service) { return isPositiveResponse(message) && service.equals(getServiceName(message.getTagName())); } public static boolean isNegativeServiceResponse(Element message, String service) { return isNegativeResponse(message) && service.equals(getServiceName(message.getTagName())); } public static boolean isService(Element message, String service) { return service.equals(getServiceName(message.getTagName())); } protected Protocol() { } }
Java
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.net; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.opentraces.metatracker.xml.DOMUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Basic OpenTraces client using XML over HTTP. * <p/> * Use this class within Android HTTP clients. * * @author $Author: Just van den Broecke$ * @version $Revision: 3043 $ $Id: HTTPClient.java 3043 2009-01-17 16:25:21Z just $ * @see */ public class OpenTracesClient extends Protocol { private static final String LOG_TAG = "MT.OpenTracesClient"; /** * Default KW session timeout (minutes). */ public static final int DEFAULT_TIMEOUT_MINS = 5; /** * Full KW protocol URL. */ private String protocolURL; /** * Debug flag for verbose output. */ private boolean debug; /** * Key gotten on login ack */ private String agentKey; /** * Keyworx session timeout (minutes). */ private int timeout; /** * Saved login request for session restore on timeout. */ private Element loginRequest; /** * Constructor with full protocol URL e.g. http://www.bla.com/proto.srv. */ public OpenTracesClient(String aProtocolURL) { this(aProtocolURL, DEFAULT_TIMEOUT_MINS); } /** * Constructor with protocol URL and timeout. */ public OpenTracesClient(String aProtocolURL, int aTimeout) { protocolURL = aProtocolURL; if (!protocolURL.endsWith("/proto.srv")) { protocolURL += "/proto.srv"; } timeout = aTimeout; } /** * Create session. */ synchronized public Element createSession() throws ClientException { agentKey = null; // Create XML request Element request = createRequest(SERVICE_SESSION_CREATE); // Execute request Element response = doRequest(request); handleResponse(request, response); throwOnNrsp(response); // Returns positive response return response; } public String getAgentKey() { return agentKey; } public boolean hasSession() { return agentKey != null; } public boolean isLoggedIn() { return hasSession() && loginRequest != null; } /** * Login on portal. */ synchronized public Element login(String aName, String aPassword) throws ClientException { // Create XML request Element request = createLoginRequest(aName, aPassword); // Execute request Element response = doRequest(request); // Filter session-related attrs handleResponse(request, response); throwOnNrsp(response); // Returns positive response return response; } /** * Keep alive service. */ synchronized public Element ping() throws ClientException { return service(createRequest(SERVICE_SESSION_PING)); } /** * perform TWorx service request. */ synchronized public Element service(Element request) throws ClientException { throwOnInvalidSession(); // Execute request Element response = doRequest(request); // Check for session timeout response = redoRequestOnSessionTimeout(request, response); // Throw exception on negative response throwOnNrsp(response); // Positive response: return wrapped handler response return response; } /** * perform TWorx multi-service request. */ synchronized public List<Element> service(List<Element> requests, boolean stopOnError) throws ClientException { // We don't need a valid session as one of the requests // may be a login or create-session request. // Create multi-req request with individual requests as children Element request = createRequest(SERVICE_MULTI_REQ); request.setAttribute(ATTR_STOPONERROR, stopOnError + ""); for (Element req : requests) { request.appendChild(req); } // Execute request Element response = doRequest(request); // Check for session timeout response = redoRequestOnSessionTimeout(request, response); // Throw exception on negative response throwOnNrsp(response); // Filter child responses for session-based responses NodeList responseList = response.getChildNodes(); List<Element> responses = new ArrayList(responseList.getLength()); for (int i = 0; i < responseList.getLength(); i++) { handleResponse(requests.get(i), (Element) responseList.item(i)); responses.add((Element) responseList.item(i)); } // Positive multi-req response: return child responses return responses; } /** * Logout from portal. */ synchronized public Element logout() throws ClientException { throwOnInvalidSession(); // Create XML request Element request = createRequest(SERVICE_LOGOUT); // Execute request Element response = doRequest(request); handleResponse(request, response); // Throw exception or return positive response // throwOnNrsp(response); return response; } /* http://brainflush.wordpress.com/2008/10/17/talking-to-web-servers-via-http-in-android-10/ */ public void uploadFile(String fileName) { try { DefaultHttpClient httpclient = new DefaultHttpClient(); File f = new File(fileName); HttpPost httpost = new HttpPost("http://local.geotracing.com/tland/media.srv"); MultipartEntity entity = new MultipartEntity(); entity.addPart("myIdentifier", new StringBody("somevalue")); entity.addPart("myFile", new FileBody(f)); httpost.setEntity(entity); HttpResponse response; response = httpclient.execute(httpost); Log.d(LOG_TAG, "Upload result: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } httpclient.getConnectionManager().shutdown(); } catch (Throwable ex) { Log.d(LOG_TAG, "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace()); } } public void setDebug(boolean b) { debug = b; } /** * Filter responses for session-related requests. */ private void handleResponse(Element request, Element response) throws ClientException { if (isNegativeResponse(response)) { return; } String service = Protocol.getServiceName(request.getTagName()); if (service.equals(SERVICE_LOGIN)) { // Save for later session restore loginRequest = request; // Save session key agentKey = response.getAttribute(ATTR_AGENTKEY); // if (response.hasAttribute(ATTR_TIME)) { // DateTimeUtils.setTime(response.getLongAttr(ATTR_TIME)); // } } else if (service.equals(SERVICE_SESSION_CREATE)) { // Save session key agentKey = response.getAttribute(ATTR_AGENTKEY); } else if (service.equals(SERVICE_LOGOUT)) { loginRequest = null; agentKey = null; } } /** * Throw exception on negative protocol response. */ private void throwOnNrsp(Element anElement) throws ClientException { if (isNegativeResponse(anElement)) { String details = "no details"; if (anElement.hasAttribute(ATTR_DETAILS)) { details = anElement.getAttribute(ATTR_DETAILS); } throw new ClientException(Integer.parseInt(anElement.getAttribute(ATTR_ERRORID)), anElement.getAttribute(ATTR_ERROR), details); } } /** * Throw exception when not logged in. */ private void throwOnInvalidSession() throws ClientException { if (agentKey == null) { throw new ClientException("Invalid tworx session"); } } /** * . */ private Element redoRequestOnSessionTimeout(Element request, Element response) throws ClientException { // Check for session timeout if (isNegativeResponse(response) && Integer.parseInt(response.getAttribute(ATTR_ERRORID)) == Protocol.ERR4007_AGENT_LEASE_EXPIRED) { p("Reestablishing session..."); // Reset session agentKey = null; // Do login if already logged in if (loginRequest != null) { response = doRequest(loginRequest); throwOnNrsp(response); } else { response = createSession(); throwOnNrsp(response); } // Save session key agentKey = response.getAttribute(ATTR_AGENTKEY); // Re-issue service request and return new response return doRequest(request); } // No session timeout so same response return response; } /** * Do XML over HTTP request and retun response. */ private Element doRequest(Element anElement) throws ClientException { // Create URL to use String url = protocolURL; if (agentKey != null) { url = url + "?agentkey=" + agentKey; } else { // Must be login url = url + "?timeout=" + timeout; } p("doRequest: " + url + " req=" + anElement.getTagName()); // Perform request/response HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); Element replyElement = null; try { // Make sure the server knows what kind of a response we will accept httpPost.addHeader("Accept", "text/xml"); // Also be sure to tell the server what kind of content we are sending httpPost.addHeader("Content-Type", "application/xml"); String xmlString = DOMUtil.dom2String(anElement.getOwnerDocument()); StringEntity entity = new StringEntity(xmlString, "UTF-8"); entity.setContentType("application/xml"); httpPost.setEntity(entity); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httpPost); // Parse response Document replyDoc = DOMUtil.parse(response.getEntity().getContent()); replyElement = replyDoc.getDocumentElement(); p("doRequest: rsp=" + replyElement.getTagName()); } catch (Throwable t) { throw new ClientException("Error in doRequest: " + t); } finally { } return replyElement; } /** * Util: print. */ private void p(String s) { if (debug) { Log.d(LOG_TAG, s); } } /** * Util: warn. */ private void warn(String s) { warn(s, null); } /** * Util: warn with exception. */ private void warn(String s, Throwable t) { Log.e(LOG_TAG, s + " ex=" + t, t); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend.elements; /** * * @author Saketh Kasibatla */ import java.awt.BorderLayout; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; /** * * @author Saketh Kasibatla */ public class MultiLineInputElement extends ScoutingElement{ private JLabel label; private JScrollPane scrolling; private JTextArea input; String name; protected boolean inComments; public MultiLineInputElement(String name) { super(); this.inComments=false; if(!(name.endsWith(":"))){ label=new JLabel(name+":"); this.name=name+":"; } else{ label=new JLabel(name); this.name=name; } this.input = new JTextArea(); this.scrolling = new JScrollPane(this.input); this.setLayout(new BorderLayout()); this.label.setAlignmentX(Component.LEFT_ALIGNMENT); this.input.setAlignmentX(Component.LEFT_ALIGNMENT); this.add(label,BorderLayout.WEST); this.add(scrolling,BorderLayout.CENTER); } public String getText(){ return this.label.getText(); } public String getInput(){ return this.input.getText()+"\n"; } public boolean isInComments() { return inComments; } public void setInComments(boolean inComments) { this.inComments = inComments; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final MultiLineInputElement other = (MultiLineInputElement) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } @Override public void clear() { this.input.setText(""); } }
Java
package com.team1160.scouting.frontend.elements; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import javax.swing.JMenuItem; /** * This class is used with a card layout to go to the next card in the layout. * @author Saketh Kasibatla */ public class NextMenuItem extends JMenuItem implements ActionListener{ /** * Contains the card layout and its parent. */ CardLayoutPacket layout; /** * creates a NextButton with text name. * @param layout a CardLayoutPacket whose cards the button will flip thru. * @param name the text displayed on the button. */ public NextMenuItem(CardLayoutPacket layout, String name) { super(name); this.layout = layout; this.addActionListener(this); } /** * creates a generic NextButton with the name "next" * @param layout a CardLayoutPacket whose cards the button will flip thru. */ public NextMenuItem(CardLayoutPacket layout) { super("next"); this.layout = layout; this.addActionListener(this); } /** * when the button is clicked, will go to the next card. * @param e the actionevent */ public void actionPerformed(ActionEvent e) { this.layout.getLayout().next(this.layout.getParent()); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend.elements; import javax.swing.JLabel; import javax.swing.JSlider; /** * * @author Saketh Kasibatla */ public class WeightingSliderElement extends ScoutingElement{ /** * label with slider's name */ private JLabel label; /** * actual slider */ private JSlider slider; /** * the name that is displayed in the jlabel */ private String name; private int hashCode; public WeightingSliderElement(String name, int hashCode) { super(); if(!(name.endsWith(":"))){ label=new JLabel(name+":"); this.name=name+":"; } else{ label=new JLabel(name); this.name=name; } this.slider=new JSlider(); this.slider.setMaximum(100); this.slider.setMinimum(0); this.slider.setMajorTickSpacing(10); this.slider.setMinorTickSpacing(2); this.slider.setPaintTicks(true); this.slider.setSnapToTicks(true); this.slider.setPaintLabels(true); this.add(label); this.add(slider); this.hashCode = hashCode; } @Override public String getInput() { int value=this.slider.getValue(); return Integer.toString(value); } @Override public String getText() { return this.label.getText(); } @Override public void clear() { this.slider.setValue(50); } public void setValue(int n) { slider.setValue(n); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final WeightingSliderElement other = (WeightingSliderElement) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } return true; } @Override public int hashCode() { return this.hashCode; } }
Java
package com.team1160.scouting.frontend.elements; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JTextField; /** * A scouting element meant to take its input in a single line. * @author Saketh Kasibatla */ public class SingleLineInputElement extends ScoutingElement{ /** * the label that displays the name of the scouting element */ private JLabel label; /** * the input text field */ private JTextField input; /** * the type of the the input. Can be INTEGER, STRING, or DOUBLE */ private int type; /** * the name that is displayed in the jlabel */ private String name; public static final int INTEGER = 1, STRING = 2, DOUBLE = 3; protected boolean inComments; protected boolean isNegative; protected boolean isTime; protected int maxTime; /** * creates a new SingleLineInputElement with the specified name and type. * if there is no : at the end of the name, one is added. * @param name the name displayed in the label. * @param type the type of input this element recieves. */ public SingleLineInputElement(String name,int type, boolean isNegative, boolean isTime, int maxTime) { super(); this.isNegative = isNegative; this.isTime =isTime; this.maxTime = maxTime; this.inComments=false; if(!(name.endsWith(":"))){ label=new JLabel(name+":"); this.name=name+":"; } else{ label=new JLabel(name); this.name=name; } this.input=new JTextField(); this.input.setColumns(10); // this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); // this.setBackground(Color.red); this.label.setAlignmentX(Component.LEFT_ALIGNMENT); this.input.setAlignmentX(Component.LEFT_ALIGNMENT); this.add(label); this.add(input); } public SingleLineInputElement(String name, int type, boolean isNegative){ this(name,type,isNegative, false, 0); } public SingleLineInputElement (String name, int type){ this(name, type, false, false, 0); } /** * * @return the text of the label */ public String getText(){ return this.label.getText().substring(0,this.label.getText().length()); } /** * * @return the input in the input field */ public String getInput(){ String text = this.input.getText(); if(this.isNegative){ if(text.startsWith("-")){ return text; } else{ return "-"+text; } }else if(this.isTime){ int value = Math.abs(Integer.parseInt(text)); return Integer.toString(this.maxTime-value); }else { return text; } } /** * * @return the type of input that this element takes */ public int getType() { return type; } public boolean isNegative(){ return this.isNegative; } public boolean isTime(){ return this.isTime; } public int getMaxTime(){ return this.maxTime; } public void setInComments(boolean b){ this.inComments=b; } public boolean isInComments(){ return this.inComments; } /** * tests if this element is equal to another object. * @param obj the object to test equality with * @return wether or not this equals obj */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SingleLineInputElement other = (SingleLineInputElement) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } return true; } /** * hash code method. used for identification purposes. * @return the hash code */ @Override public int hashCode() { int hash = 3; hash = 59 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } /** * resets this element. */ @Override public void clear() { this.input.setText(""); } }
Java
package com.team1160.scouting.frontend.elements; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; /** * This class is used with a card layout to go to the next card in the layout. * @author Saketh Kasibatla */ public class NextButton extends JButton implements ActionListener{ /** * Contains the card layout and its parent. */ CardLayoutPacket layout; /** * creates a NextButton with text name. * @param layout a CardLayoutPacket whose cards the button will flip thru. * @param name the text displayed on the button. */ public NextButton(CardLayoutPacket layout, String name) { super(name); this.layout = layout; this.addActionListener(this); } /** * creates a generic NextButton with the name "next" * @param layout a CardLayoutPacket whose cards the button will flip thru. */ public NextButton(CardLayoutPacket layout) { super("next"); this.layout = layout; this.addActionListener(this); } /** * when the button is clicked, will go to the next card. * @param e the actionevent */ public void actionPerformed(ActionEvent e) { this.layout.getLayout().next(this.layout.getParent()); } }
Java
package com.team1160.scouting.frontend.elements; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; /** * A button like NextButton or PrevButton , but to go to a specific slide. * @author Saketh Kasibatla */ public class JumpButton extends JButton implements ActionListener{ /** * Contains the card layout and its parent. */ CardLayoutPacket layout; /** * the name of the slide that the JumpButton goes to. */ String slideName; /** * creates a JumpButton with text name. * @param layout a CardLayoutPacket whose cards the button will flip thru. * @param text the text displayed on the button. * @param slideName the name of the slide that the button will jump to */ public JumpButton(CardLayoutPacket layout,String text, String slideName) { super(text); this.layout = layout; this.slideName = slideName; this.addActionListener(this); } /** * when the button is clicked, will go to the indicated card. * @param e the actionevent */ public void actionPerformed(ActionEvent e) { this.layout.getLayout().show(this.layout.getParent(),slideName); } }
Java
package com.team1160.scouting.frontend.elements; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; /** * This class is used with a card layout to go to the previous card in the layout. * @author Saketh Kasibatla */ public class PrevButton extends JButton implements ActionListener{ /** * Contains the card layout and its parent. */ CardLayoutPacket layout; /** * creates a PrevButton with text name. * @param layout a CardLayoutPacket whose cards the button will flip thru. * @param name the text displayed on the button. */ public PrevButton(CardLayoutPacket layout, String name) { super(name); this.layout = layout; this.addActionListener(this); } /** * creates a generic PrevButton with the name "prev" * @param layout a CardLayoutPacket whose cards the button will flip thru. */ public PrevButton(CardLayoutPacket layout) { super("prev"); this.layout = layout; this.addActionListener(this); } /** * when the button is clicked, will go to the previous card. * @param e the actionevent */ public void actionPerformed(ActionEvent e) { //cardlayout.previous(parent); this.layout.getLayout().previous(this.layout.getParent()); } }
Java
package com.team1160.scouting.frontend.elements; import java.util.Vector; import javax.swing.JComboBox; import javax.swing.JLabel; /** * A scouting element with a dropdown box which contains numbers for the user to choose from. * @author Saketh Kasibatla */ public class NumberDropDownElement extends ScoutingElement{ /** * the label that displays the name of the scouting element */ private JLabel label; /** * the input dropdown box. */ private JComboBox dropDown; /** * the lowest and highest numbers in the dropdown box. */ private int bottom,top; /** * the name that is displayed in the jlabel */ private String name; /** * Creates a new NumberDropDownElement. * @param name the name of the new element * @param bottom the lowest number in the dropdown box * @param top the highest element in the dropdown box. */ public NumberDropDownElement(String name, int bottom, int top) { super(); if(!(name.endsWith(":"))){ label=new JLabel(name+":"); this.name=name+":"; } else{ label=new JLabel(name); this.name=name; } this.bottom=bottom; this.top=top; Vector<Integer> items = new Vector<Integer>(); for(int i=bottom;i<=top;i++){ items.add(i); } this.dropDown=new JComboBox(items); this.add(this.label); this.add(this.dropDown); } /** * * @return the text of the label */ public String getText(){ return this.label.getText().substring(0,this.label.getText().length()); } /** * * @return the input in the input field */ public String getInput(){ return this.dropDown.getSelectedItem().toString(); } /** * tests if this element is equal to another object. * @param obj the object to test equality with * @return wether or not this equals obj */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final NumberDropDownElement other = (NumberDropDownElement) obj; if (this.bottom != other.bottom) { return false; } if (this.top != other.top) { return false; } if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } return true; } /** * hash code method. used for identification purposes. * @return the hash code */ @Override public int hashCode() { int hash = 3; hash = 97 * hash + this.bottom; hash = 97 * hash + this.top; hash = 97 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } /** * resets this element. */ @Override public void clear() { this.dropDown.setSelectedItem(new Integer(1)); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend.elements; import java.awt.Component; import java.awt.Dimension; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.table.TableCellRenderer; public class MultiLineTableCellRenderer extends JTextArea implements TableCellRenderer{ public MultiLineTableCellRenderer() { setLineWrap(true); setWrapStyleWord(true); setOpaque(true); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { setForeground(table.getSelectionForeground()); setBackground(table.getSelectionBackground()); } else { setForeground(table.getForeground()); setBackground(table.getBackground()); } setFont(table.getFont()); if (hasFocus) { setBorder(UIManager.getBorder("Table.focusCellHighlightBorder")); if (table.isCellEditable(row, column)) { setForeground(UIManager.getColor("Table.focusCellForeground")); setBackground(UIManager.getColor("Table.focusCellBackground")); } } else { setBorder(new EmptyBorder(1, 2, 1, 2)); } setText((value == null) ? "" : value.toString()); int count=((String) value).split("\n").length; this.setPreferredSize(new Dimension(267,16*count)); int height_wanted = (int)getPreferredSize().getHeight(); if (height_wanted != table.getRowHeight(row)) table.setRowHeight(row, height_wanted); return this; } }
Java
package com.team1160.scouting.frontend.elements; import java.awt.Component; import java.awt.FlowLayout; import javax.swing.JPanel; /** * abstract superclass for all xml-generated elements in the app. * @author Saketh Kasibatla */ public abstract class ScoutingElement extends JPanel{ /** * whether or not the element is weighted */ public boolean isWeighted; /** * default superconstructor for all scouting elements */ public ScoutingElement(){ this.setAlignmentX(Component.LEFT_ALIGNMENT); } /** * gets the input value of the element * @return the string value of the input */ public abstract String getInput(); /** * gets the name of the element * @return the string name of the element */ public abstract String getText(); /** * resets the element to its default state */ public abstract void clear(); }
Java
package com.team1160.scouting.frontend.elements; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import javax.swing.JMenuItem; /** * A button like NextButton or PrevButton , but to go to a specific slide. * @author Saketh Kasibatla */ public class JumpMenuItem extends JMenuItem implements ActionListener{ /** * Contains the card layout and its parent. */ CardLayoutPacket layout; /** * the name of the slide that the JumpButton goes to. */ String slideName; /** * creates a JumpButton with text name. * @param layout a CardLayoutPacket whose cards the button will flip thru. * @param text the text displayed on the button. * @param slideName the name of the slide that the button will jump to */ public JumpMenuItem(CardLayoutPacket layout,String text, String slideName) { super(text); this.layout = layout; this.slideName = slideName; this.addActionListener(this); } /** * when the button is clicked, will go to the indicated card. * @param e the actionevent */ public void actionPerformed(ActionEvent e) { this.layout.getLayout().show(this.layout.getParent(),slideName); } }
Java
package com.team1160.scouting.frontend.elements; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import javax.swing.JMenuItem; /** * This class is used with a card layout to go to the previous card in the layout. * @author Saketh Kasibatla */ public class PrevMenuItem extends JMenuItem implements ActionListener{ /** * Contains the card layout and its parent. */ CardLayoutPacket layout; /** * creates a PrevButton with text name. * @param layout a CardLayoutPacket whose cards the button will flip thru. * @param name the text displayed on the button. */ public PrevMenuItem(CardLayoutPacket layout, String name) { super(name); this.layout = layout; this.addActionListener(this); } /** * creates a generic PrevButton with the name "prev" * @param layout a CardLayoutPacket whose cards the button will flip thru. */ public PrevMenuItem(CardLayoutPacket layout) { super("prev"); this.layout = layout; this.addActionListener(this); } /** * when the button is clicked, will go to the previous card. * @param e the actionevent */ public void actionPerformed(ActionEvent e) { //cardlayout.previous(parent); this.layout.getLayout().previous(this.layout.getParent()); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; /** * * @author sakekasi */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { try { // Set cross-platform Java L&F (also called "Metal") UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException e) { // handle exception } catch (ClassNotFoundException e) { // handle exception } catch (InstantiationException e) { // handle exception } catch (IllegalAccessException e) { // handle exception } ScoutingAppWindow window = new ScoutingAppWindow(); } }
Java
package com.team1160.scouting.frontend.resourcePackets; import java.awt.CardLayout; import java.awt.Container; /** * contains a cardlayout and its container. * @author Saketh Kasibatla */ public class CardLayoutPacket { protected CardLayout layout; protected Container parent; public CardLayoutPacket(Container parent){ layout=new CardLayout(); this.parent=parent; } public CardLayout getLayout() { return layout; } public void setLayout(CardLayout layout) { this.layout = layout; } public Container getParent() { return parent; } public void setParent(Container parent) { this.parent = parent; } }
Java
package com.team1160.scouting.frontend; import com.team1160.scouting.frontend.panels.CommentPanel; import com.team1160.scouting.frontend.panels.GraphPanel; import java.awt.HeadlessException; import javax.swing.JFrame; import javax.swing.JPanel; import com.team1160.scouting.frontend.panels.InitialPanel; import com.team1160.scouting.frontend.panels.MatchScoutingPanel; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import com.team1160.scouting.h2.CommentTable; import com.team1160.scouting.h2.DictTable; import com.team1160.scouting.h2.MatchScoutingTable; import com.team1160.scouting.h2.WeightingTable; import java.io.File; /** * The actual JFrame that contains the application * @author Saketh Kasibatla */ public class ScoutingAppWindow extends JFrame{ /** * the splash pane which displays the FIRST logo and 1160 logo */ private InitialPanel splash; private MatchScoutingPanel match; /** * Contains the card layout and its parent. */ private CardLayoutPacket layout; /** * the panel upon which the cardlayout will change panels. */ private JPanel cards; private GraphPanel graph; private CommentPanel comment; /** * makes a new window * @param title the title of the window * @throws HeadlessException */ private MatchScoutingTable scoutingTable; private WeightingTable weightingTable; private DictTable dictTable; private CommentTable commentTable; public ScoutingAppWindow(String title) throws Exception{ super(title); this.scoutingTable = new MatchScoutingTable( "."+File.separator+"data"+File.separator+"database"); this.weightingTable = new WeightingTable( "."+File.separator+"data"+File.separator+"database"); this.dictTable = new DictTable( "."+File.separator+"data"+File.separator+"database"); this.commentTable = new CommentTable( "."+File.separator+"data"+File.separator+"database"); this.cards=new JPanel(); layout = new CardLayoutPacket(cards); cards.setLayout(this.layout.getLayout()); splash = new InitialPanel(layout); splash.setOpaque(true); match = new MatchScoutingPanel(layout, this.scoutingTable, this.weightingTable, this.dictTable, this.commentTable); graph = new GraphPanel(layout, this.scoutingTable, this.weightingTable, this.dictTable); comment = new CommentPanel(layout, this.commentTable); cards.add(splash,"splashscreen"); cards.add(match, "match"); cards.add(graph, "graph"); cards.add(comment, "comment"); this.add(cards); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(820,710); this.setVisible(true); } /** * creates a new window with the default title of 1160 Scouting App * @throws HeadlessException */ public ScoutingAppWindow() throws Exception{ this("1160 Scouting App"); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend.panels; import com.team1160.scouting.frontend.elements.JumpMenuItem; import com.team1160.scouting.frontend.elements.MultiLineTableCellRenderer; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import com.team1160.scouting.h2.CommentTable; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JToolBar; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellRenderer; /** * * @author sakekasi */ public class CommentPanel extends JPanel{ JMenuBar menubar; JToolBar toolbar; JMenu go; private final JButton refresh; private final JButton deleteData; CommentTable commentTable; JTable table; JScrollPane scroll; CardLayoutPacket layout; public CommentPanel(CardLayoutPacket layout, CommentTable commentTable) throws SQLException { this.commentTable = commentTable; this.layout = layout; this.menubar = new JMenuBar(); this.go = new JMenu("Go"); this.go.setMnemonic(KeyEvent.VK_G); this.go.add(new JumpMenuItem(layout,"Match Scouting","match")); this.go.add(new JumpMenuItem(layout,"Graph","graph")); this.toolbar = new JToolBar(); this.toolbar.setFloatable(false); this.deleteData = new JButton("Delete Data"); this.deleteData.setMnemonic(KeyEvent.VK_D); this.deleteData.addActionListener(this.new DeleteData()); this.deleteData.setSize(100, this.menubar.getHeight()); this.toolbar.add(this.deleteData); this.refresh = new JButton("Refresh"); this.refresh.setMnemonic(KeyEvent.VK_R); this.refresh.addActionListener(this.new Refresh()); this.refresh.setSize(100, this.menubar.getHeight()); this.toolbar.add(this.refresh); this.table = new JTable(new CommentTableModel(this.getData())); //this.table.setDefaultRenderer(Object.class, new MultiLineTableCellRenderer()); table.getColumnModel().getColumn(2).setCellRenderer(new MultiLineTableCellRenderer()); this.scroll = new JScrollPane(this.table); this.setLayout(new BorderLayout()); JPanel top = new JPanel(new BorderLayout()); top.add(this.menubar, BorderLayout.NORTH); top.add(this.toolbar, BorderLayout.SOUTH); this.add(top, BorderLayout.NORTH); this.add(this.scroll, BorderLayout.CENTER); } public void refresh() throws SQLException{ this.remove(this.scroll); this.table=null; this.scroll = null; this.table = new JTable(new CommentTableModel(this.getData())); table.getColumnModel().getColumn(2).setCellRenderer(new MultiLineTableCellRenderer()); //this.table.setDefaultRenderer(Object.class, new MultiLineTableCellRenderer()); this.scroll = new JScrollPane(this.table); this.add(this.scroll, BorderLayout.CENTER); this.validate(); } protected ArrayList<ArrayList<String>> getData() throws SQLException{ List<Integer> teams = this.commentTable.getTeams(); ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>(); for(Integer t:teams){ Map<Integer, String> comments = this.commentTable.getComments(t); for(Integer m:comments.keySet()){ ArrayList<String> row = new ArrayList<String>(); row.add(t.toString()); row.add(m.toString()); row.add(comments.get(m)); data.add(row); } } return data; } class Refresh implements ActionListener{ public void actionPerformed(ActionEvent e) { try { CommentPanel.this.refresh(); } catch (SQLException ex) { Logger.getLogger(GraphPanel.class.getName()).log(Level.SEVERE, null, ex); } } } class DeleteData implements ActionListener{ public void actionPerformed(ActionEvent e) { Object[] options = {"Continue", "Gancel"}; boolean contin = JOptionPane.showOptionDialog( CommentPanel.this, "Pressing \'Continue\' will permanently delete your data.", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[1])==0; if(contin){ try { CommentPanel.this.commentTable.reset(); } catch (SQLException ex) { Logger.getLogger(GraphPanel.class.getName()).log(Level.SEVERE, null, ex); } } } } class CommentTableModel extends AbstractTableModel{ String columnNames[]={"Team #","Match #","Comment"}; ArrayList<ArrayList<String>> data; public CommentTableModel(ArrayList<ArrayList<String>> data) { this.data = data; } public int getRowCount() { return this.data.size(); } public int getColumnCount() { return this.columnNames.length; } public Object getValueAt(int rowIndex, int columnIndex) { return this.data.get(rowIndex).get(columnIndex); } @Override public boolean isCellEditable(int row, int col){ return false; } @Override public String getColumnName (int col) { return this.columnNames[col]; } } }
Java
package com.team1160.scouting.frontend.panels; import com.team1160.scouting.frontend.elements.JumpMenuItem; import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JToolBar; import com.team1160.scouting.frontend.elements.NextButton; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import java.awt.event.KeyEvent; import javax.swing.JMenu; import javax.swing.JMenuBar; /** * the splash panel of the app. * only has an image and a next button.<br><br><br> * * * * @author Saketh Kasibatla */ public class InitialPanel extends JPanel{ /** * the toolbar displayed at the top. */ JMenuBar toolbar; /** * the panel containing the pictures under the toolbar */ JPanel picturepanel; /** * the layout packet containing the cardlayout for the next button. */ CardLayoutPacket layout; JMenu go; /** * creates a new splash panel. * @param layout the layout packet to add to the button. */ public InitialPanel(CardLayoutPacket layout) { this.layout = layout; this.setLayout(new BorderLayout()); toolbar = new JMenuBar(); toolbar.setLayout(new BorderLayout()); this.go = new JMenu("Go"); this.go.setMnemonic(KeyEvent.VK_G); this.go.add(new JumpMenuItem(layout,"Match Scouting","match")); this.go.add(new JumpMenuItem(layout,"Graph","graph")); this.go.add(new JumpMenuItem(layout,"Comments","comment")); // this.go.add(new JumpMenuItem(layout,"Pit Scouting","pit")); toolbar.add(this.go,BorderLayout.WEST); this.add(toolbar,BorderLayout.NORTH); picturepanel=new JPanel(); ImageIcon image = new ImageIcon("image.png"); picturepanel.add(new JLabel(image/*"1160 Scouting App"*/)); picturepanel.setOpaque(true); this.add(picturepanel,BorderLayout.CENTER); this.setPreferredSize(new Dimension(800,600)); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend.panels; import com.team1160.scouting.frontend.elements.JumpMenuItem; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import com.team1160.scouting.h2.DictTable; import com.team1160.scouting.h2.MatchScoutingTable; import com.team1160.scouting.h2.WeightingTable; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.sql.SQLException; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JToolBar; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.GroupedStackedBarRenderer; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; /** * * @author saketh */ public class GraphPanel extends JPanel{ CardLayoutPacket layout; JMenuBar menubar; JToolBar toolbar; JMenu go; private final JButton refresh; private final JButton deleteData; MatchScoutingTable matchTable; WeightingTable weightingTable; DictTable dictTable; JFreeChart chart; ChartPanel chartPanel; JScrollPane scroll; private final GroupedStackedBarRenderer renderer; final int preferredHeight = 600; Dimension preferredSize; public GraphPanel(CardLayoutPacket layout, MatchScoutingTable match, WeightingTable weight, DictTable dict) throws SQLException{ this.matchTable = match; this.weightingTable = weight; this.dictTable = dict; this.menubar = new JMenuBar(); this.go = new JMenu("Go"); this.go.setMnemonic(KeyEvent.VK_G); this.go.add(new JumpMenuItem(layout,"Match Scouting","match")); //this.go.add(new JumpMenuItem(layout,"Pit Scouting","pit")); this.go.add(new JumpMenuItem(layout,"Comments","comment")); this.toolbar = new JToolBar(); this.toolbar.setFloatable(false); this.deleteData = new JButton("Delete Data"); this.deleteData.setMnemonic(KeyEvent.VK_D); this.deleteData.addActionListener(this.new DeleteData()); this.deleteData.setSize(100, this.menubar.getHeight()); this.toolbar.add(this.deleteData); this.refresh = new JButton("Refresh"); this.refresh.setMnemonic(KeyEvent.VK_R); this.refresh.addActionListener(this.new Refresh()); this.refresh.setSize(100, this.menubar.getHeight()); this.toolbar.add(this.refresh); JPanel top = new JPanel(); top.setLayout(new BorderLayout()); top.add(this.menubar); this.menubar.add(this.go, BorderLayout.NORTH); top.add(this.toolbar, BorderLayout.SOUTH); this.chart = ChartFactory.createStackedBarChart( "Team Rankings", "Team Number", "Score", this.createDataSet(), PlotOrientation.VERTICAL, true, true, false); this.renderer = new GroupedStackedBarRenderer(); this.chartPanel = new ChartPanel(this.chart); this.scroll = new JScrollPane(this.chartPanel); this.chartPanel.setPreferredSize(preferredSize); this.setLayout(new BorderLayout()); this.add(top, BorderLayout.NORTH); this.add(this.scroll, BorderLayout.CENTER); } protected CategoryDataset createDataSet() throws SQLException { DefaultCategoryDataset data = new DefaultCategoryDataset(); Map<String,Integer> dict; Map<Integer, String> reverseDict; List<Integer> teams; Map<Integer, Integer> weights; teams = this.matchTable.getTeams(); dict = this.dictTable.getValuesName(); reverseDict = this.dictTable.getValuesID(); weights = this.weightingTable.getValues(); if(weights.keySet().isEmpty()){ weights = new LinkedHashMap<Integer, Integer>(); for(Integer i:reverseDict.keySet()){ weights.put(i,50); } } Map<Integer, Double> teamToOverallScore = new HashMap<Integer, Double>(); Map<Integer, LinkedHashMap<String, Double>> teamToValues = new HashMap<Integer, LinkedHashMap<String, Double>>(); ValueComparator vc = new ValueComparator(teamToOverallScore); TreeMap<Integer, Double> teamSorted = new TreeMap(vc); for(Integer t:teams){ LinkedHashMap<String, Double> values = new LinkedHashMap<String, Double>(); for(String n:dict.keySet()){ int value = this.matchTable.getAverageValue(t, dict.get(n)); double weight = (weights.get(dict.get(n))); weight /=100; double weightedValue = value * weight; values.put(n, weightedValue); // } double overallScore = 0; for(String s:values.keySet()){ overallScore+=values.get(s); } teamToOverallScore.put(t, overallScore); teamToValues.put(t, values); } teamSorted.putAll(teamToOverallScore); for(Integer t:teamSorted.keySet()){ for(String s:teamToValues.get(t).keySet()){ // System.out.println(s); // System.out.println(t); // System.out.println(teamToValues.get(t).get(s)); data.addValue(teamToValues.get(t).get(s), s.substring(0, s.length()-1), t.toString()); } } this.preferredSize = new Dimension(this.getPreferredWidth(teams.size()), this.preferredHeight); return data; } public void refresh() throws SQLException{ this.remove(this.scroll); this.chart = null; this.chartPanel = null; this.scroll = null; this.chart = ChartFactory.createStackedBarChart( "Team Rankings", "Team Number", "Score", this.createDataSet(), PlotOrientation.VERTICAL, true, true, false); this.chartPanel = new ChartPanel(this.chart); this.chartPanel.setPreferredSize(preferredSize); this.scroll = new JScrollPane(this.chartPanel); this.add(this.scroll, BorderLayout.CENTER); this.validate(); this.scroll.validate(); } class ValueComparator implements Comparator { Map base; public ValueComparator(Map base) { this.base = base; } public int compare(Object a, Object b) { if((Double)base.get(a) < (Double)base.get(b)) { return 1; } else if((Double)base.get(a) == (Double)base.get(b)) { return 0; } else { return -1; } } } private int getPreferredWidth(int n){ if((n<=10)&&(n>0)){ return 805; }else{ return 69+74*n+12; } } class Refresh implements ActionListener{ public void actionPerformed(ActionEvent e) { try { GraphPanel.this.refresh(); } catch (SQLException ex) { Logger.getLogger(GraphPanel.class.getName()).log(Level.SEVERE, null, ex); } } } class DeleteData implements ActionListener{ public void actionPerformed(ActionEvent e) { Object[] options = {"Continue", "Gancel"}; boolean contin = JOptionPane.showOptionDialog( GraphPanel.this, "Pressing \'Continue\' will permanently delete your data.", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[1])==0; if(contin){ try { GraphPanel.this.matchTable.reset(); GraphPanel.this.weightingTable.reset(); // GraphPanel.this.dictTable.reset(); } catch (SQLException ex) { Logger.getLogger(GraphPanel.class.getName()).log(Level.SEVERE, null, ex); } } } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend.panels; import com.team1160.scouting.frontend.elements.JumpMenuItem; import com.team1160.scouting.frontend.elements.MultiLineInputElement; import com.team1160.scouting.frontend.elements.NextMenuItem; import com.team1160.scouting.frontend.elements.NumberDropDownElement; import com.team1160.scouting.frontend.elements.ScoutingElement; import com.team1160.scouting.frontend.elements.SingleLineInputElement; import com.team1160.scouting.frontend.elements.WeightingSliderElement; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import com.team1160.scouting.h2.CommentTable; import com.team1160.scouting.h2.DictTable; import com.team1160.scouting.h2.MatchScoutingTable; import com.team1160.scouting.h2.WeightingTable; import com.team1160.scouting.xml.XMLParser; import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.Border; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * * @author sakekasi */ public class MatchScoutingPanel extends JPanel{ protected JPanel bottomPanel; protected ArrayList<ScoutingElement> elements; protected JPanel elementPanel; protected JPanel elementInputPanel; protected JPanel elementButtonPanel; protected Border elementBorder; protected ArrayList<WeightingSliderElement> weightingElements; protected JPanel weightingPanel; protected JPanel weightingInputPanel; protected JPanel weightingButtonPanel; protected Border weightingBorder; protected JMenuBar menubar; protected JMenu go; protected CardLayoutPacket layout; protected MatchScoutingTable scoutingTable; protected WeightingTable weightingTable; protected DictTable dictTable; protected CommentTable commentTable; public MatchScoutingPanel(CardLayoutPacket layout, MatchScoutingTable scouting, WeightingTable weighting, DictTable dict, CommentTable comment) throws ParserConfigurationException, SAXException, IOException, Exception { this.layout = layout; this.elements = new ArrayList<ScoutingElement>(); this.weightingElements = new ArrayList<WeightingSliderElement>(); this.setLayout(new BorderLayout()); XML xml = this.new XML(); this.scoutingTable = scouting; this.weightingTable = weighting; this.dictTable = dict; this.commentTable = comment; this.menubar = new JMenuBar(); this.menubar.setLayout(new BorderLayout()); this.go = new JMenu("Go"); this.go.setMnemonic(KeyEvent.VK_G); this.go.add(new JumpMenuItem(layout,"Graph","graph")); this.go.add(new JumpMenuItem(layout,"Comments","comment")); // this.go.add(new JumpMenuItem(layout,"Pit Scouting","pit")); this.menubar.add(this.go, BorderLayout.WEST); // this.toolbar.add(this.graph, BorderLayout.EAST); this.bottomPanel = new JPanel(); this.bottomPanel.setLayout(new GridLayout(1,2,0,0)); xml.parse(); this.elementPanel = new JPanel(); this.elementInputPanel = new JPanel(); this.elementBorder = BorderFactory.createTitledBorder("Values"); this.elementInputPanel.setLayout(new GridLayout(this.elements.size(),1,0,0)); this.elementPanel.setBorder(this.elementBorder); this.elementPanel.setLayout(new BorderLayout()); this.weightingPanel = new JPanel(); this.weightingInputPanel = new JPanel(); this.weightingBorder = BorderFactory.createTitledBorder("Weighting"); this.weightingPanel.setBorder(this.weightingBorder); this.weightingInputPanel.setLayout(new GridLayout(this.weightingElements.size(),1,0,0)); this.weightingPanel.setLayout(new BorderLayout()); for(ScoutingElement se: this.elements){ this.elementInputPanel.add(se); } for(WeightingSliderElement w: this.weightingElements){ this.weightingInputPanel.add(w); } JButton elementSubmit=new JButton("submit"),elementClear = new JButton("reset"); elementSubmit.addActionListener(this.new ElementSubmit()); elementClear.addActionListener(this.new ElementClear()); JButton weightingSubmit = new JButton("submit"), weightingClear = new JButton("reset"); weightingSubmit.addActionListener(this.new WeightingSubmit()); weightingClear.addActionListener(this.new WeightingClear()); this.elementButtonPanel = new JPanel(); // this.elementButtonPanel.setBackground(Color.red); this.weightingButtonPanel = new JPanel(); // this.weightingButtonPanel.setLayout(new GridLayout(1,2)); // this.weightingButtonPanel.setBackground(Color.red); this.elementButtonPanel.add(elementSubmit); this.elementButtonPanel.add(elementClear); this.weightingButtonPanel.add(weightingSubmit); this.weightingButtonPanel.add(weightingClear); this.elementPanel.add(new JScrollPane(this.elementInputPanel), BorderLayout.CENTER); this.elementPanel.add(this.elementButtonPanel, BorderLayout.SOUTH); this.weightingPanel.add(new JScrollPane(this.weightingInputPanel), BorderLayout.CENTER); this.weightingPanel.add(this.weightingButtonPanel, BorderLayout.SOUTH); this.bottomPanel.add(this.elementPanel); this.bottomPanel.add(this.weightingPanel); this.add(this.menubar, BorderLayout.NORTH); this.add(this.bottomPanel, BorderLayout.CENTER); } class XML{ XMLParser xml; protected XML() throws ParserConfigurationException, SAXException, IOException{ xml = new XMLParser("config.xml"); } protected void parse() throws Exception{ Element e = xml.getMatch(); elements.add(new SingleLineInputElement("Team No:", SingleLineInputElement.INTEGER)); SingleLineInputElement match = new SingleLineInputElement("Match No:", SingleLineInputElement.INTEGER); match.setInComments(true); elements.add(match); NodeList element = e.getElementsByTagName("field"); MatchScoutingPanel.this.dictTable.reset(); for(int i=0;i<element.getLength();i++){ Element el = (Element) element.item(i); String type=el.getAttribute("type"); String name=el.getAttribute("name"); String inWeight = el.getAttribute("inWeight"); if(type.equalsIgnoreCase("sIntInput")){ SingleLineInputElement se; if( (el.hasAttribute("isNegative")) && el.getAttribute("isNegative").equals("true")){ se = new SingleLineInputElement(name, SingleLineInputElement.INTEGER, true); } else if( ((el.hasAttribute("isTime"))) && el.getAttribute("isTime").equals("true")){ int maxTime = Integer.parseInt(el.getAttribute("maxTime")); se = new SingleLineInputElement(name, SingleLineInputElement.INTEGER, false, true, maxTime); }else { se = new SingleLineInputElement(name, SingleLineInputElement.INTEGER); } if((!(el.hasAttribute("inWeight"))) || (el.getAttribute("inWeight")).equalsIgnoreCase("true")){ weightingElements.add(new WeightingSliderElement(name, se.hashCode())); weightingElements.get(weightingElements.size()-1).setValue( MatchScoutingPanel.this.weightingTable.getValue( weightingElements.get(weightingElements.size()-1).hashCode())); MatchScoutingPanel.this.dictTable.insert(se.hashCode(), se.getText()); } se.setAlignmentX(Component.LEFT_ALIGNMENT); elements.add(se); } else if(type.equalsIgnoreCase("numDropDown")){ NumberDropDownElement ne=new NumberDropDownElement(name, Integer.parseInt(el.getAttribute("bottom")), Integer.parseInt(el.getAttribute("top"))); if((!(el.hasAttribute("inWeight"))) || (el.getAttribute("inWeight")).equalsIgnoreCase("true")){ weightingElements.add(new WeightingSliderElement(name, ne.hashCode())); weightingElements.get(weightingElements.size()-1).setValue( MatchScoutingPanel.this.weightingTable.getValue( weightingElements.get(weightingElements.size()-1).hashCode())); MatchScoutingPanel.this.dictTable.insert(ne.hashCode(), ne.getText()); } ne.setAlignmentX(Component.LEFT_ALIGNMENT); elements.add(ne); } else { throw new Exception("wrong type"); } } MultiLineInputElement comments = new MultiLineInputElement("Comments:"); comments.setInComments(true); elements.add(comments); } } class ElementSubmit implements ActionListener{ public void actionPerformed(ActionEvent ae) { ArrayList<String> values = new ArrayList<String>(); boolean error=false; for(ScoutingElement e: MatchScoutingPanel.this.elements){ if(e.getClass()== SingleLineInputElement.class){ SingleLineInputElement slie = (SingleLineInputElement) e; if(!slie.isNegative()){ error = slie.getInput().startsWith("-"); } if(slie.isTime()){ try{ int i = Integer.parseInt(slie.getInput()); error = (i>slie.getMaxTime())||(i<=0); } catch(NumberFormatException nfe){ error = true; } } } values.add(e.getInput()); } for(String s:values){ if(!s.contains("\n")){ try{ Integer.parseInt(s); }catch(NumberFormatException nfe){ error = true; } } } if(error){ JOptionPane.showMessageDialog(MatchScoutingPanel.this, "Wrong Input", "Input Error", JOptionPane.ERROR_MESSAGE); } else { for(int i=2; i<(MatchScoutingPanel.this.elements.size()-1);i++){ try { MatchScoutingPanel.this.scoutingTable.insert(Integer.parseInt(values.get(0)), MatchScoutingPanel.this.elements.get(i).hashCode(), Integer.parseInt(values.get(i))); } catch (SQLException ex) { Logger.getLogger(MatchScoutingPanel.class.getName()).log(Level.SEVERE, null, ex); } } try { MatchScoutingPanel.this.commentTable.insert(Integer.parseInt(values.get(0)), Integer.parseInt(values.get(1)), values.get(values.size()-1)); } catch (SQLException ex) { Logger.getLogger(MatchScoutingPanel.class.getName()).log(Level.SEVERE, null, ex); } for(ScoutingElement s: MatchScoutingPanel.this.elements){ s.clear(); } } } } class ElementClear implements ActionListener{ public void actionPerformed(ActionEvent ae) { for(ScoutingElement s: MatchScoutingPanel.this.elements){ s.clear(); } } } class WeightingSubmit implements ActionListener{ public void actionPerformed(ActionEvent ae) { try { MatchScoutingPanel.this.weightingTable.reset(); } catch (SQLException ex) { Logger.getLogger(MatchScoutingPanel.class.getName()).log(Level.SEVERE, null, ex); } for(WeightingSliderElement e:MatchScoutingPanel.this.weightingElements){ try { MatchScoutingPanel.this.weightingTable.insert(e.hashCode(), Integer.parseInt(e.getInput())); } catch (SQLException ex) { Logger.getLogger(MatchScoutingPanel.class.getName()).log(Level.SEVERE, null, ex); } } } } class WeightingClear implements ActionListener{ public void actionPerformed(ActionEvent ae) { for(WeightingSliderElement e:MatchScoutingPanel.this.weightingElements){ try { e.setValue(MatchScoutingPanel.this.weightingTable.getValue(e.hashCode())); } catch (SQLException ex) { Logger.getLogger(MatchScoutingPanel.class.getName()).log(Level.SEVERE, null, ex); } } } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.h2; import java.sql.*; import java.util.HashMap; import java.util.Map; /** * * @author Saketh Kasibatla */ public class WeightingTable extends H2Table{ public WeightingTable(String database) throws ClassNotFoundException, SQLException{ super(database); statement.executeUpdate("create table if not exists weight(ID int,value int);"); } public void insert(int ID, int value) throws SQLException{ PreparedStatement prep= connection.prepareStatement( "insert into weight values(?,?);"); prep.setInt(1, ID); prep.setInt(2, value); prep.addBatch(); connection.setAutoCommit(false); prep.executeBatch(); connection.setAutoCommit(true); } public int getValue(int ID) throws SQLException{ ResultSet rs; try { rs = statement.executeQuery("select * from weight where id=" + Integer.toString(ID)); rs.next(); return rs.getInt("value"); } catch (SQLException ex) { this.insert(ID, 100); return 100; } } public Map<Integer,Integer> getValues() throws SQLException{ ResultSet rs=statement.executeQuery("select * from weight"); Map<Integer,Integer> values=new HashMap<Integer,Integer>(); while(rs.next()){ Integer key; Integer value; key=rs.getInt("ID"); value=rs.getInt("value"); values.put(key, value); } return values; } public void reset() throws SQLException{ statement.executeUpdate("Drop table weight;"); statement.executeUpdate("create table if not exists weight(ID int,value int);"); } }
Java
package com.team1160.scouting.h2; import java.sql.*; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Represents the h2 table that takes match scouting data input. * * ____________________________________________ * | team # (int) | type (int) | value (int) | * -------------------------------------------- * | 1. ... | 2. ... | 3. ... | * -------------------------------------------- * * 1. the team number of the inputted data * 2. the type (the hashcode of the type input) i.e: # points scored * 3. the value of the input * * @author Saketh Kasibatla */ public class MatchScoutingTable extends H2Table{ public MatchScoutingTable(String database) throws ClassNotFoundException, SQLException{ super(database); statement.executeUpdate("create table if not exists match(team int,ID int,value int);"); } /** * inserts a row into the database. * @param team the team number of the data * @param ID the ID (hashcode) of the data * @param value the data */ public void insert(int team,int ID,int value) throws SQLException{ PreparedStatement prep= connection.prepareStatement( "insert into match values(?,?,?);"); prep.setInt(1, team); prep.setInt(2, ID); prep.setInt(3, value); prep.addBatch(); connection.setAutoCommit(false); prep.executeBatch(); connection.setAutoCommit(true); } /** * gets the values in the table. * @param team the team name whose values will be retrieved * @return a map containing a type and value for each data entry under the team. */ public Map<Integer,Integer> getValues(int team) throws SQLException{ ResultSet rs=statement.executeQuery("select * from match where team="+Integer.toString(team)); Map<Integer,Integer> values=new HashMap<Integer,Integer>(); while(rs.next()){ Integer key,value; key=rs.getInt("value"); value=rs.getInt("ID"); values.put(key, value); } return values; } /** * gets all values with the inputted team and ID. * @param team the team number which the values are under. * @param ID the id (hashcode) which the values are under. * @return a list of all the values. */ public List<Integer> getValues(int team,int ID) throws SQLException{ ResultSet rs=statement.executeQuery("select * from match where team="+Integer.toString(team)+"and ID="+Integer.toString(ID)); List<Integer> values=new ArrayList<Integer>(); while(rs.next()){ Integer value; value=rs.getInt("value"); values.add(value); } return values; } public int getAverageValue(int team, int ID) throws SQLException{ List<Integer> values = this.getValues(team, ID); int sum = 0; for(Integer i:values){ sum += i; } // System.out.println(team); // System.out.println(values.size()); // System.out.println(sum/(values.size())); // System.out.println("\n"); int average = (values.size()==0)?0:sum/(values.size()); return average; } public List<Integer> getTeams() throws SQLException{ ResultSet rs = statement.executeQuery("select distinct team from match"); List<Integer> teams = new ArrayList<Integer>(); while(rs.next()){ Integer team; team=rs.getInt("team"); teams.add(team); } Collections.sort(teams); return teams; } public void reset() throws SQLException{ statement.executeUpdate("Drop table match;"); statement.executeUpdate("create table if not exists match(team int,ID int,value int);"); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.h2; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * * @author sakekasi */ public class CommentTable extends H2Table{ public CommentTable(String database) throws ClassNotFoundException, SQLException { super(database); statement.executeUpdate("create table if not exists comment(team int,match int,comment varchar);"); } public void insert(int team, int match, String comment) throws SQLException{ PreparedStatement prep= connection.prepareStatement( "insert into comment values(?,?,?);"); prep.setInt(1, team); prep.setInt(2, match); prep.setString(3, comment); prep.addBatch(); connection.setAutoCommit(false); prep.executeBatch(); connection.setAutoCommit(true); } public String getComment(int team, int match) throws SQLException{ ResultSet rs; rs = statement.executeQuery("select * from comment where team=" + Integer.toString(team) +"and match="+Integer.toString(match)); rs.next(); return rs.getString("comment"); } public Map<Integer, String> getComments(int team) throws SQLException{ ResultSet rs; rs = statement.executeQuery("select * from comment where team="+ Integer.toString(team)); Map<Integer, String> comments = new LinkedHashMap<Integer, String>(); while(rs.next()){ Integer key; String value; key=rs.getInt("match"); value=rs.getString("comment"); System.out.println(value); comments.put(key, value); } return comments; } public List<Integer> getTeams() throws SQLException{ ResultSet rs = statement.executeQuery("select distinct team from match"); List<Integer> teams = new ArrayList<Integer>(); while(rs.next()){ Integer team; team=rs.getInt("team"); teams.add(team); } Collections.sort(teams); return teams; } public void reset() throws SQLException{ statement.executeUpdate("Drop table comment;"); statement.executeUpdate("create table if not exists comment(team int,match int,comment varchar);"); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.h2; import java.sql.*; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * * @author Saketh Kasibatla */ public class DictTable extends H2Table{ public DictTable(String database) throws SQLException, ClassNotFoundException{ super(database); statement.executeUpdate("create table if not exists dictweight(ID int,value varchar);"); } public void insert(int ID, String value) throws SQLException{ PreparedStatement prep= connection.prepareStatement( "insert into dictweight values(?,?);"); prep.setInt(1, ID); prep.setString(2, value); prep.addBatch(); connection.setAutoCommit(false); prep.executeBatch(); connection.setAutoCommit(true); } public String getString(int ID) throws SQLException{ ResultSet rs=statement.executeQuery("select * from dictweight where id=" +Integer.toString(ID)); return rs.getString("value"); } public String getID(String value) throws SQLException{ ResultSet rs=statement.executeQuery("select * from dictweight where value=" +value); return rs.getString("ID"); } public Map<Integer,String> getValuesID() throws SQLException{ ResultSet rs=statement.executeQuery("select * from dictweight"); Map<Integer,String> values=new LinkedHashMap<Integer,String>(); while(rs.next()){ Integer key; String value; key=rs.getInt("ID"); value=rs.getString("value"); values.put(key, value); } return values; } public Map<String,Integer> getValuesName() throws SQLException{ ResultSet rs=statement.executeQuery("select * from dictweight"); Map<String,Integer> values=new LinkedHashMap<String,Integer>(); while(rs.next()){ Integer key; String value; key=rs.getInt("ID"); value=rs.getString("value"); values.put(value, key); } return values; } public void reset() throws SQLException{ statement.executeUpdate("Drop table dictweight;"); statement.executeUpdate("create table if not exists dictweight(ID int,value varchar);"); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.h2; import java.sql.*; import org.h2.Driver; /** * * @author Saketh Kasibatla */ public abstract class H2Table { /** * the location of the database. */ protected String database; /** * the Connection object provided (java.sql) * created from the database string. */ protected Connection connection; /** * the Statement object used to send commands * to the database. */ protected Statement statement; public H2Table(String database) throws ClassNotFoundException, SQLException{ this.database = database; Class.forName("org.h2.Driver"); connection= DriverManager.getConnection("jdbc:h2:"+database); statement=connection.createStatement(); } }
Java
package com.team1160.scouting.xml; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * This class parses the config.xml file and returns elements which are nodes of the xml tree. * @author Saketh Kasibatla */ public class XMLParser { /** * the name of the document to be parsed. */ String documentName; /** * the file at location documentName */ File documentFile; /** * the document which is parsed by the java parsers. */ Document document; /** * creates a new XMLParser from the document name * @param documentName the name of the document to be read */ public XMLParser(String documentName) throws ParserConfigurationException, SAXException, IOException { this.documentName = documentName; documentFile = new File(documentName); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); document=db.parse(documentFile); document.getDocumentElement().normalize(); } /** * gets the match node of the xml document. * @return the match subnode in the xml document */ public Element getMatch() { NodeList nodes = document.getDocumentElement().getChildNodes(); for(int i=0;i<nodes.getLength();i++){ if(nodes.item(i).getNodeType()==Node.ELEMENT_NODE){ Element e=(Element) nodes.item(i); if(e.getTagName().equals("match")){ return e; } } } throw new NullPointerException("no tag named match"); } /** * * @return the pit subnode in the xml document */ public Element getPit() { NodeList nodes = document.getDocumentElement().getChildNodes(); for(int i=0;i<nodes.getLength();i++){ if(nodes.item(i).getNodeType()==Node.ELEMENT_NODE){ Element e=(Element) nodes.item(i); if(e.getTagName().equals("pit")){ return e; } } } throw new NullPointerException("no tag named pit"); } }
Java
/** Automatically generated file. DO NOT MODIFY */ package com.example.testgps; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package com.example.testgps; import android.app.Activity; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements LocationListener { private TextView latituteField; private TextView longitudeField; private LocationManager locationManager; private String provider; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); latituteField = (TextView) findViewById(R.id.TextView02); longitudeField = (TextView) findViewById(R.id.TextView04); // Get the location manager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Define the criteria how to select the locatioin provider -> use // default Criteria criteria = new Criteria(); provider = locationManager.getBestProvider(criteria, false); Location location = locationManager.getLastKnownLocation(provider); // Initialize the location fields if (location != null) { System.out.println("Provider " + provider + " has been selected."); double lat = (double) (location.getLatitude()); double lng = (double) (location.getLongitude()); latituteField.setText(String.valueOf(lat)); longitudeField.setText(String.valueOf(lng)); } else { latituteField.setText("Provider not available"); longitudeField.setText("Provider not available"); } } /* Request updates at startup */ @Override protected void onResume() { super.onResume(); locationManager.requestLocationUpdates(provider, 400, 1, this); } /* Remove the locationlistener updates when Activity is paused */ @Override protected void onPause() { super.onPause(); locationManager.removeUpdates(this); } public void onLocationChanged(Location location) { double lat = (double) (location.getLatitude()); double lng = (double) (location.getLongitude()); latituteField.setText(String.valueOf(lat)); longitudeField.setText(String.valueOf(lng)); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { Toast.makeText(this, "Enabled new provider " + provider, Toast.LENGTH_SHORT).show(); } public void onProviderDisabled(String provider) { Toast.makeText(this, "Disabled provider " + provider, Toast.LENGTH_SHORT).show(); } }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.CircleOutlineParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AlphaInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.ui.activity.LayoutGameActivity; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class XMLLayoutExample extends LayoutGameActivity { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getLayoutID() { return R.layout.xmllayoutexample; } @Override protected int getRenderSurfaceViewID() { return R.id.xmllayoutexample_rendersurfaceview; } @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to move the particlesystem.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_point.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final CircleOutlineParticleEmitter particleEmitter = new CircleOutlineParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f + 20, 80); final ParticleSystem particleSystem = new ParticleSystem(particleEmitter, 60, 60, 360, this.mParticleTextureRegion); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { particleEmitter.setCenter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } }); particleSystem.addParticleInitializer(new ColorInitializer(1, 0, 0)); particleSystem.addParticleInitializer(new AlphaInitializer(0)); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-2, 2, -20, -10)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleModifier(new ScaleModifier(1.0f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0, 0.5f, 0, 0, 0, 3)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0.5f, 1, 0, 1, 4, 6)); particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 1)); particleSystem.addParticleModifier(new AlphaModifier(1, 0, 5, 6)); particleSystem.addParticleModifier(new ExpireModifier(6, 6)); scene.attachChild(particleSystem); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.entity.scene.menu.MenuScene; import org.anddev.andengine.entity.scene.menu.animator.SlideMenuAnimator; import org.anddev.andengine.entity.scene.menu.item.IMenuItem; import org.anddev.andengine.entity.scene.menu.item.SpriteMenuItem; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:33:33 - 01.04.2010 */ public class SubMenuExample extends MenuExample { // =========================================================== // Constants // =========================================================== private static final int MENU_QUIT_OK = MenuExample.MENU_QUIT + 1; private static final int MENU_QUIT_BACK = MENU_QUIT_OK + 1; // =========================================================== // Fields // =========================================================== private MenuScene mSubMenuScene; private BitmapTextureAtlas mSubMenuTexture; private TextureRegion mMenuOkTextureRegion; private TextureRegion mMenuBackTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onLoadResources() { super.onLoadResources(); this.mSubMenuTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mMenuOkTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mSubMenuTexture, this, "menu_ok.png", 0, 0); this.mMenuBackTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mSubMenuTexture, this, "menu_back.png", 0, 50); this.mEngine.getTextureManager().loadTexture(this.mSubMenuTexture); } @Override protected void createMenuScene() { super.createMenuScene(); this.mSubMenuScene = new MenuScene(this.mCamera); this.mSubMenuScene.addMenuItem(new SpriteMenuItem(MENU_QUIT_OK, this.mMenuOkTextureRegion)); this.mSubMenuScene.addMenuItem(new SpriteMenuItem(MENU_QUIT_BACK, this.mMenuBackTextureRegion)); this.mSubMenuScene.setMenuAnimator(new SlideMenuAnimator()); this.mSubMenuScene.buildAnimations(); this.mSubMenuScene.setBackgroundEnabled(false); this.mSubMenuScene.setOnMenuItemClickListener(this); } @Override public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) { switch(pMenuItem.getID()) { case MENU_RESET: this.mMainScene.reset(); this.mMenuScene.back(); return true; case MENU_QUIT: pMenuScene.setChildSceneModal(this.mSubMenuScene); return true; case MENU_QUIT_BACK: this.mSubMenuScene.back(); return true; case MENU_QUIT_OK: this.finish(); return true; default: return false; } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class SpriteExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; /* Create the face and add it to the scene. */ final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); scene.attachChild(face); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.AlphaModifier; import org.anddev.andengine.entity.modifier.DelayModifier; import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.LoopEntityModifier.ILoopEntityModifierListener; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationByModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.modifier.IModifier; import org.anddev.andengine.util.modifier.LoopModifier; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class EntityModifierExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Rectangle rect = new Rectangle(centerX + 100, centerY, 32, 32); rect.setColor(1, 0, 0); final AnimatedSprite face = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion); face.animate(100); face.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); final LoopEntityModifier entityModifier = new LoopEntityModifier( new IEntityModifierListener() { @Override public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Sequence started.", Toast.LENGTH_SHORT).show(); } }); } @Override public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Sequence finished.", Toast.LENGTH_SHORT).show(); } }); } }, 2, new ILoopEntityModifierListener() { @Override public void onLoopStarted(final LoopModifier<IEntity> pLoopModifier, final int pLoop, final int pLoopCount) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Loop: '" + (pLoop + 1) + "' of '" + pLoopCount + "' started.", Toast.LENGTH_SHORT).show(); } }); } @Override public void onLoopFinished(final LoopModifier<IEntity> pLoopModifier, final int pLoop, final int pLoopCount) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Loop: '" + (pLoop + 1) + "' of '" + pLoopCount + "' finished.", Toast.LENGTH_SHORT).show(); } }); } }, new SequenceEntityModifier( new RotationModifier(1, 0, 90), new AlphaModifier(2, 1, 0), new AlphaModifier(1, 0, 1), new ScaleModifier(2, 1, 0.5f), new DelayModifier(0.5f), new ParallelEntityModifier( new ScaleModifier(3, 0.5f, 5), new RotationByModifier(3, 90) ), new ParallelEntityModifier( new ScaleModifier(3, 5, 1), new RotationModifier(3, 180, 0) ) ) ); face.registerEntityModifier(entityModifier); rect.registerEntityModifier(entityModifier.deepCopy()); scene.attachChild(face); scene.attachChild(rect); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.PathModifier; import org.anddev.andengine.entity.modifier.PathModifier.IPathModifierListener; import org.anddev.andengine.entity.modifier.PathModifier.Path; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.RepeatingSpriteBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.modifier.ease.EaseSineInOut; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class PathModifierExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private RepeatingSpriteBackground mGrassBackground; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mPlayerTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "You move my sprite right round, right round...", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.DEFAULT); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "player.png", 0, 0, 3, 4); this.mGrassBackground = new RepeatingSpriteBackground(CAMERA_WIDTH, CAMERA_HEIGHT, this.mEngine.getTextureManager(), new AssetBitmapTextureAtlasSource(this, "background_grass.png")); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { // this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(this.mGrassBackground); /* Create the face and add it to the scene. */ final AnimatedSprite player = new AnimatedSprite(10, 10, 48, 64, this.mPlayerTextureRegion); final Path path = new Path(5).to(10, 10).to(10, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, 10).to(10, 10); /* Add the proper animation when a waypoint of the path is passed. */ player.registerEntityModifier(new LoopEntityModifier(new PathModifier(30, path, null, new IPathModifierListener() { @Override public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity) { Debug.d("onPathStarted"); } @Override public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { Debug.d("onPathWaypointStarted: " + pWaypointIndex); switch(pWaypointIndex) { case 0: player.animate(new long[]{200, 200, 200}, 6, 8, true); break; case 1: player.animate(new long[]{200, 200, 200}, 3, 5, true); break; case 2: player.animate(new long[]{200, 200, 200}, 0, 2, true); break; case 3: player.animate(new long[]{200, 200, 200}, 9, 11, true); break; } } @Override public void onPathWaypointFinished(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { Debug.d("onPathWaypointFinished: " + pWaypointIndex); } @Override public void onPathFinished(final PathModifier pPathModifier, final IEntity pEntity) { Debug.d("onPathFinished"); } }, EaseSineInOut.getInstance()))); scene.attachChild(player); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 21:18:08 - 27.06.2010 */ public class PhysicsJumpExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener, IOnAreaTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 360; private static final int CAMERA_HEIGHT = 240; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private int mFaceCount = 0; private PhysicsWorld mPhysicsWorld; private float mGravityX; private float mGravityY; private Scene mScene; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects. Touch an object to shoot it up into the air.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); this.mScene.setOnAreaTouchListener(this); return this.mScene; } @Override public boolean onAreaTouched( final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea,final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { final AnimatedSprite face = (AnimatedSprite) pTouchArea; this.jumpFace(face); return true; } return false; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { this.mGravityX = pAccelerometerData.getX(); this.mGravityY = pAccelerometerData.getY(); final Vector2 gravity = Vector2Pool.obtain(this.mGravityX, this.mGravityY); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; final AnimatedSprite face; final Body body; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount % 2 == 1){ face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); face.animate(new long[]{200,200}, 0, 1, true); face.setUserData(body); this.mScene.registerTouchArea(face); this.mScene.attachChild(face); } private void jumpFace(final AnimatedSprite face) { final Body faceBody = (Body)face.getUserData(); final Vector2 velocity = Vector2Pool.obtain(this.mGravityX * -50, this.mGravityY * -50); faceBody.setLinearVelocity(velocity); Vector2Pool.recycle(velocity); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.CircleOutlineParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AlphaInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ParticleSystemSimpleExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to move the particlesystem.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_point.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final CircleOutlineParticleEmitter particleEmitter = new CircleOutlineParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f + 20, 80); final ParticleSystem particleSystem = new ParticleSystem(particleEmitter, 60, 60, 360, this.mParticleTextureRegion); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { particleEmitter.setCenter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } }); particleSystem.addParticleInitializer(new ColorInitializer(1, 0, 0)); particleSystem.addParticleInitializer(new AlphaInitializer(0)); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-2, 2, -20, -10)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleModifier(new ScaleModifier(1.0f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0, 0.5f, 0, 0, 0, 3)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0.5f, 1, 0, 1, 4, 6)); particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 1)); particleSystem.addParticleModifier(new AlphaModifier(1, 0, 5, 6)); particleSystem.addParticleModifier(new ExpireModifier(6, 6)); scene.attachChild(particleSystem); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.MoveModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.scene.menu.MenuScene; import org.anddev.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener; import org.anddev.andengine.entity.scene.menu.item.IMenuItem; import org.anddev.andengine.entity.scene.menu.item.TextMenuItem; import org.anddev.andengine.entity.scene.menu.item.decorator.ColorMenuItemDecorator; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.FontFactory; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.graphics.Color; import android.view.KeyEvent; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 01:30:15 - 02.04.2010 */ public class TextMenuExample extends BaseExample implements IOnMenuItemClickListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; protected static final int MENU_RESET = 0; protected static final int MENU_QUIT = MENU_RESET + 1; // =========================================================== // Fields // =========================================================== protected Camera mCamera; protected Scene mMainScene; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mFontTexture; private Font mFont; protected MenuScene mMenuScene; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { /* Load Font/Textures. */ this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); FontFactory.setAssetBasePath("font/"); this.mFont = FontFactory.createFromAsset(this.mFontTexture, this, "Plok.ttf", 48, true, Color.WHITE); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.getFontManager().loadFont(this.mFont); /* Load Sprite-Textures. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box_menu.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mMenuScene = this.createMenuScene(); /* Just a simple scene with an animated face flying around. */ this.mMainScene = new Scene(); this.mMainScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - face.getWidth(), 0, CAMERA_HEIGHT - face.getHeight())); this.mMainScene.attachChild(face); return this.mMainScene; } @Override public void onLoadComplete() { } @Override public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) { if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) { if(this.mMainScene.hasChildScene()) { /* Remove the menu and reset it. */ this.mMenuScene.back(); } else { /* Attach the menu. */ this.mMainScene.setChildScene(this.mMenuScene, false, true, true); } return true; } else { return super.onKeyDown(pKeyCode, pEvent); } } @Override public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) { switch(pMenuItem.getID()) { case MENU_RESET: /* Restart the animation. */ this.mMainScene.reset(); /* Remove the menu and reset it. */ this.mMainScene.clearChildScene(); this.mMenuScene.reset(); return true; case MENU_QUIT: /* End Activity. */ this.finish(); return true; default: return false; } } // =========================================================== // Methods // =========================================================== protected MenuScene createMenuScene() { final MenuScene menuScene = new MenuScene(this.mCamera); final IMenuItem resetMenuItem = new ColorMenuItemDecorator(new TextMenuItem(MENU_RESET, this.mFont, "RESET"), 1.0f,0.0f,0.0f, 0.0f,0.0f,0.0f); resetMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); menuScene.addMenuItem(resetMenuItem); final IMenuItem quitMenuItem = new ColorMenuItemDecorator(new TextMenuItem(MENU_QUIT, this.mFont, "QUIT"), 1.0f,0.0f,0.0f, 0.0f,0.0f,0.0f); quitMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); menuScene.addMenuItem(quitMenuItem); menuScene.buildAnimations(); menuScene.setBackgroundEnabled(false); menuScene.setOnMenuItemClickListener(this); return menuScene; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.IOException; import java.io.InputStream; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.ZoomState; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRTexture; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRTexture.PVRTextureFormat; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 13.07.2011 */ public class PVRTextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private ITexture mTextureRGB565; private ITexture mTextureRGBA5551; private ITexture mTextureARGB4444; private ITexture mTextureRGBA888MipMaps; private TextureRegion mHouseNearestTextureRegion; private TextureRegion mHouseLinearTextureRegion; private TextureRegion mHouseMipMapsNearestTextureRegion; private TextureRegion mHouseMipMapsLinearTextureRegion; private ZoomState mZoomState = ZoomState.NONE; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "The lower houses use MipMaps!", Toast.LENGTH_LONG); Toast.makeText(this, "Click the top half of the screen to zoom in or the bottom half to zoom out!", Toast.LENGTH_LONG); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 0, 0, 0.1f) { @Override public void onUpdate(final float pSecondsElapsed) { switch (PVRTextureExample.this.mZoomState) { case IN: this.setZoomFactor(this.getZoomFactor() + 0.1f * pSecondsElapsed); break; case OUT: this.setZoomFactor(this.getZoomFactor() - 0.1f * pSecondsElapsed); break; } super.onUpdate(pSecondsElapsed); } }; return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { try { this.mTextureRGB565 = new PVRTexture(PVRTextureFormat.RGB_565, new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) { @Override protected InputStream onGetInputStream() throws IOException { return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_rgb_565); } }; this.mTextureRGBA5551 = new PVRTexture(PVRTextureFormat.RGBA_5551, new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) { @Override protected InputStream onGetInputStream() throws IOException { return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_argb_5551); } }; this.mTextureARGB4444 = new PVRTexture(PVRTextureFormat.RGBA_4444, new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) { @Override protected InputStream onGetInputStream() throws IOException { return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_argb_4444); } }; this.mTextureRGBA888MipMaps = new PVRTexture(PVRTextureFormat.RGBA_8888, new TextureOptions(GL10.GL_LINEAR_MIPMAP_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) { @Override protected InputStream onGetInputStream() throws IOException { return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_argb_8888_mipmaps); } }; this.mHouseNearestTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureRGB565, 0, 0, 512, 512, true); this.mHouseLinearTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureRGBA5551, 0, 0, 512, 512, true); this.mHouseMipMapsNearestTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureARGB4444, 0, 0, 512, 512, true); this.mHouseMipMapsLinearTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureRGBA888MipMaps, 0, 0, 512, 512, true); this.mEngine.getTextureManager().loadTextures(this.mTextureRGB565, this.mTextureRGBA5551, this.mTextureARGB4444, this.mTextureRGBA888MipMaps); } catch (final Throwable e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = CAMERA_WIDTH / 2; final int centerY = CAMERA_HEIGHT / 2; final Entity container = new Entity(centerX, centerY); container.setScale(0.5f); container.attachChild(new Sprite(-512, -384, this.mHouseNearestTextureRegion)); container.attachChild(new Sprite(0, -384, this.mHouseLinearTextureRegion)); container.attachChild(new Sprite(-512, -128, this.mHouseMipMapsNearestTextureRegion)); container.attachChild(new Sprite(0, -128, this.mHouseMipMapsLinearTextureRegion)); scene.attachChild(container); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) { if(pSceneTouchEvent.getY() < CAMERA_HEIGHT / 2) { PVRTextureExample.this.mZoomState = ZoomState.IN; } else { PVRTextureExample.this.mZoomState = ZoomState.OUT; } } else { PVRTextureExample.this.mZoomState = ZoomState.NONE; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class AnalogOnScreenControlsExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_LONG).show(); } else { this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true; Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); /* Velocity control (left). */ final int x1 = 0; final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(); final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); velocityOnScreenControl.getControlBase().setAlpha(0.5f); scene.setChildScene(velocityOnScreenControl); /* Rotation control (right). */ final int y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1; final int x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth(); final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { if(pValueX == x1 && pValueY == x1) { face.setRotation(x1); } else { face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY))); } } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); rotationOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); rotationOnScreenControl.getControlBase().setAlpha(0.5f); velocityOnScreenControl.setChildScene(rotationOnScreenControl); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class AnalogOnScreenControlExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Also try tapping this AnalogOnScreenControl!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); final AnalogOnScreenControl analogOnScreenControl = new AnalogOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, 200, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { face.registerEntityModifier(new SequenceEntityModifier(new ScaleModifier(0.25f, 1, 1.5f), new ScaleModifier(0.25f, 1.5f, 1))); } }); analogOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); analogOnScreenControl.getControlBase().setAlpha(0.5f); analogOnScreenControl.getControlBase().setScaleCenter(0, 128); analogOnScreenControl.getControlBase().setScale(1.25f); analogOnScreenControl.getControlKnob().setScale(1.25f); analogOnScreenControl.refreshControlKnobPosition(); scene.setChildScene(analogOnScreenControl); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ZoomExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch and hold the scene and the camera will smoothly zoom in.\nRelease the scene it to zoom out again.", Toast.LENGTH_LONG).show(); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 10, 10, 1.0f); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Calculate the coordinates for the screen-center. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; /* Create some faces and add them to the scene. */ scene.attachChild(new Sprite(centerX - 25, centerY - 25, this.mFaceTextureRegion)); scene.attachChild(new Sprite(centerX + 25, centerY - 25, this.mFaceTextureRegion)); scene.attachChild(new Sprite(centerX, centerY + 25, this.mFaceTextureRegion)); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { switch(pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: ZoomExample.this.mSmoothCamera.setZoomFactor(5.0f); break; case TouchEvent.ACTION_UP: ZoomExample.this.mSmoothCamera.setZoomFactor(1.0f); break; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class CoordinateConversionExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private Scene mScene; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "The arrow will always point to the left eye of the face!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_LONG).show(); } else { this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true; Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Create three lines that will form an arrow pointing to the eye. */ final Line arrowLineMain = new Line(0, 0, 0, 0, 3); final Line arrowLineWingLeft = new Line(0, 0, 0, 0, 3); final Line arrowLineWingRight = new Line(0, 0, 0, 0, 3); arrowLineMain.setColor(1, 0, 0); arrowLineWingLeft.setColor(1, 0, 0); arrowLineWingRight.setColor(1, 0, 0); /* Create a face-sprite. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion){ @Override protected void onManagedUpdate(final float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); final float[] eyeCoordinates = this.convertLocalToSceneCoordinates(11, 13); final float eyeX = eyeCoordinates[VERTEX_INDEX_X]; final float eyeY = eyeCoordinates[VERTEX_INDEX_Y]; arrowLineMain.setPosition(eyeX, eyeY, eyeX, eyeY - 50); arrowLineWingLeft.setPosition(eyeX, eyeY, eyeX - 10, eyeY - 10); arrowLineWingRight.setPosition(eyeX, eyeY, eyeX + 10, eyeY - 10); } }; final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); face.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new ScaleModifier(3, 1, 1.75f), new ScaleModifier(3, 1.75f, 1)))); this.mScene.attachChild(face); this.mScene.attachChild(arrowLineMain); this.mScene.attachChild(arrowLineWingLeft); this.mScene.attachChild(arrowLineWingRight); /* Velocity control (left). */ final int x1 = 0; final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(); final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); velocityOnScreenControl.getControlBase().setAlpha(0.5f); this.mScene.setChildScene(velocityOnScreenControl); /* Rotation control (right). */ final int y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1; final int x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth(); final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { if(pValueX == x1 && pValueY == x1) { face.setRotation(x1); } else { face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY))); } } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); rotationOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); rotationOnScreenControl.getControlBase().setAlpha(0.5f); velocityOnScreenControl.setChildScene(rotationOnScreenControl); return this.mScene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.entity.util.ScreenCapture; import org.anddev.andengine.entity.util.ScreenCapture.IScreenCaptureCallback; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.util.FileUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ScreenCaptureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to capture it (screenshot).", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final ScreenCapture screenCapture = new ScreenCapture(); scene.setBackground(new ColorBackground(0, 0, 0)); /* Create three lines that will form an arrow pointing to the eye. */ final Line arrowLineMain = new Line(0, 0, 0, 0, 3); final Line arrowLineWingLeft = new Line(0, 0, 0, 0, 3); final Line arrowLineWingRight = new Line(0, 0, 0, 0, 3); arrowLineMain.setColor(1, 0, 1); arrowLineWingLeft.setColor(1, 0, 1); arrowLineWingRight.setColor(1, 0, 1); scene.attachChild(arrowLineMain); scene.attachChild(arrowLineWingLeft); scene.attachChild(arrowLineWingRight); /* Create the rectangles. */ final Rectangle rect1 = this.makeColoredRectangle(-180, -180, 1, 0, 0); final Rectangle rect2 = this.makeColoredRectangle(0, -180, 0, 1, 0); final Rectangle rect3 = this.makeColoredRectangle(0, 0, 0, 0, 1); final Rectangle rect4 = this.makeColoredRectangle(-180, 0, 1, 1, 0); final Entity rectangleGroup = new Entity(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2); rectangleGroup.registerEntityModifier(new LoopEntityModifier(new ParallelEntityModifier( new SequenceEntityModifier( new ScaleModifier(10, 1, 0.5f), new ScaleModifier(10, 0.5f, 1) ), new RotationModifier(20, 0, 360)) )); rectangleGroup.attachChild(rect1); rectangleGroup.attachChild(rect2); rectangleGroup.attachChild(rect3); rectangleGroup.attachChild(rect4); scene.attachChild(rectangleGroup); /* Attaching the ScreenCapture to the end. */ scene.attachChild(screenCapture); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { final int viewWidth = ScreenCaptureExample.this.mRenderSurfaceView.getWidth(); final int viewHeight = ScreenCaptureExample.this.mRenderSurfaceView.getHeight(); screenCapture.capture(viewWidth, viewHeight, FileUtils.getAbsolutePathOnExternalStorage(ScreenCaptureExample.this, "Screen_" + System.currentTimeMillis() + ".png"), new IScreenCaptureCallback() { @Override public void onScreenCaptured(final String pFilePath) { ScreenCaptureExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(ScreenCaptureExample.this, "Screenshot: " + pFilePath + " taken!", Toast.LENGTH_SHORT).show(); } }); } @Override public void onScreenCaptureFailed(final String pFilePath, final Exception pException) { ScreenCaptureExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(ScreenCaptureExample.this, "FAILED capturing Screenshot: " + pFilePath + " !", Toast.LENGTH_SHORT).show(); } }); } }); } return true; } }); return scene; } private Rectangle makeColoredRectangle(final float pX, final float pY, final float pRed, final float pGreen, final float pBlue) { final Rectangle coloredRect = new Rectangle(pX, pY, 180, 180); coloredRect.setColor(pRed, pGreen, pBlue); final Rectangle subRectangle = new Rectangle(45, 45, 90, 90); subRectangle.registerEntityModifier(new LoopEntityModifier(new RotationModifier(3, 0, 360))); coloredRect.attachChild(subRectangle); return coloredRect; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class MovingBallExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final float DEMO_VELOCITY = 100.0f; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 0, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Ball ball = new Ball(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(ball); ball.registerUpdateHandler(physicsHandler); physicsHandler.setVelocity(DEMO_VELOCITY, DEMO_VELOCITY); scene.attachChild(ball); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== private static class Ball extends AnimatedSprite { private final PhysicsHandler mPhysicsHandler; public Ball(final float pX, final float pY, final TiledTextureRegion pTextureRegion) { super(pX, pY, pTextureRegion); this.mPhysicsHandler = new PhysicsHandler(this); this.registerUpdateHandler(this.mPhysicsHandler); } @Override protected void onManagedUpdate(final float pSecondsElapsed) { if(this.mX < 0) { this.mPhysicsHandler.setVelocityX(DEMO_VELOCITY); } else if(this.mX + this.getWidth() > CAMERA_WIDTH) { this.mPhysicsHandler.setVelocityX(-DEMO_VELOCITY); } if(this.mY < 0) { this.mPhysicsHandler.setVelocityY(DEMO_VELOCITY); } else if(this.mY + this.getHeight() > CAMERA_HEIGHT) { this.mPhysicsHandler.setVelocityY(-DEMO_VELOCITY); } super.onManagedUpdate(pSecondsElapsed); } } }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.AutoParallaxBackground; import org.anddev.andengine.entity.scene.background.ParallaxBackground.ParallaxEntity; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 19:58:39 - 19.07.2010 */ public class AutoParallaxBackgroundExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mPlayerTextureRegion; private TiledTextureRegion mEnemyTextureRegion; private BitmapTextureAtlas mAutoParallaxBackgroundTexture; private TextureRegion mParallaxLayerBack; private TextureRegion mParallaxLayerMid; private TextureRegion mParallaxLayerFront; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "player.png", 0, 0, 3, 4); this.mEnemyTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "enemy.png", 73, 0, 3, 4); this.mAutoParallaxBackgroundTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.DEFAULT); this.mParallaxLayerFront = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "parallax_background_layer_front.png", 0, 0); this.mParallaxLayerBack = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "parallax_background_layer_back.png", 0, 188); this.mParallaxLayerMid = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "parallax_background_layer_mid.png", 0, 669); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mAutoParallaxBackgroundTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final AutoParallaxBackground autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5); autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerBack.getHeight(), this.mParallaxLayerBack))); autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-5.0f, new Sprite(0, 80, this.mParallaxLayerMid))); autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-10.0f, new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerFront.getHeight(), this.mParallaxLayerFront))); scene.setBackground(autoParallaxBackground); /* Calculate the coordinates for the face, so its centered on the camera. */ final int playerX = (CAMERA_WIDTH - this.mPlayerTextureRegion.getTileWidth()) / 2; final int playerY = CAMERA_HEIGHT - this.mPlayerTextureRegion.getTileHeight() - 5; /* Create two sprits and add it to the scene. */ final AnimatedSprite player = new AnimatedSprite(playerX, playerY, this.mPlayerTextureRegion); player.setScaleCenterY(this.mPlayerTextureRegion.getTileHeight()); player.setScale(2); player.animate(new long[]{200, 200, 200}, 3, 5, true); final AnimatedSprite enemy = new AnimatedSprite(playerX - 80, playerY, this.mEnemyTextureRegion); enemy.setScaleCenterY(this.mEnemyTextureRegion.getTileHeight()); enemy.setScale(2); enemy.animate(new long[]{200, 200, 200}, 3, 5, true); scene.attachChild(player); scene.attachChild(enemy); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.app.cityradar; import java.util.ArrayList; import java.util.HashMap; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.HUD; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.FillResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.examples.adt.cityradar.City; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureBuilder; import org.anddev.andengine.opengl.texture.atlas.buildable.builder.ITextureBuilder.TextureAtlasSourcePackingException; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.sensor.location.ILocationListener; import org.anddev.andengine.sensor.location.LocationProviderStatus; import org.anddev.andengine.sensor.location.LocationSensorOptions; import org.anddev.andengine.sensor.orientation.IOrientationListener; import org.anddev.andengine.sensor.orientation.OrientationData; import org.anddev.andengine.ui.activity.BaseGameActivity; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.MathUtils; import org.anddev.andengine.util.modifier.ease.EaseLinear; import android.graphics.Color; import android.graphics.Typeface; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; public class CityRadarActivity extends BaseGameActivity implements IOrientationListener, ILocationListener { // =========================================================== // Constants // =========================================================== private static final boolean USE_MOCK_LOCATION = false; private static final boolean USE_ACTUAL_LOCATION = !USE_MOCK_LOCATION; private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 800; private static final int GRID_SIZE = 80; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BuildableBitmapTextureAtlas mBuildableBitmapTextureAtlas; private TextureRegion mRadarPointTextureRegion; private TextureRegion mRadarTextureRegion; private BitmapTextureAtlas mFontTexture; private Font mFont; private Location mUserLocation; private final ArrayList<City> mCities = new ArrayList<City>(); private final HashMap<City, Sprite> mCityToCitySpriteMap = new HashMap<City, Sprite>(); private final HashMap<City, Text> mCityToCityNameTextMap = new HashMap<City, Text>(); private Scene mScene; // =========================================================== // Constructors // =========================================================== public CityRadarActivity() { this.mCities.add(new City("London", 51.509, -0.118)); this.mCities.add(new City("New York", 40.713, -74.006)); // this.mCities.add(new City("Paris", 48.857, 2.352)); this.mCities.add(new City("Beijing", 39.929, 116.388)); this.mCities.add(new City("Sydney", -33.850, 151.200)); this.mCities.add(new City("Berlin", 52.518, 13.408)); this.mCities.add(new City("Rio", -22.908, -43.196)); this.mCities.add(new City("New Delhi", 28.636, 77.224)); this.mCities.add(new City("Cape Town", -33.926, 18.424)); this.mUserLocation = new Location(LocationManager.GPS_PROVIDER); if(USE_MOCK_LOCATION) { this.mUserLocation.setLatitude(51.518); this.mUserLocation.setLongitude(13.408); } } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public org.anddev.andengine.engine.Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CityRadarActivity.CAMERA_WIDTH, CityRadarActivity.CAMERA_HEIGHT); return new org.anddev.andengine.engine.Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new FillResolutionPolicy(), this.mCamera)); } @Override public void onLoadResources() { /* Init font. */ this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.DEFAULT, 12, true, Color.WHITE); this.getFontManager().loadFont(this.mFont); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); /* Init TextureRegions. */ this.mBuildableBitmapTextureAtlas = new BuildableBitmapTextureAtlas(512, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mRadarTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "radar.png"); this.mRadarPointTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "radarpoint.png"); try { this.mBuildableBitmapTextureAtlas.build(new BlackPawnTextureBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(1)); } catch (final TextureAtlasSourcePackingException e) { Debug.e(e); } this.mEngine.getTextureManager().loadTexture(this.mBuildableBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mScene = new Scene(); final HUD hud = new HUD(); this.mCamera.setHUD(hud); /* BACKGROUND */ this.initBackground(hud); /* CITIES */ this.initCitySprites(); return this.mScene; } private void initCitySprites() { final int cityCount = this.mCities.size(); for(int i = 0; i < cityCount; i++) { final City city = this.mCities.get(i); final Sprite citySprite = new Sprite(CityRadarActivity.CAMERA_WIDTH / 2, CityRadarActivity.CAMERA_HEIGHT / 2, this.mRadarPointTextureRegion); citySprite.setColor(0, 0.5f, 0, 1f); final Text cityNameText = new Text(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2, this.mFont, city.getName()) { @Override protected void onManagedDraw(final GL10 pGL, final Camera pCamera) { /* This ensures that the name of the city is always 'pointing down'. */ this.setRotation(-CityRadarActivity.this.mCamera.getRotation()); super.onManagedDraw(pGL, pCamera); } }; cityNameText.setRotationCenterY(- citySprite.getHeight() / 2); this.mCityToCityNameTextMap.put(city, cityNameText); this.mCityToCitySpriteMap.put(city, citySprite); this.mScene.attachChild(citySprite); this.mScene.attachChild(cityNameText); } } private void initBackground(final IEntity pEntity) { /* Vertical Grid lines. */ for(int i = CityRadarActivity.GRID_SIZE / 2; i < CityRadarActivity.CAMERA_WIDTH; i += CityRadarActivity.GRID_SIZE) { final Line line = new Line(i, 0, i, CityRadarActivity.CAMERA_HEIGHT); line.setColor(0, 0.5f, 0, 1f); pEntity.attachChild(line); } /* Horizontal Grid lines. */ for(int i = CityRadarActivity.GRID_SIZE / 2; i < CityRadarActivity.CAMERA_HEIGHT; i += CityRadarActivity.GRID_SIZE) { final Line line = new Line(0, i, CityRadarActivity.CAMERA_WIDTH, i); line.setColor(0, 0.5f, 0, 1f); pEntity.attachChild(line); } /* Vertical Grid lines. */ final Sprite radarSprite = new Sprite(CityRadarActivity.CAMERA_WIDTH / 2 - this.mRadarTextureRegion.getWidth(), CityRadarActivity.CAMERA_HEIGHT / 2 - this.mRadarTextureRegion.getHeight(), this.mRadarTextureRegion); radarSprite.setColor(0, 1f, 0, 1f); radarSprite.setRotationCenter(radarSprite.getWidth(), radarSprite.getHeight()); radarSprite.registerEntityModifier(new LoopEntityModifier(new RotationModifier(3, 0, 360, EaseLinear.getInstance()))); pEntity.attachChild(radarSprite); /* Title. */ final Text titleText = new Text(0, 0, this.mFont, "-- CityRadar --"); titleText.setPosition(CAMERA_WIDTH / 2 - titleText.getWidth() / 2, titleText.getHeight() + 35); titleText.setScale(2); titleText.setScaleCenterY(0); pEntity.attachChild(titleText); } @Override public void onLoadComplete() { this.refreshCitySprites(); } @Override protected void onResume() { super.onResume(); this.enableOrientationSensor(this); final LocationSensorOptions locationSensorOptions = new LocationSensorOptions(); locationSensorOptions.setAccuracy(Criteria.ACCURACY_COARSE); locationSensorOptions.setMinimumTriggerTime(0); locationSensorOptions.setMinimumTriggerDistance(0); this.enableLocationSensor(this, locationSensorOptions); } @Override protected void onPause() { super.onPause(); this.mEngine.disableOrientationSensor(this); this.mEngine.disableLocationSensor(this); } @Override public void onOrientationChanged(final OrientationData pOrientationData) { this.mCamera.setRotation(-pOrientationData.getYaw()); } @Override public void onLocationChanged(final Location pLocation) { if(USE_ACTUAL_LOCATION) { this.mUserLocation = pLocation; } this.refreshCitySprites(); } @Override public void onLocationLost() { } @Override public void onLocationProviderDisabled() { } @Override public void onLocationProviderEnabled() { } @Override public void onLocationProviderStatusChanged(final LocationProviderStatus pLocationProviderStatus, final Bundle pBundle) { } // =========================================================== // Methods // =========================================================== private void refreshCitySprites() { final double userLatitudeRad = MathUtils.degToRad((float) this.mUserLocation.getLatitude()); final double userLongitudeRad = MathUtils.degToRad((float) this.mUserLocation.getLongitude()); final int cityCount = this.mCities.size(); double maxDistance = Double.MIN_VALUE; /* Calculate the distances and bearings of the cities to the location of the user. */ for(int i = 0; i < cityCount; i++) { final City city = this.mCities.get(i); final double cityLatitudeRad = MathUtils.degToRad((float) city.getLatitude()); final double cityLongitudeRad = MathUtils.degToRad((float) city.getLongitude()); city.setDistanceToUser(GeoMath.calculateDistance(userLatitudeRad, userLongitudeRad, cityLatitudeRad, cityLongitudeRad)); city.setBearingToUser(GeoMath.calculateBearing(userLatitudeRad, userLongitudeRad, cityLatitudeRad, cityLongitudeRad)); maxDistance = Math.max(maxDistance, city.getDistanceToUser()); } /* Calculate a scaleRatio so that all cities are visible at all times. */ final double scaleRatio = (CityRadarActivity.CAMERA_WIDTH / 2) / maxDistance * 0.93f; for(int i = 0; i < cityCount; i++) { final City city = this.mCities.get(i); final Sprite citySprite = this.mCityToCitySpriteMap.get(city); final Text cityNameText = this.mCityToCityNameTextMap.get(city); final float bearingInRad = MathUtils.degToRad(90 - (float) city.getBearingToUser()); final float x = (float) (CityRadarActivity.CAMERA_WIDTH / 2 + city.getDistanceToUser() * scaleRatio * Math.cos(bearingInRad)); final float y = (float) (CityRadarActivity.CAMERA_HEIGHT / 2 - city.getDistanceToUser() * scaleRatio * Math.sin(bearingInRad)); citySprite.setPosition(x - citySprite.getWidth() / 2, y - citySprite.getHeight() / 2); final float textX = x - cityNameText.getWidth() / 2; final float textY = y + citySprite.getHeight() / 2; cityNameText.setPosition(textX, textY); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== /** * Note: Formulas taken from <a href="http://www.movable-type.co.uk/scripts/latlong.html">here</a>. */ private static class GeoMath { // =========================================================== // Constants // =========================================================== private static final double RADIUS_EARTH_METERS = 6371000; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== /** * @return the distance in meters. */ public static double calculateDistance(final double pLatitude1, final double pLongitude1, final double pLatitude2, final double pLongitude2) { return Math.acos(Math.sin(pLatitude1) * Math.sin(pLatitude2) + Math.cos(pLatitude1) * Math.cos(pLatitude2) * Math.cos(pLongitude2 - pLongitude1)) * RADIUS_EARTH_METERS; } /** * @return the bearing in degrees. */ public static double calculateBearing(final double pLatitude1, final double pLongitude1, final double pLatitude2, final double pLongitude2) { final double y = Math.sin(pLongitude2 - pLongitude1) * Math.cos(pLatitude2); final double x = Math.cos(pLatitude1) * Math.sin(pLatitude2) - Math.sin(pLatitude1) * Math.cos(pLatitude2) * Math.cos(pLongitude2 - pLongitude1); final float bearing = MathUtils.radToDeg((float) Math.atan2(y, x)); return (bearing + 360) % 360; } // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class SpriteRemoveExample extends BaseExample implements IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private Sprite mFaceToRemove; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to safely remove the sprite.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; this.mFaceToRemove = new Sprite(centerX, centerY, this.mFaceTextureRegion); scene.attachChild(this.mFaceToRemove); scene.setOnSceneTouchListener(this); return scene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { /* Removing entities can only be done safely on the UpdateThread. * Doing it while updating/drawing can * cause an exception with a suddenly missing entity. * Alternatively, there is a possibility to run the TouchEvents on the UpdateThread by default, by doing: * engineOptions.getTouchOptions().setRunOnUpdateThread(true); * when creating the Engine in onLoadEngine(); */ this.runOnUpdateThread(new Runnable() { @Override public void run() { /* Now it is save to remove the entity! */ pScene.detachChild(SpriteRemoveExample.this.mFaceToRemove); } }); return false; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake; import java.io.IOException; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.audio.sound.Sound; import org.anddev.andengine.audio.sound.SoundFactory; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl.IOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.DigitalOnScreenControl; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.text.ChangeableText; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.game.snake.adt.Direction; import org.anddev.andengine.examples.game.snake.adt.SnakeSuicideException; import org.anddev.andengine.examples.game.snake.entity.Frog; import org.anddev.andengine.examples.game.snake.entity.Snake; import org.anddev.andengine.examples.game.snake.entity.SnakeHead; import org.anddev.andengine.examples.game.snake.util.constants.SnakeConstants; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.FontFactory; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.ui.activity.BaseGameActivity; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.HorizontalAlign; import org.anddev.andengine.util.MathUtils; import android.graphics.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 02:26:05 - 08.07.2010 */ public class SnakeGameActivity extends BaseGameActivity implements SnakeConstants { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = CELLS_HORIZONTAL * CELL_WIDTH; // 640 private static final int CAMERA_HEIGHT = CELLS_VERTICAL * CELL_HEIGHT; // 480 private static final int LAYER_COUNT = 4; private static final int LAYER_BACKGROUND = 0; private static final int LAYER_FOOD = LAYER_BACKGROUND + 1; private static final int LAYER_SNAKE = LAYER_FOOD + 1; private static final int LAYER_SCORE = LAYER_SNAKE + 1; // =========================================================== // Fields // =========================================================== private Camera mCamera; private DigitalOnScreenControl mDigitalOnScreenControl; private BitmapTextureAtlas mFontTexture; private Font mFont; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mTailPartTextureRegion; private TiledTextureRegion mHeadTextureRegion; private TiledTextureRegion mFrogTextureRegion; private BitmapTextureAtlas mBackgroundTexture; private TextureRegion mBackgroundTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private Scene mScene; private Snake mSnake; private Frog mFrog; private int mScore = 0; private ChangeableText mScoreText; private Sound mGameOverSound; private Sound mMunchSound; protected boolean mGameRunning; private Text mGameOverText; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera).setNeedsSound(true)); } @Override public void onLoadResources() { /* Load the font we are going to use. */ FontFactory.setAssetBasePath("font/"); this.mFontTexture = new BitmapTextureAtlas(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = FontFactory.createFromAsset(this.mFontTexture, this, "Plok.ttf", 32, true, Color.WHITE); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.getFontManager().loadFont(this.mFont); /* Load all the textures this game needs. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mHeadTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "snake_head.png", 0, 0, 3, 1); this.mTailPartTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "snake_tailpart.png", 96, 0); this.mFrogTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "frog.png", 0, 64, 3, 1); this.mBackgroundTexture = new BitmapTextureAtlas(1024, 512, TextureOptions.DEFAULT); this.mBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBackgroundTexture, this, "snake_background.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBackgroundTexture, this.mBitmapTextureAtlas, this.mOnScreenControlTexture); /* Load all the sounds this game needs. */ try { SoundFactory.setAssetBasePath("mfx/"); this.mGameOverSound = SoundFactory.createSoundFromAsset(this.getSoundManager(), this, "game_over.ogg"); this.mMunchSound = SoundFactory.createSoundFromAsset(this.getSoundManager(), this, "munch.ogg"); } catch (final IOException e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); for(int i = 0; i < LAYER_COUNT; i++) { this.mScene.attachChild(new Entity()); } /* No background color needed as we have a fullscreen background sprite. */ this.mScene.setBackgroundEnabled(false); this.mScene.getChild(LAYER_BACKGROUND).attachChild(new Sprite(0, 0, this.mBackgroundTextureRegion)); /* The ScoreText showing how many points the pEntity scored. */ this.mScoreText = new ChangeableText(5, 5, this.mFont, "Score: 0", "Score: XXXX".length()); this.mScoreText.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); this.mScoreText.setAlpha(0.5f); this.mScene.getChild(LAYER_SCORE).attachChild(this.mScoreText); /* The Snake. */ this.mSnake = new Snake(Direction.RIGHT, 0, CELLS_VERTICAL / 2, this.mHeadTextureRegion, this.mTailPartTextureRegion); this.mSnake.getHead().animate(200); /* Snake starts with one tail. */ this.mSnake.grow(); this.mScene.getChild(LAYER_SNAKE).attachChild(this.mSnake); /* A frog to approach and eat. */ this.mFrog = new Frog(0, 0, this.mFrogTextureRegion); this.mFrog.animate(1000); this.setFrogToRandomCell(); this.mScene.getChild(LAYER_FOOD).attachChild(this.mFrog); /* The On-Screen Controls to control the direction of the snake. */ this.mDigitalOnScreenControl = new DigitalOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { if(pValueX == 1) { SnakeGameActivity.this.mSnake.setDirection(Direction.RIGHT); } else if(pValueX == -1) { SnakeGameActivity.this.mSnake.setDirection(Direction.LEFT); } else if(pValueY == 1) { SnakeGameActivity.this.mSnake.setDirection(Direction.DOWN); } else if(pValueY == -1) { SnakeGameActivity.this.mSnake.setDirection(Direction.UP); } } }); /* Make the controls semi-transparent. */ this.mDigitalOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); this.mDigitalOnScreenControl.getControlBase().setAlpha(0.5f); this.mScene.setChildScene(this.mDigitalOnScreenControl); /* Make the Snake move every 0.5 seconds. */ this.mScene.registerUpdateHandler(new TimerHandler(0.5f, true, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { if(SnakeGameActivity.this.mGameRunning) { try { SnakeGameActivity.this.mSnake.move(); } catch (final SnakeSuicideException e) { SnakeGameActivity.this.onGameOver(); } SnakeGameActivity.this.handleNewSnakePosition(); } } })); /* The title-text. */ final Text titleText = new Text(0, 0, this.mFont, "Snake\non a Phone!", HorizontalAlign.CENTER); titleText.setPosition((CAMERA_WIDTH - titleText.getWidth()) * 0.5f, (CAMERA_HEIGHT - titleText.getHeight()) * 0.5f); titleText.setScale(0.0f); titleText.registerEntityModifier(new ScaleModifier(2, 0.0f, 1.0f)); this.mScene.getChild(LAYER_SCORE).attachChild(titleText); /* The handler that removes the title-text and starts the game. */ this.mScene.registerUpdateHandler(new TimerHandler(3.0f, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { SnakeGameActivity.this.mScene.unregisterUpdateHandler(pTimerHandler); SnakeGameActivity.this.mScene.getChild(LAYER_SCORE).detachChild(titleText); SnakeGameActivity.this.mGameRunning = true; } })); /* The game-over text. */ this.mGameOverText = new Text(0, 0, this.mFont, "Game\nOver", HorizontalAlign.CENTER); this.mGameOverText.setPosition((CAMERA_WIDTH - this.mGameOverText.getWidth()) * 0.5f, (CAMERA_HEIGHT - this.mGameOverText.getHeight()) * 0.5f); this.mGameOverText.registerEntityModifier(new ScaleModifier(3, 0.1f, 2.0f)); this.mGameOverText.registerEntityModifier(new RotationModifier(3, 0, 720)); return this.mScene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void setFrogToRandomCell() { this.mFrog.setCell(MathUtils.random(1, CELLS_HORIZONTAL - 2), MathUtils.random(1, CELLS_VERTICAL - 2)); } private void handleNewSnakePosition() { final SnakeHead snakeHead = this.mSnake.getHead(); if(snakeHead.getCellX() < 0 || snakeHead.getCellX() >= CELLS_HORIZONTAL || snakeHead.getCellY() < 0 || snakeHead.getCellY() >= CELLS_VERTICAL) { this.onGameOver(); } else if(snakeHead.isInSameCell(this.mFrog)) { this.mScore += 50; this.mScoreText.setText("Score: " + this.mScore); this.mSnake.grow(); this.mMunchSound.play(); this.setFrogToRandomCell(); } } private void onGameOver() { this.mGameOverSound.play(); this.mScene.getChild(LAYER_SCORE).attachChild(this.mGameOverText); this.mGameRunning = false; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.entity; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.examples.game.snake.util.constants.SnakeConstants; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:13:44 - 09.07.2010 */ public abstract class AnimatedCellEntity extends AnimatedSprite implements SnakeConstants, ICellEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected int mCellX; protected int mCellY; // =========================================================== // Constructors // =========================================================== public AnimatedCellEntity(final int pCellX, final int pCellY, final int pWidth, final int pHeight, final TiledTextureRegion pTiledTextureRegion) { super(pCellX * CELL_WIDTH, pCellY * CELL_HEIGHT, pWidth, pHeight, pTiledTextureRegion); this.mCellX = pCellX; this.mCellY = pCellY; } // =========================================================== // Getter & Setter // =========================================================== public int getCellX() { return this.mCellX; } public int getCellY() { return this.mCellY; } public void setCell(final ICellEntity pCellEntity) { this.setCell(pCellEntity.getCellX(), pCellEntity.getCellY()); } public void setCell(final int pCellX, final int pCellY) { this.mCellX = pCellX; this.mCellY = pCellY; this.setPosition(this.mCellX * CELL_WIDTH, this.mCellY * CELL_HEIGHT); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== @Override public boolean isInSameCell(final ICellEntity pCellEntity) { return this.mCellX == pCellEntity.getCellX() && this.mCellY == pCellEntity.getCellY(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.entity; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:08:58 - 11.07.2010 */ public class Frog extends AnimatedCellEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public Frog(final int pCellX, final int pCellY, final TiledTextureRegion pTiledTextureRegion) { super(pCellX, pCellY, CELL_WIDTH, CELL_HEIGHT, pTiledTextureRegion); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.entity; import org.anddev.andengine.examples.game.snake.adt.Direction; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:44:59 - 09.07.2010 */ public class SnakeHead extends AnimatedCellEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public SnakeHead(final int pCellX, final int pCellY, final TiledTextureRegion pTiledTextureRegion) { super(pCellX, pCellY, CELL_WIDTH, 2 * CELL_HEIGHT, pTiledTextureRegion); this.setRotationCenterY(CELL_HEIGHT / 2); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void setRotation(final Direction pDirection) { switch(pDirection) { case UP: this.setRotation(180); break; case DOWN: this.setRotation(0); break; case LEFT: this.setRotation(90); break; case RIGHT: this.setRotation(270); break; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.entity; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:44:59 - 09.07.2010 */ public class SnakeTailPart extends CellEntity implements Cloneable { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public SnakeTailPart(final SnakeHead pSnakeHead, final TextureRegion pTextureRegion) { this(pSnakeHead.mCellX, pSnakeHead.mCellY, pTextureRegion); } public SnakeTailPart(final int pCellX, final int pCellY, final TextureRegion pTextureRegion) { super(pCellX, pCellY, CELL_WIDTH, CELL_HEIGHT, pTextureRegion); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected SnakeTailPart deepCopy() { return new SnakeTailPart(this.mCellX, this.mCellY, this.getTextureRegion()); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.entity; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:39:05 - 11.07.2010 */ public interface ICellEntity { // =========================================================== // Constants // =========================================================== public abstract int getCellX(); public abstract int getCellY(); public abstract void setCell(final ICellEntity pCellEntity); public abstract void setCell(final int pCellX, final int pCellY); public abstract boolean isInSameCell(final ICellEntity pCellEntity); }
Java
package org.anddev.andengine.examples.game.snake.entity; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.examples.game.snake.util.constants.SnakeConstants; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:13:44 - 09.07.2010 */ public abstract class CellEntity extends Sprite implements SnakeConstants, ICellEntity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected int mCellX; protected int mCellY; // =========================================================== // Constructors // =========================================================== public CellEntity(final int pCellX, final int pCellY, final int pWidth, final int pHeight, final TextureRegion pTextureRegion) { super(pCellX * CELL_WIDTH, pCellY * CELL_HEIGHT, pWidth, pHeight, pTextureRegion); this.mCellX = pCellX; this.mCellY = pCellY; } // =========================================================== // Getter & Setter // =========================================================== public int getCellX() { return this.mCellX; } public int getCellY() { return this.mCellY; } public void setCell(final ICellEntity pCellEntity) { this.setCell(pCellEntity.getCellX(), pCellEntity.getCellY()); } public void setCell(final int pCellX, final int pCellY) { this.mCellX = pCellX; this.mCellY = pCellY; this.setPosition(this.mCellX * CELL_WIDTH, this.mCellY * CELL_HEIGHT); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== @Override public boolean isInSameCell(final ICellEntity pCellEntity) { return this.mCellX == pCellEntity.getCellX() && this.mCellY == pCellEntity.getCellY(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.entity; import java.util.LinkedList; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.examples.game.snake.adt.Direction; import org.anddev.andengine.examples.game.snake.adt.SnakeSuicideException; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:11:44 - 09.07.2010 */ public class Snake extends Entity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final SnakeHead mHead; private final LinkedList<SnakeTailPart> mTail = new LinkedList<SnakeTailPart>(); private Direction mDirection; private boolean mGrow; private final TextureRegion mTailPartTextureRegion; private Direction mLastMoveDirection; // =========================================================== // Constructors // =========================================================== public Snake(final Direction pInitialDirection, final int pCellX, final int pCellY, final TiledTextureRegion pHeadTextureRegion, final TextureRegion pTailPartTextureRegion) { super(0, 0); this.mTailPartTextureRegion = pTailPartTextureRegion; this.mHead = new SnakeHead(pCellX, pCellY, pHeadTextureRegion); this.attachChild(this.mHead); this.setDirection(pInitialDirection); } // =========================================================== // Getter & Setter // =========================================================== public Direction getDirection() { return this.mDirection; } public void setDirection(final Direction pDirection) { if(this.mLastMoveDirection != Direction.opposite(pDirection)) { this.mDirection = pDirection; this.mHead.setRotation(pDirection); } } public int getTailLength() { return this.mTail.size(); } public SnakeHead getHead() { return this.mHead; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void grow() { this.mGrow = true; } public int getNextX() { return Direction.addToX(this.mDirection, this.mHead.getCellX()); } public int getNextY() { return Direction.addToY(this.mDirection, this.mHead.getCellY()); } public void move() throws SnakeSuicideException { this.mLastMoveDirection = this.mDirection; if(this.mGrow) { this.mGrow = false; /* If the snake should grow, * simply add a new part in the front of the tail, * where the head currently is. */ final SnakeTailPart newTailPart = new SnakeTailPart(this.mHead, this.mTailPartTextureRegion); this.attachChild(newTailPart); this.mTail.addFirst(newTailPart); } else { if(this.mTail.isEmpty() == false) { /* First move the end of the tail to where the head currently is. */ final SnakeTailPart tailEnd = this.mTail.removeLast(); tailEnd.setCell(this.mHead); this.mTail.addFirst(tailEnd); } } /* The move the head into the direction of the snake. */ this.mHead.setCell(this.getNextX(), this.getNextY()); /* Check if head collides with tail. */ for(int i = this.mTail.size() - 1; i >= 0; i--) { if(this.mHead.isInSameCell(this.mTail.get(i))) { throw new SnakeSuicideException(); } } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.adt; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 02:29:05 - 08.07.2010 */ public enum Direction { // =========================================================== // Elements // =========================================================== UP, DOWN, LEFT, RIGHT; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static int addToX(final Direction pDirection, final int pX) { switch(pDirection) { case UP: case DOWN: return pX; case LEFT: return pX - 1; case RIGHT: return pX + 1; default: throw new IllegalArgumentException(); } } public static int addToY(final Direction pDirection, final int pY) { switch(pDirection) { case LEFT: case RIGHT: return pY; case UP: return pY - 1; case DOWN: return pY + 1; default: throw new IllegalArgumentException(); } } public static Direction opposite(final Direction pDirection) { switch(pDirection) { case UP: return DOWN; case DOWN: return UP; case LEFT: return RIGHT; case RIGHT: return LEFT; default: return null; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.adt; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:29:42 - 11.07.2010 */ public class SnakeSuicideException extends Exception { // =========================================================== // Constants // =========================================================== private static final long serialVersionUID = -4008723747610431268L; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.snake.util.constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 17:42:10 - 09.07.2010 */ public interface SnakeConstants { // =========================================================== // Final Fields // =========================================================== public static final int CELLS_HORIZONTAL = 16; public static final int CELLS_VERTICAL = 12; public static final int CELL_WIDTH = 32; public static final int CELL_HEIGHT = CELL_WIDTH; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong; import java.io.IOException; import java.util.ArrayList; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.examples.adt.messages.MessageConstants; import org.anddev.andengine.examples.adt.messages.client.ClientMessageFlags; import org.anddev.andengine.examples.adt.messages.client.ConnectionCloseClientMessage; import org.anddev.andengine.examples.adt.messages.client.ConnectionEstablishClientMessage; import org.anddev.andengine.examples.adt.messages.client.ConnectionPingClientMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionEstablishedServerMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionPongServerMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionRejectedProtocolMissmatchServerMessage; import org.anddev.andengine.examples.adt.messages.server.ServerMessageFlags; import org.anddev.andengine.examples.game.pong.adt.PaddleUserData; import org.anddev.andengine.examples.game.pong.adt.Score; import org.anddev.andengine.examples.game.pong.adt.messages.client.MovePaddleClientMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.SetPaddleIDServerMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.UpdateBallServerMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.UpdatePaddleServerMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.UpdateScoreServerMessage; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.IMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.IClientMessage; import org.anddev.andengine.extension.multiplayer.protocol.server.IClientMessageHandler; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer.ISocketServerListener.DefaultSocketServerListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.ClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector.ISocketConnectionClientConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.shared.SocketConnection; import org.anddev.andengine.extension.multiplayer.protocol.util.MessagePool; import org.anddev.andengine.extension.physics.box2d.FixedStepPhysicsWorld; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.MathUtils; import android.util.SparseArray; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.Manifold; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:00:09 - 28.02.2011 */ public class PongServer extends SocketServer<SocketConnectionClientConnector> implements IUpdateHandler, PongConstants, ContactListener, ClientMessageFlags, ServerMessageFlags { // =========================================================== // Constants // =========================================================== private static final FixtureDef PADDLE_FIXTUREDEF = PhysicsFactory.createFixtureDef(1, 1, 0); private static final FixtureDef BALL_FIXTUREDEF = PhysicsFactory.createFixtureDef(1, 1, 0); private static final FixtureDef WALL_FIXTUREDEF = PhysicsFactory.createFixtureDef(1, 1, 0); // =========================================================== // Fields // =========================================================== private final PhysicsWorld mPhysicsWorld; private final Body mBallBody; private final SparseArray<Body> mPaddleBodies = new SparseArray<Body>(); private boolean mResetBall = true; private final SparseArray<Score> mPaddleScores = new SparseArray<Score>(); private final MessagePool<IMessage> mMessagePool = new MessagePool<IMessage>(); private final ArrayList<UpdatePaddleServerMessage> mUpdatePaddleServerMessages = new ArrayList<UpdatePaddleServerMessage>(); // =========================================================== // Constructors // =========================================================== public PongServer(final ISocketConnectionClientConnectorListener pSocketConnectionClientConnectorListener) { super(SERVER_PORT, pSocketConnectionClientConnectorListener, new DefaultSocketServerListener<SocketConnectionClientConnector>()); this.initMessagePool(); this.mPaddleScores.put(PADDLE_LEFT.getOwnerID(), new Score()); this.mPaddleScores.put(PADDLE_RIGHT.getOwnerID(), new Score()); this.mPhysicsWorld = new FixedStepPhysicsWorld(FPS, 2, new Vector2(0, 0), false, 8, 8); this.mPhysicsWorld.setContactListener(this); /* Ball */ this.mBallBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, new Rectangle(-BALL_WIDTH_HALF, -BALL_HEIGHT_HALF, BALL_WIDTH, BALL_HEIGHT), BodyType.DynamicBody, BALL_FIXTUREDEF); this.mBallBody.setBullet(true); /* Paddles */ final Body paddleBodyLeft = PhysicsFactory.createBoxBody(this.mPhysicsWorld, new Rectangle(-GAME_WIDTH_HALF, -PADDLE_HEIGHT_HALF, PADDLE_WIDTH, PADDLE_HEIGHT), BodyType.KinematicBody, PADDLE_FIXTUREDEF); paddleBodyLeft.setUserData(PADDLE_LEFT); this.mPaddleBodies.put(PADDLE_LEFT.getOwnerID(), paddleBodyLeft); final Body paddleBodyRight = PhysicsFactory.createBoxBody(this.mPhysicsWorld, new Rectangle(GAME_WIDTH_HALF - PADDLE_WIDTH, -PADDLE_HEIGHT_HALF, PADDLE_WIDTH, PADDLE_HEIGHT), BodyType.KinematicBody, PADDLE_FIXTUREDEF); paddleBodyRight.setUserData(PADDLE_RIGHT); this.mPaddleBodies.put(PADDLE_RIGHT.getOwnerID(), paddleBodyRight); this.initWalls(); } private void initMessagePool() { this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED, UpdateScoreServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_CONNECTION_PONG, UpdateScoreServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_CONNECTION_CLOSE, UpdateScoreServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_UPDATE_SCORE, UpdateScoreServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_UPDATE_BALL, UpdateBallServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_UPDATE_PADDLE, UpdatePaddleServerMessage.class); } private void initWalls() { final Line left = new Line(-GAME_WIDTH_HALF, -GAME_HEIGHT_HALF, -GAME_WIDTH_HALF, GAME_HEIGHT_HALF); final Line right = new Line(GAME_WIDTH_HALF, -GAME_HEIGHT_HALF, GAME_WIDTH_HALF, GAME_HEIGHT_HALF); WALL_FIXTUREDEF.isSensor = true; final Body leftBody = PhysicsFactory.createLineBody(this.mPhysicsWorld, left, WALL_FIXTUREDEF); leftBody.setUserData(this.mPaddleBodies.get(PADDLE_LEFT.getOwnerID())); final Body rightBody = PhysicsFactory.createLineBody(this.mPhysicsWorld, right, WALL_FIXTUREDEF); rightBody.setUserData(this.mPaddleBodies.get(PADDLE_RIGHT.getOwnerID())); WALL_FIXTUREDEF.isSensor = false; final Line top = new Line(-GAME_WIDTH_HALF, -GAME_HEIGHT_HALF, GAME_WIDTH_HALF, -GAME_HEIGHT_HALF); final Line bottom = new Line(-GAME_WIDTH_HALF, GAME_HEIGHT_HALF, GAME_WIDTH_HALF, GAME_HEIGHT_HALF); PhysicsFactory.createLineBody(this.mPhysicsWorld, top, WALL_FIXTUREDEF); PhysicsFactory.createLineBody(this.mPhysicsWorld, bottom, WALL_FIXTUREDEF); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void preSolve(final Contact pContact, final Manifold pManifold) { } @Override public void postSolve(final Contact pContact, final ContactImpulse pContactImpulse) { } @Override public void beginContact(final Contact pContact) { final Fixture fixtureA = pContact.getFixtureA(); final Body bodyA = fixtureA.getBody(); final Object userDataA = bodyA.getUserData(); final Fixture fixtureB = pContact.getFixtureB(); final Body bodyB = fixtureB.getBody(); final Object userDataB = bodyB.getUserData(); final boolean isScoreSensorA = userDataA != null && userDataA instanceof Body; final boolean isScoreSensorB = userDataB != null && userDataB instanceof Body; if(isScoreSensorA || isScoreSensorB) { this.mResetBall = true; final PaddleUserData paddleUserData = (isScoreSensorA) ? (PaddleUserData)(((Body)userDataA).getUserData()) : (PaddleUserData)(((Body)userDataA).getUserData()); final int opponentID = paddleUserData.getOpponentID(); final Score opponentPaddleScore = this.mPaddleScores.get(opponentID); opponentPaddleScore.increase(); final UpdateScoreServerMessage updateScoreServerMessage = (UpdateScoreServerMessage)this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_UPDATE_SCORE); updateScoreServerMessage.set(opponentID, opponentPaddleScore.getScore()); final ArrayList<SocketConnectionClientConnector> clientConnectors = this.mClientConnectors; for(int i = 0; i < clientConnectors.size(); i++) { try { final ClientConnector<SocketConnection> clientConnector = clientConnectors.get(i); clientConnector.sendServerMessage(updateScoreServerMessage); } catch (final IOException e) { Debug.e(e); } } this.mMessagePool.recycleMessage(updateScoreServerMessage); } } @Override public void endContact(final Contact pContact) { } @Override public void onUpdate(final float pSecondsElapsed) { if(this.mResetBall) { this.mResetBall = false; final Vector2 vector2 = Vector2Pool.obtain(0, 0); this.mBallBody.setTransform(vector2, 0); vector2.set(MathUtils.randomSign() * MathUtils.random(3, 4), MathUtils.randomSign() * MathUtils.random(3, 4)); this.mBallBody.setLinearVelocity(vector2); Vector2Pool.recycle(vector2); } this.mPhysicsWorld.onUpdate(pSecondsElapsed); /* Prepare UpdateBallServerMessage. */ final Vector2 ballPosition = this.mBallBody.getPosition(); final float ballX = ballPosition.x * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - BALL_WIDTH_HALF; final float ballY = ballPosition.y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - BALL_HEIGHT_HALF; final UpdateBallServerMessage updateBallServerMessage = (UpdateBallServerMessage)this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_UPDATE_BALL); updateBallServerMessage.set(ballX, ballY); final ArrayList<UpdatePaddleServerMessage> updatePaddleServerMessages = this.mUpdatePaddleServerMessages; /* Prepare UpdatePaddleServerMessages. */ final SparseArray<Body> paddleBodies = this.mPaddleBodies; for(int j = 0; j < paddleBodies.size(); j++) { final int paddleID = paddleBodies.keyAt(j); final Body paddleBody = paddleBodies.get(paddleID); final Vector2 paddlePosition = paddleBody.getPosition(); final float paddleX = paddlePosition.x * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - PADDLE_WIDTH_HALF; final float paddleY = paddlePosition.y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - PADDLE_HEIGHT_HALF; final UpdatePaddleServerMessage updatePaddleServerMessage = (UpdatePaddleServerMessage)this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_UPDATE_PADDLE); updatePaddleServerMessage.set(paddleID, paddleX, paddleY); updatePaddleServerMessages.add(updatePaddleServerMessage); } try { /* Update Ball. */ this.sendBroadcastServerMessage(updateBallServerMessage); /* Update Paddles. */ for(int j = 0; j < updatePaddleServerMessages.size(); j++) { this.sendBroadcastServerMessage(updatePaddleServerMessages.get(j)); } this.sendBroadcastServerMessage(updateBallServerMessage); } catch (final IOException e) { Debug.e(e); } /* Recycle messages. */ this.mMessagePool.recycleMessage(updateBallServerMessage); this.mMessagePool.recycleMessages(updatePaddleServerMessages); updatePaddleServerMessages.clear(); } @Override public void reset() { /* Nothing. */ } @Override protected SocketConnectionClientConnector newClientConnector(final SocketConnection pSocketConnection) throws IOException { final SocketConnectionClientConnector clientConnector = new SocketConnectionClientConnector(pSocketConnection); clientConnector.registerClientMessage(FLAG_MESSAGE_CLIENT_MOVE_PADDLE, MovePaddleClientMessage.class, new IClientMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ClientConnector<SocketConnection> pClientConnector, final IClientMessage pClientMessage) throws IOException { final MovePaddleClientMessage movePaddleClientMessage = (MovePaddleClientMessage)pClientMessage; final Body paddleBody = PongServer.this.mPaddleBodies.get(movePaddleClientMessage.mPaddleID); final Vector2 paddlePosition = paddleBody.getTransform().getPosition(); final float paddleY = MathUtils.bringToBounds(-GAME_HEIGHT_HALF + PADDLE_HEIGHT_HALF, GAME_HEIGHT_HALF - PADDLE_HEIGHT_HALF, movePaddleClientMessage.mY); paddlePosition.set(paddlePosition.x, paddleY / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT); paddleBody.setTransform(paddlePosition, 0); } }); clientConnector.registerClientMessage(FLAG_MESSAGE_CLIENT_CONNECTION_CLOSE, ConnectionCloseClientMessage.class, new IClientMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ClientConnector<SocketConnection> pClientConnector, final IClientMessage pClientMessage) throws IOException { pClientConnector.terminate(); } }); clientConnector.registerClientMessage(FLAG_MESSAGE_CLIENT_CONNECTION_ESTABLISH, ConnectionEstablishClientMessage.class, new IClientMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ClientConnector<SocketConnection> pClientConnector, final IClientMessage pClientMessage) throws IOException { final ConnectionEstablishClientMessage connectionEstablishClientMessage = (ConnectionEstablishClientMessage) pClientMessage; if(connectionEstablishClientMessage.getProtocolVersion() == MessageConstants.PROTOCOL_VERSION) { final ConnectionEstablishedServerMessage connectionEstablishedServerMessage = (ConnectionEstablishedServerMessage) PongServer.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED); try { pClientConnector.sendServerMessage(connectionEstablishedServerMessage); } catch (IOException e) { Debug.e(e); } PongServer.this.mMessagePool.recycleMessage(connectionEstablishedServerMessage); } else { final ConnectionRejectedProtocolMissmatchServerMessage connectionRejectedProtocolMissmatchServerMessage = (ConnectionRejectedProtocolMissmatchServerMessage) PongServer.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_CONNECTION_REJECTED_PROTOCOL_MISSMATCH); connectionRejectedProtocolMissmatchServerMessage.setProtocolVersion(MessageConstants.PROTOCOL_VERSION); try { pClientConnector.sendServerMessage(connectionRejectedProtocolMissmatchServerMessage); } catch (IOException e) { Debug.e(e); } PongServer.this.mMessagePool.recycleMessage(connectionRejectedProtocolMissmatchServerMessage); } } }); clientConnector.registerClientMessage(FLAG_MESSAGE_CLIENT_CONNECTION_PING, ConnectionPingClientMessage.class, new IClientMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ClientConnector<SocketConnection> pClientConnector, final IClientMessage pClientMessage) throws IOException { final ConnectionPongServerMessage connectionPongServerMessage = (ConnectionPongServerMessage) PongServer.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_CONNECTION_PONG); try { pClientConnector.sendServerMessage(connectionPongServerMessage); } catch (IOException e) { Debug.e(e); } PongServer.this.mMessagePool.recycleMessage(connectionPongServerMessage); } }); clientConnector.sendServerMessage(new SetPaddleIDServerMessage(this.mClientConnectors.size())); // TODO should not be size(), as it only works properly for first two connections! return clientConnector; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.ClientMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:52:27 - 28.02.2011 */ public class MovePaddleClientMessage extends ClientMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int mPaddleID; public float mY; // =========================================================== // Constructors // =========================================================== public MovePaddleClientMessage() { } public MovePaddleClientMessage(final int pID, final float pY) { this.mPaddleID = pID; this.mY = pY; } // =========================================================== // Getter & Setter // =========================================================== public void setPaddleID(final int pPaddleID, final float pY) { this.mPaddleID = pPaddleID; this.mY = pY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_CLIENT_MOVE_PADDLE; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mPaddleID = pDataInputStream.readInt(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mPaddleID); pDataOutputStream.writeFloat(this.mY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:48:32 - 28.02.2011 */ public class SetPaddleIDServerMessage extends ServerMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int mPaddleID; // =========================================================== // Constructors // =========================================================== public SetPaddleIDServerMessage() { } public SetPaddleIDServerMessage(final int pPaddleID) { this.mPaddleID = pPaddleID; } // =========================================================== // Getter & Setter // =========================================================== public void set(final int pPaddleID) { this.mPaddleID = pPaddleID; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_SET_PADDLEID; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mPaddleID = pDataInputStream.readInt(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mPaddleID); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:48:32 - 28.02.2011 */ public class UpdatePaddleServerMessage extends ServerMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int mPaddleID; public float mX; public float mY; // =========================================================== // Constructors // =========================================================== public UpdatePaddleServerMessage() { } public UpdatePaddleServerMessage(final int pPaddleID, final float pX, final float pY) { this.mPaddleID = pPaddleID; this.mX = pX; this.mY = pY; } // =========================================================== // Getter & Setter // =========================================================== public void set(final int pPaddleID, final float pX,final float pY) { this.mPaddleID = pPaddleID; this.mX = pX; this.mY = pY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_UPDATE_PADDLE; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mPaddleID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mPaddleID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:48:32 - 28.02.2011 */ public class UpdateBallServerMessage extends ServerMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public float mX; public float mY; // =========================================================== // Constructors // =========================================================== public UpdateBallServerMessage() { } public UpdateBallServerMessage(final float pX, final float pY) { this.mX = pX; this.mY = pY; } // =========================================================== // Getter & Setter // =========================================================== public void set(final float pX,final float pY) { this.mX = pX; this.mY = pY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_UPDATE_BALL; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 02:02:12 - 01.03.2011 */ public class UpdateScoreServerMessage extends ServerMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int mPaddleID; public int mScore; // =========================================================== // Constructors // =========================================================== public UpdateScoreServerMessage() { } public UpdateScoreServerMessage(final int pPaddleID, final int pScore) { this.mPaddleID = pPaddleID; this.mScore = pScore; } // =========================================================== // Getter & Setter // =========================================================== public void set(final int pPaddleID, final int pScore) { this.mPaddleID = pPaddleID; this.mScore = pScore; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_UPDATE_SCORE; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mPaddleID = pDataInputStream.readInt(); this.mScore = pDataInputStream.readInt(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mPaddleID); pDataOutputStream.writeInt(this.mScore); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:11:58 - 01.03.2011 */ public class Score { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private int mScore = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== public int getScore() { return this.mScore; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void increase() { this.mScore++; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:14:17 - 01.03.2011 */ public class PaddleUserData { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mOwnerID; private final int mOpponentID; // =========================================================== // Constructors // =========================================================== public PaddleUserData(final int pOwnerID, final int pOpponentID) { this.mOwnerID = pOwnerID; this.mOpponentID = pOpponentID; } // =========================================================== // Getter & Setter // =========================================================== public int getOwnerID() { return this.mOwnerID; } public int getOpponentID() { return this.mOpponentID; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.LimitedFPSEngine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.text.ChangeableText; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.messages.MessageConstants; import org.anddev.andengine.examples.adt.messages.client.ConnectionPingClientMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionCloseServerMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionEstablishedServerMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionPongServerMessage; import org.anddev.andengine.examples.adt.messages.server.ConnectionRejectedProtocolMissmatchServerMessage; import org.anddev.andengine.examples.adt.messages.server.ServerMessageFlags; import org.anddev.andengine.examples.game.pong.adt.messages.client.MovePaddleClientMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.SetPaddleIDServerMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.UpdateBallServerMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.UpdatePaddleServerMessage; import org.anddev.andengine.examples.game.pong.adt.messages.server.UpdateScoreServerMessage; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.IServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.client.IServerMessageHandler; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.ServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.SocketConnectionServerConnector.ISocketConnectionServerConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.ClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector.ISocketConnectionClientConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.shared.SocketConnection; import org.anddev.andengine.extension.multiplayer.protocol.util.WifiUtils; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.FontFactory; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.ui.activity.BaseGameActivity; import org.anddev.andengine.util.Debug; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.graphics.Color; import android.util.SparseArray; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 19:36:45 - 28.02.2011 */ public class PongGameActivity extends BaseGameActivity implements PongConstants, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final String LOCALHOST_IP = "127.0.0.1"; private static final int CAMERA_WIDTH = GAME_WIDTH; private static final int CAMERA_HEIGHT = GAME_HEIGHT; private static final int DIALOG_CHOOSE_SERVER_OR_CLIENT_ID = 0; private static final int DIALOG_ENTER_SERVER_IP_ID = DIALOG_CHOOSE_SERVER_OR_CLIENT_ID + 1; private static final int DIALOG_SHOW_SERVER_IP_ID = DIALOG_ENTER_SERVER_IP_ID + 1; private static final int PADDLEID_NOT_SET = -1; private static final int MENU_PING = Menu.FIRST; // =========================================================== // Fields // =========================================================== private Camera mCamera; private String mServerIP = LOCALHOST_IP; private int mPaddleID = PADDLEID_NOT_SET; private PongServer mServer; private PongServerConnector mServerConnector; private Rectangle mBall; private final SparseArray<Rectangle> mPaddleMap = new SparseArray<Rectangle>(); private final SparseArray<ChangeableText> mScoreChangeableTextMap = new SparseArray<ChangeableText>(); private BitmapTextureAtlas mScoreFontTexture; private Font mScoreFont; private float mPaddleCenterY; // =========================================================== // Constructors // =========================================================== @Override public Engine onLoadEngine() { this.showDialog(DIALOG_CHOOSE_SERVER_OR_CLIENT_ID); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); this.mCamera.setCenter(0,0); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new LimitedFPSEngine(engineOptions, FPS); } @Override public void onLoadResources() { this.mScoreFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); FontFactory.setAssetBasePath("font/"); this.mScoreFont = FontFactory.createFromAsset(this.mScoreFontTexture, this, "LCD.ttf", 32, true, Color.WHITE); this.mEngine.getTextureManager().loadTexture(this.mScoreFontTexture); this.getFontManager().loadFont(this.mScoreFont); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); /* Ball */ this.mBall = new Rectangle(0, 0, BALL_WIDTH, BALL_HEIGHT); scene.attachChild(this.mBall); /* Walls */ scene.attachChild(new Line(-GAME_WIDTH_HALF + 1, -GAME_HEIGHT_HALF, -GAME_WIDTH_HALF + 1, GAME_HEIGHT_HALF)); // Left scene.attachChild(new Line(GAME_WIDTH_HALF, -GAME_HEIGHT_HALF, GAME_WIDTH_HALF, GAME_HEIGHT_HALF)); // Right scene.attachChild(new Line(-GAME_WIDTH_HALF, -GAME_HEIGHT_HALF + 1, GAME_WIDTH_HALF , -GAME_HEIGHT_HALF + 1)); // Top scene.attachChild(new Line(-GAME_WIDTH_HALF, GAME_HEIGHT_HALF, GAME_WIDTH_HALF, GAME_HEIGHT_HALF)); // Bottom scene.attachChild(new Line(0, -GAME_HEIGHT_HALF, 0, GAME_HEIGHT_HALF)); // Middle /* Paddles */ final Rectangle paddleLeft = new Rectangle(0, 0, PADDLE_WIDTH, PADDLE_HEIGHT); final Rectangle paddleRight = new Rectangle(0, 0, PADDLE_WIDTH, PADDLE_HEIGHT); this.mPaddleMap.put(PADDLE_LEFT.getOwnerID(), paddleLeft); this.mPaddleMap.put(PADDLE_RIGHT.getOwnerID(), paddleRight); scene.attachChild(paddleLeft); scene.attachChild(paddleRight); /* Scores */ final ChangeableText scoreLeft = new ChangeableText(0, -GAME_HEIGHT_HALF + SCORE_PADDING, this.mScoreFont, "0", 2); scoreLeft.setPosition(-scoreLeft.getWidth() - SCORE_PADDING, scoreLeft.getY()); final ChangeableText scoreRight = new ChangeableText(SCORE_PADDING, -GAME_HEIGHT_HALF + SCORE_PADDING, this.mScoreFont, "0", 2); this.mScoreChangeableTextMap.put(PADDLE_LEFT.getOwnerID(), scoreLeft); this.mScoreChangeableTextMap.put(PADDLE_RIGHT.getOwnerID(), scoreRight); scene.attachChild(scoreLeft); scene.attachChild(scoreRight); scene.setOnSceneTouchListener(this); scene.registerUpdateHandler(new IUpdateHandler() { @Override public void onUpdate(final float pSecondsElapsed) { if(PongGameActivity.this.mPaddleID != PADDLEID_NOT_SET) { try { PongGameActivity.this.mServerConnector.sendClientMessage(new MovePaddleClientMessage(PongGameActivity.this.mPaddleID, PongGameActivity.this.mPaddleCenterY)); } catch (final IOException e) { Debug.e(e); } } } @Override public void reset() {} }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public boolean onCreateOptionsMenu(final Menu pMenu) { pMenu.add(Menu.NONE, MENU_PING, Menu.NONE, "Ping Server"); return super.onCreateOptionsMenu(pMenu); } @Override public boolean onMenuItemSelected(final int pFeatureId, final MenuItem pItem) { switch(pItem.getItemId()) { case MENU_PING: try { final ConnectionPingClientMessage connectionPingClientMessage = new ConnectionPingClientMessage(); // TODO Pooling connectionPingClientMessage.setTimestamp(System.currentTimeMillis()); this.mServerConnector.sendClientMessage(connectionPingClientMessage); } catch (final IOException e) { Debug.e(e); } return true; default: return super.onMenuItemSelected(pFeatureId, pItem); } } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_SHOW_SERVER_IP_ID: try { return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Your Server-IP ...") .setCancelable(false) .setMessage("The IP of your Server is:\n" + WifiUtils.getWifiIPv4Address(this)) .setPositiveButton(android.R.string.ok, null) .create(); } catch (final UnknownHostException e) { return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Your Server-IP ...") .setCancelable(false) .setMessage("Error retrieving IP of your Server: " + e) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { PongGameActivity.this.finish(); } }) .create(); } case DIALOG_ENTER_SERVER_IP_ID: final EditText ipEditText = new EditText(this); return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Enter Server-IP ...") .setCancelable(false) .setView(ipEditText) .setPositiveButton("Connect", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { PongGameActivity.this.mServerIP = ipEditText.getText().toString(); PongGameActivity.this.initClient(); } }) .setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { PongGameActivity.this.finish(); } }) .create(); case DIALOG_CHOOSE_SERVER_OR_CLIENT_ID: return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Be Server or Client ...") .setCancelable(false) .setPositiveButton("Client", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { PongGameActivity.this.showDialog(DIALOG_ENTER_SERVER_IP_ID); } }) .setNeutralButton("Server", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { PongGameActivity.this.initServerAndClient(); PongGameActivity.this.showDialog(DIALOG_SHOW_SERVER_IP_ID); } }) .create(); default: return super.onCreateDialog(pID); } } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { this.mPaddleCenterY = pSceneTouchEvent.getY(); return true; } @Override protected void onDestroy() { if(this.mServer != null) { try { this.mServer.sendBroadcastServerMessage(new ConnectionCloseServerMessage()); } catch (final IOException e) { Debug.e(e); } this.mServer.terminate(); } if(this.mServerConnector != null) { this.mServerConnector.terminate(); } super.onDestroy(); } @Override public boolean onKeyUp(final int pKeyCode, final KeyEvent pEvent) { switch(pKeyCode) { case KeyEvent.KEYCODE_BACK: this.finish(); return true; } return super.onKeyUp(pKeyCode, pEvent); } // =========================================================== // Methods // =========================================================== public void updateScore(final int pPaddleID, final int pPoints) { final ChangeableText scoreChangeableText = this.mScoreChangeableTextMap.get(pPaddleID); scoreChangeableText.setText(String.valueOf(pPoints)); /* Adjust position of left Score, so that it doesn't overlap the middle line. */ if(pPaddleID == PADDLE_LEFT.getOwnerID()) { scoreChangeableText.setPosition(-scoreChangeableText.getWidth() - SCORE_PADDING, scoreChangeableText.getY()); } } public void setPaddleID(final int pPaddleID) { this.mPaddleID = pPaddleID; } public void updatePaddle(final int pPaddleID, final float pX, final float pY) { this.mPaddleMap.get(pPaddleID).setPosition(pX, pY); } public void updateBall(final float pX, final float pY) { this.mBall.setPosition(pX, pY); } private void initServerAndClient() { PongGameActivity.this.initServer(); /* Wait some time after the server has been started, so it actually can start up. */ try { Thread.sleep(500); } catch (final Throwable t) { Debug.e(t); } PongGameActivity.this.initClient(); } private void initServer() { this.mServer = new PongServer(new ExampleClientConnectorListener()); this.mServer.start(); this.mEngine.registerUpdateHandler(this.mServer); } private void initClient() { try { this.mServerConnector = new PongServerConnector(this.mServerIP, new ExampleServerConnectorListener()); this.mServerConnector.getConnection().start(); } catch (final Throwable t) { Debug.e(t); } } private void toast(final String pMessage) { this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(PongGameActivity.this, pMessage, Toast.LENGTH_SHORT).show(); } }); } // =========================================================== // Inner and Anonymous Classes // =========================================================== private class PongServerConnector extends ServerConnector<SocketConnection> implements PongConstants, ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public PongServerConnector(final String pServerIP, final ISocketConnectionServerConnectorListener pSocketConnectionServerConnectorListener) throws IOException { super(new SocketConnection(new Socket(pServerIP, SERVER_PORT)), pSocketConnectionServerConnectorListener); this.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_CLOSE, ConnectionCloseServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { PongGameActivity.this.finish(); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED, ConnectionEstablishedServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { Debug.d("CLIENT: Connection established."); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_REJECTED_PROTOCOL_MISSMATCH, ConnectionRejectedProtocolMissmatchServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final ConnectionRejectedProtocolMissmatchServerMessage connectionRejectedProtocolMissmatchServerMessage = (ConnectionRejectedProtocolMissmatchServerMessage)pServerMessage; if(connectionRejectedProtocolMissmatchServerMessage.getProtocolVersion() > MessageConstants.PROTOCOL_VERSION) { // Toast.makeText(context, text, duration).show(); } else if(connectionRejectedProtocolMissmatchServerMessage.getProtocolVersion() < MessageConstants.PROTOCOL_VERSION) { // Toast.makeText(context, text, duration).show(); } PongGameActivity.this.finish(); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_PONG, ConnectionPongServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final ConnectionPongServerMessage connectionPongServerMessage = (ConnectionPongServerMessage) pServerMessage; final long roundtripMilliseconds = System.currentTimeMillis() - connectionPongServerMessage.getTimestamp(); Debug.v("Ping: " + roundtripMilliseconds / 2 + "ms"); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_SET_PADDLEID, SetPaddleIDServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final SetPaddleIDServerMessage setPaddleIDServerMessage = (SetPaddleIDServerMessage) pServerMessage; PongGameActivity.this.setPaddleID(setPaddleIDServerMessage.mPaddleID); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_UPDATE_SCORE, UpdateScoreServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final UpdateScoreServerMessage updateScoreServerMessage = (UpdateScoreServerMessage) pServerMessage; PongGameActivity.this.updateScore(updateScoreServerMessage.mPaddleID, updateScoreServerMessage.mScore); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_UPDATE_BALL, UpdateBallServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final UpdateBallServerMessage updateBallServerMessage = (UpdateBallServerMessage) pServerMessage; PongGameActivity.this.updateBall(updateBallServerMessage.mX, updateBallServerMessage.mY); } }); this.registerServerMessage(FLAG_MESSAGE_SERVER_UPDATE_PADDLE, UpdatePaddleServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final UpdatePaddleServerMessage updatePaddleServerMessage = (UpdatePaddleServerMessage) pServerMessage; PongGameActivity.this.updatePaddle(updatePaddleServerMessage.mPaddleID, updatePaddleServerMessage.mX, updatePaddleServerMessage.mY); } }); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } private class ExampleServerConnectorListener implements ISocketConnectionServerConnectorListener { @Override public void onStarted(final ServerConnector<SocketConnection> pServerConnector) { PongGameActivity.this.toast("CLIENT: Connected to server."); } @Override public void onTerminated(final ServerConnector<SocketConnection> pServerConnector) { PongGameActivity.this.toast("CLIENT: Disconnected from Server."); PongGameActivity.this.finish(); } } private class ExampleClientConnectorListener implements ISocketConnectionClientConnectorListener { @Override public void onStarted(final ClientConnector<SocketConnection> pClientConnector) { PongGameActivity.this.toast("SERVER: Client connected: " + pClientConnector.getConnection().getSocket().getInetAddress().getHostAddress()); } @Override public void onTerminated(final ClientConnector<SocketConnection> pClientConnector) { PongGameActivity.this.toast("SERVER: Client disconnected: " + pClientConnector.getConnection().getSocket().getInetAddress().getHostAddress()); } } }
Java
package org.anddev.andengine.examples.game.pong.util.constants; import org.anddev.andengine.examples.game.pong.adt.PaddleUserData; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:49:20 - 28.02.2011 */ public interface PongConstants { // =========================================================== // Final Fields // =========================================================== public static final int FPS = 30; public static final int GAME_WIDTH = 720; public static final int GAME_WIDTH_HALF = GAME_WIDTH / 2; public static final int GAME_HEIGHT = 480; public static final int GAME_HEIGHT_HALF = GAME_HEIGHT / 2; public static final int PADDLE_WIDTH = 20; public static final int PADDLE_WIDTH_HALF = PADDLE_WIDTH / 2; public static final int PADDLE_HEIGHT = 80; public static final int PADDLE_HEIGHT_HALF = PADDLE_HEIGHT / 2; public static final int BALL_WIDTH = 10; public static final int BALL_WIDTH_HALF = BALL_WIDTH / 2; public static final int BALL_HEIGHT = 10; public static final int BALL_HEIGHT_HALF = BALL_HEIGHT / 2; public static final int SCORE_PADDING = 5; public static final PaddleUserData PADDLE_LEFT = new PaddleUserData(0, 1); public static final PaddleUserData PADDLE_RIGHT = new PaddleUserData(1, 0); public static final int SERVER_PORT = 4444; /* Server --> Client */ public static final short FLAG_MESSAGE_SERVER_SET_PADDLEID = 1; public static final short FLAG_MESSAGE_SERVER_UPDATE_SCORE = FLAG_MESSAGE_SERVER_SET_PADDLEID + 1; public static final short FLAG_MESSAGE_SERVER_UPDATE_BALL = FLAG_MESSAGE_SERVER_UPDATE_SCORE + 1; public static final short FLAG_MESSAGE_SERVER_UPDATE_PADDLE = FLAG_MESSAGE_SERVER_UPDATE_BALL + 1; /* Client --> Server */ public static final short FLAG_MESSAGE_CLIENT_MOVE_PADDLE = 1; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.examples.game.racer; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.sprite.TiledSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.FixedStepPhysicsWorld; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.ui.activity.BaseGameActivity; import org.anddev.andengine.util.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 22:43:20 - 15.07.2010 */ public class RacerGameActivity extends BaseGameActivity { // =========================================================== // Constants // =========================================================== private static final int RACETRACK_WIDTH = 64; private static final int OBSTACLE_SIZE = 16; private static final int CAR_SIZE = 16; private static final int CAMERA_WIDTH = RACETRACK_WIDTH * 5; private static final int CAMERA_HEIGHT = RACETRACK_WIDTH * 3; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mVehiclesTexture; private TiledTextureRegion mVehiclesTextureRegion; private BitmapTextureAtlas mBoxTexture; private TextureRegion mBoxTextureRegion; private BitmapTextureAtlas mRacetrackTexture; private TextureRegion mRacetrackStraightTextureRegion; private TextureRegion mRacetrackCurveTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private Body mCarBody; private TiledSprite mCar; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mVehiclesTexture = new BitmapTextureAtlas(128, 16, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mVehiclesTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mVehiclesTexture, this, "vehicles.png", 0, 0, 6, 1); this.mRacetrackTexture = new BitmapTextureAtlas(128, 256, TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA); this.mRacetrackStraightTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mRacetrackTexture, this, "racetrack_straight.png", 0, 0); this.mRacetrackCurveTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mRacetrackTexture, this, "racetrack_curve.png", 0, 128); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mBoxTexture = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mBoxTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBoxTexture, this, "box.png", 0, 0); this.mEngine.getTextureManager().loadTextures(this.mVehiclesTexture, this.mRacetrackTexture, this.mOnScreenControlTexture, this.mBoxTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mPhysicsWorld = new FixedStepPhysicsWorld(30, new Vector2(0, 0), false, 8, 1); this.initRacetrack(); this.initRacetrackBorders(); this.initCar(); this.initObstacles(); this.initOnScreenControls(); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void initOnScreenControls() { final AnalogOnScreenControl analogOnScreenControl = new AnalogOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { final Body carBody = RacerGameActivity.this.mCarBody; final Vector2 velocity = Vector2Pool.obtain(pValueX * 5, pValueY * 5); carBody.setLinearVelocity(velocity); Vector2Pool.recycle(velocity); final float rotationInRad = (float)Math.atan2(-pValueX, pValueY); carBody.setTransform(carBody.getWorldCenter(), rotationInRad); RacerGameActivity.this.mCar.setRotation(MathUtils.radToDeg(rotationInRad)); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); analogOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); analogOnScreenControl.getControlBase().setAlpha(0.5f); // analogOnScreenControl.getControlBase().setScaleCenter(0, 128); // analogOnScreenControl.getControlBase().setScale(0.75f); // analogOnScreenControl.getControlKnob().setScale(0.75f); analogOnScreenControl.refreshControlKnobPosition(); this.mScene.setChildScene(analogOnScreenControl); } private void initCar() { this.mCar = new TiledSprite(20, 20, CAR_SIZE, CAR_SIZE, this.mVehiclesTextureRegion); this.mCar.setCurrentTileIndex(0); final FixtureDef carFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); this.mCarBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, this.mCar, BodyType.DynamicBody, carFixtureDef); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(this.mCar, this.mCarBody, true, false)); this.mScene.attachChild(this.mCar); } private void initObstacles() { this.addObstacle(CAMERA_WIDTH / 2, RACETRACK_WIDTH / 2); this.addObstacle(CAMERA_WIDTH / 2, RACETRACK_WIDTH / 2); this.addObstacle(CAMERA_WIDTH / 2, CAMERA_HEIGHT - RACETRACK_WIDTH / 2); this.addObstacle(CAMERA_WIDTH / 2, CAMERA_HEIGHT - RACETRACK_WIDTH / 2); } private void addObstacle(final float pX, final float pY) { final Sprite box = new Sprite(pX, pY, OBSTACLE_SIZE, OBSTACLE_SIZE, this.mBoxTextureRegion); final FixtureDef boxFixtureDef = PhysicsFactory.createFixtureDef(0.1f, 0.5f, 0.5f); final Body boxBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, box, BodyType.DynamicBody, boxFixtureDef); boxBody.setLinearDamping(10); boxBody.setAngularDamping(10); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(box, boxBody, true, true)); this.mScene.attachChild(box); } private void initRacetrack() { /* Straights. */ { final TextureRegion racetrackHorizontalStraightTextureRegion = this.mRacetrackStraightTextureRegion.deepCopy(); racetrackHorizontalStraightTextureRegion.setWidth(3 * this.mRacetrackStraightTextureRegion.getWidth()); final TextureRegion racetrackVerticalStraightTextureRegion = this.mRacetrackStraightTextureRegion; /* Top Straight */ this.mScene.attachChild(new Sprite(RACETRACK_WIDTH, 0, 3 * RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackHorizontalStraightTextureRegion)); /* Bottom Straight */ this.mScene.attachChild(new Sprite(RACETRACK_WIDTH, CAMERA_HEIGHT - RACETRACK_WIDTH, 3 * RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackHorizontalStraightTextureRegion)); /* Left Straight */ final Sprite leftVerticalStraight = new Sprite(0, RACETRACK_WIDTH, RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackVerticalStraightTextureRegion); leftVerticalStraight.setRotation(90); this.mScene.attachChild(leftVerticalStraight); /* Right Straight */ final Sprite rightVerticalStraight = new Sprite(CAMERA_WIDTH - RACETRACK_WIDTH, RACETRACK_WIDTH, RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackVerticalStraightTextureRegion); rightVerticalStraight.setRotation(90); this.mScene.attachChild(rightVerticalStraight); } /* Edges */ { final TextureRegion racetrackCurveTextureRegion = this.mRacetrackCurveTextureRegion; /* Upper Left */ final Sprite upperLeftCurve = new Sprite(0, 0, RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackCurveTextureRegion); upperLeftCurve.setRotation(90); this.mScene.attachChild(upperLeftCurve); /* Upper Right */ final Sprite upperRightCurve = new Sprite(CAMERA_WIDTH - RACETRACK_WIDTH, 0, RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackCurveTextureRegion); upperRightCurve.setRotation(180); this.mScene.attachChild(upperRightCurve); /* Lower Right */ final Sprite lowerRightCurve = new Sprite(CAMERA_WIDTH - RACETRACK_WIDTH, CAMERA_HEIGHT - RACETRACK_WIDTH, RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackCurveTextureRegion); lowerRightCurve.setRotation(270); this.mScene.attachChild(lowerRightCurve); /* Lower Left */ final Sprite lowerLeftCurve = new Sprite(0, CAMERA_HEIGHT - RACETRACK_WIDTH, RACETRACK_WIDTH, RACETRACK_WIDTH, racetrackCurveTextureRegion); this.mScene.attachChild(lowerLeftCurve); } } private void initRacetrackBorders() { final Shape bottomOuter = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape topOuter = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape leftOuter = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape rightOuter = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final Shape bottomInner = new Rectangle(RACETRACK_WIDTH, CAMERA_HEIGHT - 2 - RACETRACK_WIDTH, CAMERA_WIDTH - 2 * RACETRACK_WIDTH, 2); final Shape topInner = new Rectangle(RACETRACK_WIDTH, RACETRACK_WIDTH, CAMERA_WIDTH - 2 * RACETRACK_WIDTH, 2); final Shape leftInner = new Rectangle(RACETRACK_WIDTH, RACETRACK_WIDTH, 2, CAMERA_HEIGHT - 2 * RACETRACK_WIDTH); final Shape rightInner = new Rectangle(CAMERA_WIDTH - 2 - RACETRACK_WIDTH, RACETRACK_WIDTH, 2, CAMERA_HEIGHT - 2 * RACETRACK_WIDTH); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, bottomOuter, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, topOuter, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, leftOuter, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, rightOuter, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, bottomInner, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, topInner, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, leftInner, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, rightInner, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(bottomOuter); this.mScene.attachChild(topOuter); this.mScene.attachChild(leftOuter); this.mScene.attachChild(rightOuter); this.mScene.attachChild(bottomInner); this.mScene.attachChild(topInner); this.mScene.attachChild(leftInner); this.mScene.attachChild(rightInner); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.PointParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AccelerationInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 16:44:30 - 29.06.2010 */ public class ParticleSystemNexusExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; private static final float RATE_MIN = 8; private static final float RATE_MAX = 12; private static final int PARTICLES_MAX = 200; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_fire.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f)); /* LowerLeft to LowerRight Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(-32, CAMERA_HEIGHT - 32), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(35, 45, 0, -10)); particleSystem.addParticleInitializer(new AccelerationInitializer(5, -11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 1.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* LowerRight to LowerLeft Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH, CAMERA_HEIGHT - 32), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-35, -45, 0, -10)); particleSystem.addParticleInitializer(new AccelerationInitializer(-5, -11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 1.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* UpperLeft to UpperRight Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(-32, 0), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(35, 45, 0, 10)); particleSystem.addParticleInitializer(new AccelerationInitializer(5, 11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 0.0f, 1.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* UpperRight to UpperLeft Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH, 0), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-35, -45, 0, 10)); particleSystem.addParticleInitializer(new AccelerationInitializer(-5, 11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 0.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.SingleSceneSplitScreenEngine; import org.anddev.andengine.engine.camera.BoundCamera; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class SplitScreenExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 400; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private Camera mChaseCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add boxes.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); this.mChaseCamera = new BoundCamera(0, 0, CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2, 0, CAMERA_WIDTH, 0, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH * 2, CAMERA_HEIGHT), this.mCamera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new SingleSceneSplitScreenEngine(engineOptions, this.mChaseCamera); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); final AnimatedSprite face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion).animate(100); final Body body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); if(this.mFaceCount == 0){ this.mChaseCamera.setChaseEntity(face); } this.mFaceCount++; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.ColorKeyBitmapTextureAtlasSourceDecorator; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.decorator.shape.RectangleBitmapTextureAtlasSourceDecoratorShape; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.graphics.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ColorKeyTextureSourceDecoratorExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mChromaticCircleTextureRegion; private TextureRegion mChromaticCircleColorKeyedTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); /* The actual AssetTextureSource. */ BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); final AssetBitmapTextureAtlasSource baseTextureSource = new AssetBitmapTextureAtlasSource(this, "chromatic_circle.png"); this.mChromaticCircleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(this.mBitmapTextureAtlas, baseTextureSource, 0, 0); /* We will remove both the red and the green segment of the chromatic circle, * by nesting two ColorKeyTextureSourceDecorators around the actual baseTextureSource. */ final int colorKeyRed = Color.rgb(255, 0, 51); // Red segment final int colorKeyGreen = Color.rgb(0, 179, 0); // Green segment final ColorKeyBitmapTextureAtlasSourceDecorator colorKeyBitmapTextureAtlasSource = new ColorKeyBitmapTextureAtlasSourceDecorator(new ColorKeyBitmapTextureAtlasSourceDecorator(baseTextureSource, RectangleBitmapTextureAtlasSourceDecoratorShape.getDefaultInstance(), colorKeyRed), RectangleBitmapTextureAtlasSourceDecoratorShape.getDefaultInstance(), colorKeyGreen); this.mChromaticCircleColorKeyedTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromSource(this.mBitmapTextureAtlas, colorKeyBitmapTextureAtlasSource, 128, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final int centerX = (CAMERA_WIDTH - this.mChromaticCircleTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mChromaticCircleTextureRegion.getHeight()) / 2; final Sprite chromaticCircle = new Sprite(centerX - 80, centerY, this.mChromaticCircleTextureRegion); final Sprite chromaticCircleColorKeyed = new Sprite(centerX + 80, centerY, this.mChromaticCircleColorKeyedTextureRegion); scene.attachChild(chromaticCircle); scene.attachChild(chromaticCircleColorKeyed); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.svg.adt.ISVGColorMapper; import org.anddev.andengine.extension.svg.adt.SVGDirectColorMapper; import org.anddev.andengine.extension.svg.opengl.texture.atlas.bitmap.SVGBitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureBuilder; import org.anddev.andengine.opengl.texture.atlas.buildable.builder.ITextureBuilder.TextureAtlasSourcePackingException; import org.anddev.andengine.opengl.texture.region.BaseTextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.Debug; import android.graphics.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 13:58:12 - 21.05.2011 */ public class SVGTextureRegionExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SIZE = 128; private static final int COUNT = 12; private static final int COLUMNS = 4; private static final int ROWS = (int)Math.ceil((float)COUNT / COLUMNS); // =========================================================== // Fields // =========================================================== private Camera mCamera; private BuildableBitmapTextureAtlas mBuildableBitmapTextureAtlas; private BaseTextureRegion[] mSVGTestTextureRegions; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBuildableBitmapTextureAtlas = new BuildableBitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA); SVGBitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mSVGTestTextureRegions = new BaseTextureRegion[COUNT]; int i = 0; this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "chick.svg", 16, 16); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "chick.svg", 32, 32); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "chick.svg", 64, 64); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "chick.svg", 128, 128); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "badge.svg", 16, 16); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "badge.svg", 64, 64); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "badge.svg", 128, 128, new ISVGColorMapper() { @Override public Integer mapColor(final Integer pColor) { if(pColor == null) { return null; } else { /* Swap blue and green channel. */ return Color.argb(0, Color.red(pColor), Color.blue(pColor), Color.green(pColor)); } } }); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBuildableBitmapTextureAtlas, this, "badge.svg", 256, 256, new ISVGColorMapper() { @Override public Integer mapColor(final Integer pColor) { if(pColor == null) { return null; } else { /* Swap red and green channel. */ return Color.argb(0, Color.green(pColor), Color.red(pColor), Color.blue(pColor)); } } }); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBuildableBitmapTextureAtlas, this, "pacdroid.svg", 64, 64, 2, 2); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBuildableBitmapTextureAtlas, this, "pacdroid.svg", 256, 256, 2, 2); final SVGDirectColorMapper angryPacDroidSVGColorMapper = new SVGDirectColorMapper(); angryPacDroidSVGColorMapper.addColorMapping(0xA7CA4A, 0xEA872A); angryPacDroidSVGColorMapper.addColorMapping(0xC1DA7F, 0xFAA15F); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBuildableBitmapTextureAtlas, this, "pacdroid.svg", 256, 256, angryPacDroidSVGColorMapper, 2, 2); this.mSVGTestTextureRegions[i++] = SVGBitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBuildableBitmapTextureAtlas, this, "pacdroid_apples.svg", 256, 256, 2, 2); try { this.mBuildableBitmapTextureAtlas.build(new BlackPawnTextureBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(1)); } catch (final TextureAtlasSourcePackingException e) { Debug.e(e); } this.mEngine.getTextureManager().loadTexture(this.mBuildableBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.5f, 0.5f, 0.5f)); for(int i = 0; i < COUNT; i++) { final int row = i / COLUMNS; final int column = i % COLUMNS; final float centerX = this.mCamera.getWidth() / (COLUMNS + 1) * (column + 1); final float centerY = this.mCamera.getHeight() / (ROWS + 1) * (row + 1); final float x = centerX - SIZE * 0.5f; final float y = centerY - SIZE * 0.5f; final BaseTextureRegion baseTextureRegion = this.mSVGTestTextureRegions[i]; if(baseTextureRegion instanceof TextureRegion) { final TextureRegion textureRegion = (TextureRegion)baseTextureRegion; scene.attachChild(new Sprite(x, y, SIZE, SIZE, textureRegion)); } else if(baseTextureRegion instanceof TiledTextureRegion) { final TiledTextureRegion tiledTextureRegion = (TiledTextureRegion)baseTextureRegion; final AnimatedSprite animatedSprite = new AnimatedSprite(x, y, SIZE, SIZE, tiledTextureRegion); animatedSprite.animate(500); scene.attachChild(animatedSprite); } } return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl.IOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.DigitalOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class DigitalOnScreenControlExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; private static final int DIALOG_ALLOWDIAGONAL_ID = 0; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private DigitalOnScreenControl mDigitalOnScreenControl; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); this.mDigitalOnScreenControl = new DigitalOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } }); this.mDigitalOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); this.mDigitalOnScreenControl.getControlBase().setAlpha(0.5f); this.mDigitalOnScreenControl.getControlBase().setScaleCenter(0, 128); this.mDigitalOnScreenControl.getControlBase().setScale(1.25f); this.mDigitalOnScreenControl.getControlKnob().setScale(1.25f); this.mDigitalOnScreenControl.refreshControlKnobPosition(); scene.setChildScene(this.mDigitalOnScreenControl); return scene; } @Override public void onLoadComplete() { this.showDialog(DIALOG_ALLOWDIAGONAL_ID); } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_ALLOWDIAGONAL_ID: return new AlertDialog.Builder(this) .setTitle("Setup...") .setMessage("Do you wish to allow diagonal directions on the OnScreenControl?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { DigitalOnScreenControlExample.this.mDigitalOnScreenControl.setAllowDiagonal(true); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { DigitalOnScreenControlExample.this.mDigitalOnScreenControl.setAllowDiagonal(false); } }) .create(); } return super.onCreateDialog(pID); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.pool.RunnablePoolItem; import org.anddev.andengine.util.pool.RunnablePoolUpdateHandler; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 14:56:22 - 15.06.2011 */ public class RunnablePoolUpdateHandlerExample extends BaseExample implements IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int FACE_COUNT = 2; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private int mTargetFaceIndex = 0; private final Sprite[] mFaces = new Sprite[FACE_COUNT]; private final RunnablePoolUpdateHandler<FaceRotateRunnablePoolItem> mFaceRotateRunnablePoolUpdateHandler = new RunnablePoolUpdateHandler<FaceRotateRunnablePoolItem>() { @Override protected FaceRotateRunnablePoolItem onAllocatePoolItem() { return new FaceRotateRunnablePoolItem(); } }; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to rotate the sprites using RunnablePoolItems.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); scene.registerUpdateHandler(this.mFaceRotateRunnablePoolUpdateHandler); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; this.mFaces[0] = new Sprite(centerX - 50, centerY, this.mFaceTextureRegion); this.mFaces[1] = new Sprite(centerX + 50, centerY, this.mFaceTextureRegion); scene.attachChild(this.mFaces[0]); scene.attachChild(this.mFaces[1]); scene.setOnSceneTouchListener(this); return scene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { this.mTargetFaceIndex = (this.mTargetFaceIndex + 1) % FACE_COUNT; final FaceRotateRunnablePoolItem faceRotateRunnablePoolItem = this.mFaceRotateRunnablePoolUpdateHandler.obtainPoolItem(); faceRotateRunnablePoolItem.setTargetFace(this.mFaces[this.mTargetFaceIndex]); this.mFaceRotateRunnablePoolUpdateHandler.postPoolItem(faceRotateRunnablePoolItem); } return true; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public class FaceRotateRunnablePoolItem extends RunnablePoolItem { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private Sprite mTargetFace; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== public void setTargetFace(final Sprite pTargetFace) { this.mTargetFace = pTargetFace; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void run() { this.mTargetFace.setRotation(this.mTargetFace.getRotation() + 45); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java