code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using T4Common;
namespace T4Test
{
class Program
{
static void Main(string[] args)
{
//SqlServerProcMetaReader proc = new SqlServerProcMetaReader("Data Source=localhost;Initial Catalog=Sipmch3;Persist Security Info=True;User ID=sa;Password=sa;");
//var a = proc.SpResultMeta;
SqlServerTableMetaReader reader = new SqlServerTableMetaReader("Data Source=localhost;Initial Catalog=Sipmch3;Persist Security Info=True;User ID=sa;Password=sa;");
//reader.RetriveTableDetails(reader.GetTables("dbo").Select(x => x.Name).ToList());
}
}
}
| zznhgzf-t4-code-generator-clone | T4/T4Test/Program.cs | C# | asf20 | 641 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("T4Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("T4Test")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3ff0e757-864a-4468-88ad-10e53340d056")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zznhgzf-t4-code-generator-clone | T4/T4Test/Properties/AssemblyInfo.cs | C# | asf20 | 1,388 |
namespace T4Common.Domain
{
/// <summary>
/// Defines what primary keys are supported.
/// </summary>
public enum PrimaryKeyType
{
/// <summary>
/// Primary key consisting of one column.
/// </summary>
PrimaryKey,
/// <summary>
/// Primary key consisting of two or more columns.
/// </summary>
CompositeKey,
/// <summary>
/// Default primary key type.
/// </summary>
Default = PrimaryKey
}
}
| zznhgzf-t4-code-generator-clone | T4/T4Common/Domain/PrimaryKeyType.cs | C# | asf20 | 512 |
using System;
using System.Collections.Generic;
namespace T4Common.Domain
{
public class DotNetTypes : List<string>
{
public DotNetTypes()
{
Add(typeof (String).Name);
Add(typeof (Int16).Name);
Add(typeof (Int32).Name);
Add(typeof (Int64).Name);
Add(typeof (double).Name);
Add(typeof (DateTime).Name);
Add(typeof (TimeSpan).Name);
Add(typeof (Byte).Name);
Add(typeof (byte[]).Name);
Add(typeof (Boolean).Name);
Add(typeof (Single).Name);
Add(typeof (Guid).Name);
}
}
} | zznhgzf-t4-code-generator-clone | T4/T4Common/Domain/DotNetTypes.cs | C# | asf20 | 653 |
using System.Collections.Generic;
namespace T4Common.Domain
{
public class ColumnDetails : List<ColumnDetail>
{
}
} | zznhgzf-t4-code-generator-clone | T4/T4Common/Domain/ColumnDetails.cs | C# | asf20 | 128 |
namespace T4Common.Domain
{
public enum Language
{
CSharp,
VB
}
} | zznhgzf-t4-code-generator-clone | T4/T4Common/Domain/Language.cs | C# | asf20 | 93 |
using T4Common;
namespace T4Common.Domain
{
public class ColumnDetail
{
public ColumnDetail(string columnName, string dataType, int? dataLength, int? dataPrecision,
int dataPrecisionRadix, int? dataScale, bool isNullable)
{
DataLength = dataLength;
DataPrecision = dataPrecision;
DataPrecisionRadix = dataPrecisionRadix;
DataScale = dataScale;
ColumnName = columnName;
DataType = dataType;
IsNullable = isNullable;
MappedType = DataTypeMapper.MapFromDBType(DataType).Name;
}
public bool IsNullable { get; private set; }
public int? DataLength { get; private set; }
public int? DataPrecision { get; private set; }
public int DataPrecisionRadix { get; private set; }
public int? DataScale { get; private set; }
public string ColumnName { get; set; }
public string DataType { get; set; }
public string MappedType { get; set; }
public bool IsPrimaryKey { get; set; }
public bool IsForeignKey { get; set; }
public string PropertyName { get; set; }
public string ForeignKeyEntity { get; set; }
}
} | zznhgzf-t4-code-generator-clone | T4/T4Common/Domain/ColumnDetail.cs | C# | asf20 | 1,250 |
namespace T4Common.Domain
{
public enum ServerType
{
Oracle,
SqlServer,
PostgreSQL
}
} | zznhgzf-t4-code-generator-clone | T4/T4Common/Domain/ServerType.cs | C# | asf20 | 122 |
using System;
using System.Collections.Generic;
namespace T4Common
{
public class DataTypeMapper
{
private static IList<string> _CSharpKeywords = new List<string>()
{
"abstract",
"as",
"base",
"bool",
"break",
"byte",
"case",
"catch",
"char",
"checked",
"class",
"const",
"continue",
"decimal",
"default",
"delegate",
"do",
"double",
"else",
"enum",
"event",
"explicit",
"extern",
"false",
"finally",
"fixed",
"float",
"for",
"foreach",
"goto",
"if",
"implicit",
"in",
"int",
"interface",
"internal",
"is",
"lock",
"long",
"namespace",
"new",
"null",
"object",
"operator",
"out",
"override",
"params",
"private",
"protected",
"public",
"readonly",
"ref",
"return",
"sbyte",
"sealed",
"short",
"sizeof",
"stackalloc",
"static",
"string",
"struct",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"uint",
"ulong",
"unchecked",
"unsafe",
"ushort",
"using",
"virtual",
"void",
"volatile",
"while"
};
public static IList<string> CSharpKeywords
{
get
{
return _CSharpKeywords;
}
}
public static Type MapFromDBType(string dataType)
{
dataType = dataType.ToLower();
if (dataType == "date" || dataType == "datetime" || dataType == "timestamp" ||
dataType == "timestamp with time zone" || dataType == "timestamp with local time zone" ||
dataType == "smalldatetime")
{
return typeof(DateTime);
}
if (dataType == "number" || dataType == "long" || dataType == "bigint")
{
return typeof(long);
}
if (dataType == "int" || dataType == "interval year to month" || dataType == "binary_integer")
{
return typeof(int);
}
if (dataType == "binary_double" || dataType == "float")
{
return typeof(double);
}
if (dataType == "binary_float" || dataType == "float")
{
return typeof(float);
}
if (dataType == "blob" || dataType == "bfile *" || dataType == "long raw" || dataType == "binary" ||
dataType == "image" || dataType == "timestamp" || dataType == "varbinary")
{
return typeof(byte[]);
}
if (dataType == "interval day to second")
{
return typeof(TimeSpan);
}
if (dataType == "bit")
{
return typeof(Boolean);
}
if (dataType == "decimal" || dataType == "money" || dataType == "smallmoney" || dataType == "numeric")
{
return typeof(decimal);
}
if (dataType == "real")
{
return typeof(Single);
}
if (dataType == "smallint")
{
return typeof(Int16);
}
if (dataType == "uniqueidentifier")
{
return typeof(Guid);
}
if (dataType == "tinyint")
{
return typeof(Byte);
}
// CHAR, CLOB, NCLOB, NCHAR, XMLType, VARCHAR2, nchar, ntext
return typeof(string);
}
}
} | zznhgzf-t4-code-generator-clone | T4/T4Common/DataTypeMapper.cs | C# | asf20 | 3,429 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace T4Common
{
[Serializable]
public class SpColumn
{
/// <summary>
/// 数据库中的字段名称,有可能是C#关键字
/// </summary>
public string CName
{
get;
set;
}
public int Length
{
get;
set;
}
/// <summary>
/// 如果CName是数据库关键字,则对其进行处理,加_Keyword
/// </summary>
public string CLegalName
{
get
{
if (DataTypeMapper.CSharpKeywords.Contains(CName))
return CName + "_Keyword";
return CName;
}
}
public bool IsNullable
{
get;
set;
}
public Type CType
{
get;
set;
}
}
}
| zznhgzf-t4-code-generator-clone | T4/T4Common/SpColumn.cs | C# | asf20 | 706 |
using System;
namespace T4Common
{
// Type safe enumerator
public sealed class SqlServerConstraintType
{
public static readonly SqlServerConstraintType PrimaryKey = new SqlServerConstraintType(1, "PRIMARY KEY");
public static readonly SqlServerConstraintType ForeignKey = new SqlServerConstraintType(2, "FOREIGN KEY");
public static readonly SqlServerConstraintType Check = new SqlServerConstraintType(3, "CHECK");
public static readonly SqlServerConstraintType Unique = new SqlServerConstraintType(4, "UNIQUE");
private readonly String name;
private readonly int value;
private SqlServerConstraintType(int value, String name)
{
this.name = name;
this.value = value;
}
public override String ToString()
{
return name;
}
}
} | zznhgzf-t4-code-generator-clone | T4/T4Common/SqlServerConstraintType.cs | C# | asf20 | 874 |
using System.Collections.Generic;
using T4Common.Domain;
namespace T4Common
{
public interface IMetadataReader
{
IList<Column> GetTableDetails(Table table, string owner);
List<Table> GetTables(string owner);
IList<string> GetOwners();
List<string> GetSequences();
//List<string> GetSequences(List<Table> table);
//List<string> GetForeignKeyTables(string columnName);
}
} | zznhgzf-t4-code-generator-clone | T4/T4Common/IMetadataReader.cs | C# | asf20 | 433 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using T4Common;
using T4Common.Domain;
using T4Common.Properties;
namespace T4Common
{
public class SqlServerTableMetaReader : IMetadataReader
{
private readonly string connectionStr;
public SqlServerTableMetaReader(string conStr)
{
this.connectionStr = conStr;
}
#region IMetadataReader Members
public IList<Column> GetTableDetails(Table table, string owner)
{
var columns = new List<Column>();
var conn = new SqlConnection(connectionStr);
conn.Open();
using (conn)
{
using (SqlCommand tableDetailsCommand = conn.CreateCommand())
{
tableDetailsCommand.CommandText = string.Format(
@"
SELECT c.column_name, c.data_type, c.is_nullable, tc.constraint_type, c.numeric_precision, c.numeric_scale, c.character_maximum_length,
COLUMNPROPERTY(object_id('[' + '{1}' + '].[' + '{0}' + ']'), c.column_name, 'IsIdentity') as 'IsIdentity',t1.value as 'remark'
from information_schema.columns c
join syscolumns on (
id = object_id('[' + '{1}' + '].[' + '{0}' + ']')
and syscolumns.name = c.column_name
)
left outer join (
information_schema.constraint_column_usage ccu
join information_schema.table_constraints tc on (
tc.table_schema = ccu.table_schema
and tc.constraint_name = ccu.constraint_name
and tc.constraint_type <> 'CHECK'
)
) on (
c.table_schema = ccu.table_schema and ccu.table_schema = '{1}'
and c.table_name = ccu.table_name
and c.column_name = ccu.column_name
)
left join sys.extended_properties t1
on (
t1.major_id = object_id(c.table_name)
and syscolumns.colid = t1.minor_id
)
where c.table_name = '{0}'
order by c.table_name, c.ordinal_position",
table.Name, owner);
using (SqlDataReader sqlDataReader = tableDetailsCommand.ExecuteReader(CommandBehavior.Default))
{
while (sqlDataReader.Read())
{
string columnName = sqlDataReader.GetString(0);
string dataType = sqlDataReader.GetString(1);
bool isNullable = sqlDataReader.GetString(2).Equals("YES",
StringComparison.
CurrentCultureIgnoreCase);
var characterMaxLenth = sqlDataReader["character_maximum_length"] as int?;
var numericPrecision = sqlDataReader["numeric_precision"] as int?;
var numericScale = sqlDataReader["numeric_scale"] as int?;
var remark = sqlDataReader["remark"] as string;
bool isPrimaryKey =
(!sqlDataReader.IsDBNull(3)
? sqlDataReader.GetString(3).Equals(
SqlServerConstraintType.PrimaryKey.ToString(),
StringComparison.CurrentCultureIgnoreCase)
: false);
bool isForeignKey =
(!sqlDataReader.IsDBNull(3)
? sqlDataReader.GetString(3).Equals(
SqlServerConstraintType.ForeignKey.ToString(),
StringComparison.CurrentCultureIgnoreCase)
: false);
bool isIdentity = sqlDataReader["IsIdentity"].ToString() == "1" ? true : false;
columns.Add(new Column
{
TableName = table.Name,
Name = columnName,
DataType = dataType,
IsNullable = isNullable,
IsPrimaryKey = isPrimaryKey,
//IsPrimaryKey(selectedTableName.Name, columnName)
IsForeignKey = isForeignKey,
// IsFK()
MappedDataType =
DataTypeMapper.MapFromDBType(dataType).ToString(),
DataLength = characterMaxLenth,
IsIdentity = isIdentity,
Remark = string.IsNullOrEmpty(remark) ? "" : remark
});
table.Columns = columns;
}
table.PrimaryKey = DeterminePrimaryKeys(table);
//comment by ben 2011-09-04
//table.ForeignKeys = DetermineForeignKeyReferences(table);
//table.HasManyRelationships = DetermineHasManyRelationships(table);
}
}
}
return columns;
}
public IList<Table> RetriveTableDetails()
{
List<Table> tables = GetTables("dbo");
List<Table> tableList = new List<Table>();
var columns = new List<Column>();
var conn = new SqlConnection(connectionStr);
conn.Open();
using (conn)
{
using (SqlCommand tableDetailsCommand = conn.CreateCommand())
{
tableDetailsCommand.CommandText = string.Format(
@"
SELECT c.column_name, c .data_type, c.is_nullable, tc.constraint_type, c.numeric_precision, c.numeric_scale, c.character_maximum_length,
COLUMNPROPERTY(object_id(c.table_name), c.column_name, 'IsIdentity') as 'IsIdentity',c.table_name,t1.value as 'remark'
from information_schema.columns c
join syscolumns on (
id = object_id(c.table_name)
and syscolumns.name = c.column_name
)
left outer join (
information_schema.constraint_column_usage ccu
join information_schema.table_constraints tc on (
tc.table_schema = ccu.table_schema
and tc.constraint_name = ccu.constraint_name
and tc.constraint_type <> 'CHECK'
)
) on (
c.table_schema = ccu.table_schema and ccu.table_schema = 'dbo'
and c.table_name = ccu.table_name
and c.column_name = ccu.column_name
)
left join sys.extended_properties t1
on (
t1.major_id = object_id(c.table_name)
and syscolumns.colid = t1.minor_id
)
order by c.table_name, c.ordinal_position");
using (SqlDataReader sqlDataReader = tableDetailsCommand.ExecuteReader(CommandBehavior.Default))
{
while (sqlDataReader.Read())
{
string tableName = sqlDataReader["table_name"].ToString();
string columnName = sqlDataReader.GetString(0);
string dataType = sqlDataReader.GetString(1);
bool isNullable = sqlDataReader.GetString(2).Equals("YES",
StringComparison.
CurrentCultureIgnoreCase);
var characterMaxLenth = sqlDataReader["character_maximum_length"] as int?;
var numericPrecision = sqlDataReader["numeric_precision"] as int?;
var numericScale = sqlDataReader["numeric_scale"] as int?;
var remark = sqlDataReader["remark"] as string;
bool isPrimaryKey =
(!sqlDataReader.IsDBNull(3)
? sqlDataReader.GetString(3).Equals(
SqlServerConstraintType.PrimaryKey.ToString(),
StringComparison.CurrentCultureIgnoreCase)
: false);
bool isForeignKey =
(!sqlDataReader.IsDBNull(3)
? sqlDataReader.GetString(3).Equals(
SqlServerConstraintType.ForeignKey.ToString(),
StringComparison.CurrentCultureIgnoreCase)
: false);
bool isIdentity = sqlDataReader["IsIdentity"].ToString() == "1" ? true : false;
columns.Add(new Column
{
TableName = tableName,
Name = columnName,
DataType = dataType,
IsNullable = isNullable,
IsPrimaryKey = isPrimaryKey,
//IsPrimaryKey(selectedTableName.Name, columnName)
IsForeignKey = isForeignKey,
// IsFK()
MappedDataType =
DataTypeMapper.MapFromDBType(dataType).ToString(),
DataLength = characterMaxLenth,
IsIdentity = isIdentity,
Remark = string.IsNullOrEmpty(remark) ? "" : remark
});
}
for (int i = 0; i < columns.Count; i++)
{
Table temp = tableList.FirstOrDefault(x => x.Name == columns[i].TableName);
if (temp == null)
{
temp = new Table() { Name = columns[i].TableName, Remark = tables.FirstOrDefault(x => x.Name == columns[i].TableName).Remark, TableType = GetTableType(columns[i].TableName, tables) };
temp.Columns.Add(columns[i]);
tableList.Add(temp);
continue;
}
temp.Columns.Add(columns[i]);
}
foreach (var item in tableList)
{
item.PrimaryKey = DeterminePrimaryKeys(item);
}
//comment by ben 2011-09-04
//table.ForeignKeys = DetermineForeignKeyReferences(table);
//table.HasManyRelationships = DetermineHasManyRelationships(table);
}
}
}
return tableList;
}
public EnumTableType GetTableType(string tableName, List<Table> tables)
{
return tables.First(x => x.Name == tableName).TableType;
}
public IList<string> GetOwners()
{
var owners = new List<string>();
var conn = new SqlConnection(connectionStr);
conn.Open();
using (conn)
{
var tableCommand = conn.CreateCommand();
tableCommand.CommandText = "SELECT SCHEMA_NAME from INFORMATION_SCHEMA.SCHEMATA";
var sqlDataReader = tableCommand.ExecuteReader(CommandBehavior.CloseConnection);
while (sqlDataReader.Read())
{
var ownerName = sqlDataReader.GetString(0);
owners.Add(ownerName);
}
}
return owners;
}
public List<Table> GetTables(string owner)
{
var tables = new List<Table>();
var conn = new SqlConnection(connectionStr);
conn.Open();
using (conn)
{
var tableCommand = conn.CreateCommand();
tableCommand.CommandText = String.Format(@"
select distinct TABLE_NAME,TABLE_TYPE,t.value as Remark from information_schema.tables
outer apply(
select top 1 [value] from sys.extended_properties where object_id(TABLE_NAME)=major_id and minor_id = 0
) t
where (table_type like 'BASE TABLE' or table_type like 'VIEW') and TABLE_SCHEMA = '{0}'", owner);
var sqlDataReader = tableCommand.ExecuteReader(CommandBehavior.CloseConnection);
while (sqlDataReader.Read())
{
var tableName = sqlDataReader.GetString(0);
var tableType = sqlDataReader.GetString(1);
var tableRemark = sqlDataReader.GetValue(2);
tables.Add(new Table { Name = tableName, TableType = tableType == "VIEW" ? EnumTableType.View : EnumTableType.Table, Remark = tableRemark == null ? "" : tableRemark.ToString() });
}
}
tables.Sort((x, y) => x.Name.CompareTo(y.Name));
return tables;
}
public List<string> GetSequences()
{
return new List<string>();
}
#endregion
private static PrimaryKey DeterminePrimaryKeys(Table table)
{
IEnumerable<Column> primaryKeys = table.Columns.Where(x => x.IsPrimaryKey.Equals(true));
if (primaryKeys.Count() == 1)
{
Column c = primaryKeys.First();
var key = new PrimaryKey
{
Type = PrimaryKeyType.PrimaryKey,
Columns =
{
new Column
{
DataType = c.DataType,
Name = c.Name,
IsIdentity=c.IsIdentity
}
}
};
return key;
}
else
{
var key = new PrimaryKey
{
Type = PrimaryKeyType.CompositeKey
};
foreach (var primaryKey in primaryKeys)
{
key.Columns.Add(new Column
{
DataType = primaryKey.DataType,
Name = primaryKey.Name,
IsIdentity = primaryKey.IsIdentity
});
}
return key;
}
}
private IList<ForeignKey> DetermineForeignKeyReferences(Table table)
{
var foreignKeys = table.Columns.Where(x => x.IsForeignKey.Equals(true));
var tempForeignKeys = new List<ForeignKey>();
foreach (var foreignKey in foreignKeys)
{
tempForeignKeys.Add(new ForeignKey
{
Name = foreignKey.Name,
References = GetForeignKeyReferenceTableName(table.Name, foreignKey.Name)
});
}
return tempForeignKeys;
}
private string GetForeignKeyReferenceTableName(string selectedTableName, string columnName)
{
var conn = new SqlConnection(connectionStr);
conn.Open();
using (conn)
{
SqlCommand tableCommand = conn.CreateCommand();
tableCommand.CommandText = String.Format(
@"
select pk_table = pk.table_name
from information_schema.referential_constraints c
inner join information_schema.table_constraints fk on c.constraint_name = fk.constraint_name
inner join information_schema.table_constraints pk on c.unique_constraint_name = pk.constraint_name
inner join information_schema.key_column_usage cu on c.constraint_name = cu.constraint_name
inner join (
select i1.table_name, i2.column_name
from information_schema.table_constraints i1
inner join information_schema.key_column_usage i2 on i1.constraint_name = i2.constraint_name
where i1.constraint_type = 'PRIMARY KEY'
) pt on pt.table_name = pk.table_name
where fk.table_name = '{0}' and cu.column_name = '{1}'",
selectedTableName, columnName);
object referencedTableName = tableCommand.ExecuteScalar();
return (string)referencedTableName;
}
}
// http://blog.sqlauthority.com/2006/11/01/sql-server-query-to-display-foreign-key-relationships-and-name-of-the-constraint-for-each-table-in-database/
private IList<HasMany> DetermineHasManyRelationships(Table table)
{
var hasManyRelationships = new List<HasMany>();
var conn = new SqlConnection(connectionStr);
conn.Open();
using (conn)
{
using (var command = new SqlCommand())
{
command.Connection = conn;
command.CommandText =
String.Format(
@"
SELECT DISTINCT
PK_TABLE = b.TABLE_NAME,
FK_TABLE = c.TABLE_NAME,
FK_COLUMN_NAME = d.COLUMN_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS a
JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS b ON a.CONSTRAINT_SCHEMA = b.CONSTRAINT_SCHEMA AND a.UNIQUE_CONSTRAINT_NAME = b.CONSTRAINT_NAME
JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS c ON a.CONSTRAINT_SCHEMA = c.CONSTRAINT_SCHEMA AND a.CONSTRAINT_NAME = c.CONSTRAINT_NAME
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE d on a.CONSTRAINT_NAME = d.CONSTRAINT_NAME
WHERE b.TABLE_NAME = '{0}'
ORDER BY 1,2",
table.Name);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
hasManyRelationships.Add(new HasMany
{
Reference = reader.GetString(1),
ReferenceColumn = reader["FK_COLUMN_NAME"].ToString()
});
}
return hasManyRelationships;
}
}
}
}
}
| zznhgzf-t4-code-generator-clone | T4/T4Common/SqlServerTableMetaReader.cs | C# | asf20 | 15,254 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using T4Common.Properties;
using System.Runtime.InteropServices;
namespace T4Common
{
public class SqlServerProcMetaReader
{
private static DataTable emptyDataTable = new DataTable();
private string connectionString;
private SqlConnection connection;
private Dictionary<string, Dictionary<string,bool>> dictionaryDefault;
private Dictionary<string, List<SpColumn>> spResultMeta;
private Dictionary<string, List<SpColumn>> spParaMeta;
private List<StoreProcedure> storeProcedures;
private Dictionary<string, string> spFailed;
public Dictionary<string, string> SpFailed
{
get { return spFailed; }
set { spFailed = value; }
}
public Dictionary<string, List<SpColumn>> RetriveStoreProcedureResultMeta(Dictionary<string, string> storeProcedureFailed, string[] storeProcedureNames, [Optional, DefaultParameterValue(null)] Dictionary<string, SqlParameter[]> storeProcedureParameters)
{
var storeProcedureResultMeta = new Dictionary<string, List<SpColumn>>();
SqlCommand innerCommand = new SqlCommand();
SqlDataReader innerReader = null;
innerCommand.CommandType = CommandType.StoredProcedure;
innerCommand.Connection = connection;
for (int i = 0; i < storeProcedureNames.Length; i++)
{
try
{
List<SpColumn> columns = new List<SpColumn>();
innerCommand.CommandText = storeProcedureNames[i];
innerCommand.Parameters.Clear();
if (storeProcedureParameters == null)
{
SqlParameterCollection collection = GetParameterCollectionByProcedure(storeProcedureNames[i]);
for (int j = 0; j < collection.Count; j++)
{
if (collection[j].IsNullable)
continue;
SqlParameter newParameter = new SqlParameter(collection[j].ParameterName, collection[j].Value);
innerCommand.Parameters.Add(newParameter);
}
}
else
{
innerCommand.Parameters.AddRange(storeProcedureParameters[storeProcedureNames[i]]);
}
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
innerReader = innerCommand.ExecuteReader(CommandBehavior.CloseConnection);
DataTable table = innerReader.GetSchemaTable();
if (table == null)
{
table = emptyDataTable;
innerReader.Close();
}
int emptyColumnNameSerial = 0;
for (int k = 0; k < table.Rows.Count; k++)
{
SpColumn spColumn = new SpColumn();
spColumn.CName = table.Rows[k]["ColumnName"].ToString().Trim() == "" ? "Column" + (++emptyColumnNameSerial) : table.Rows[k]["ColumnName"].ToString().Trim();
spColumn.IsNullable = true;
spColumn.CType = DataTypeMapper.MapFromDBType(table.Rows[k]["DataTypeName"].ToString());
columns.Add(spColumn);
}
storeProcedureResultMeta.Add(storeProcedureNames[i], columns);
innerReader.Close();
}
catch (Exception e)
{
storeProcedureFailed.Add(storeProcedureNames[i], e.Message);
}
finally
{
if (innerReader!=null && !innerReader.IsClosed)
innerReader.Close();
}
}
return storeProcedureResultMeta;
}
public List<SpColumn> RetriveStoreProcedureParameterMeta(string storeProcedureName)
{
var result = RetriveStoreProcedureParameterMeta(new String[] { storeProcedureName });
return result.FirstOrDefault().Value;
}
public Dictionary<string, List<SpColumn>> RetriveStoreProcedureParameterMeta(string[] storeProcedureNames)
{
var stroePorcedureParameterMeta = new Dictionary<string, List<SpColumn>>();
for (int i = 0; i < storeProcedureNames.Length; i++)
{
List<SpColumn> columns = new List<SpColumn>();
SqlParameterCollection collection = GetParameterCollectionByProcedure(storeProcedureNames[i]);
for (int j = 0; j < collection.Count; j++)
{
SpColumn spColumn = new SpColumn();
spColumn.CName = collection[j].ParameterName;
spColumn.IsNullable = collection[j].IsNullable;
spColumn.CType = DataTypeMapper.MapFromDBType(collection[j].SqlDbType.ToString());
spColumn.Length = collection[j].Size;
columns.Add(spColumn);
}
stroePorcedureParameterMeta.Add(storeProcedureNames[i], columns);
}
return stroePorcedureParameterMeta;
}
public SqlParameter[] RetriveParametersWithDefaultValue(string procedureName)
{
SqlParameterCollection collection = GetParameterCollectionByProcedure(procedureName);
List<SqlParameter> parameters = new List<SqlParameter>();
for (int j = 0; j < collection.Count; j++)
{
if (collection[j].IsNullable)
continue;
SqlParameter newParameter = new SqlParameter(collection[j].ParameterName, collection[j].Value);
parameters.Add(newParameter);
}
return parameters.ToArray();
}
public SqlParameterCollection GetParameterCollectionByProcedure(string procedureName)
{
SqlCommand innerCommand = new SqlCommand() { Connection = connection };
innerCommand.CommandType = System.Data.CommandType.StoredProcedure;
innerCommand.CommandText = procedureName;
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlCommandBuilder.DeriveParameters(innerCommand);
innerCommand.Parameters.RemoveAt(0);
for (int i = 0; i < innerCommand.Parameters.Count; i++)
{
bool result = IsParameterHasDefaultValue(procedureName, innerCommand.Parameters[i].ParameterName);
innerCommand.Parameters[i].IsNullable = result;
if (!result)
{
if (DataTypeMapper.MapFromDBType(innerCommand.Parameters[i].SqlDbType.ToString()) == typeof(string))
innerCommand.Parameters[i].Value = string.Empty;
if (DataTypeMapper.MapFromDBType(innerCommand.Parameters[i].SqlDbType.ToString()) == typeof(DateTime))
innerCommand.Parameters[i].Value = DateTime.Now;
if (DataTypeMapper.MapFromDBType(innerCommand.Parameters[i].SqlDbType.ToString()) == typeof(long) ||
DataTypeMapper.MapFromDBType(innerCommand.Parameters[i].SqlDbType.ToString()) == typeof(int) ||
DataTypeMapper.MapFromDBType(innerCommand.Parameters[i].SqlDbType.ToString()) == typeof(double) ||
DataTypeMapper.MapFromDBType(innerCommand.Parameters[i].SqlDbType.ToString()) == typeof(float) ||
DataTypeMapper.MapFromDBType(innerCommand.Parameters[i].SqlDbType.ToString()) == typeof(Single) ||
DataTypeMapper.MapFromDBType(innerCommand.Parameters[i].SqlDbType.ToString()) == typeof(Int16) ||
DataTypeMapper.MapFromDBType(innerCommand.Parameters[i].SqlDbType.ToString()) == typeof(decimal)
)
innerCommand.Parameters[i].Value = 0;
if (DataTypeMapper.MapFromDBType(innerCommand.Parameters[i].SqlDbType.ToString()) == typeof(Boolean))
innerCommand.Parameters[i].Value = true;
if (DataTypeMapper.MapFromDBType(innerCommand.Parameters[i].SqlDbType.ToString()) == typeof(Guid))
innerCommand.Parameters[i].Value = new Guid();
if (DataTypeMapper.MapFromDBType(innerCommand.Parameters[i].SqlDbType.ToString()) == typeof(string))
innerCommand.Parameters[i].Value = string.Empty;
}
}
return innerCommand.Parameters;
}
public Dictionary<string, List<SpColumn>> SpResultMeta
{
get
{
if (spResultMeta != null)
return spResultMeta;
spFailed = new Dictionary<string, string>();
spResultMeta = new Dictionary<string, List<SpColumn>>();
spResultMeta = RetriveStoreProcedureResultMeta(spFailed, StoreProcedures.Select(x => x.Name).ToArray(),null);
return spResultMeta;
}
}
public Dictionary<string, List<SpColumn>> SpParaMeta
{
get
{
if (spParaMeta != null)
return spParaMeta;
spParaMeta = RetriveStoreProcedureParameterMeta(StoreProcedures.Select(x => x.Name).ToArray());
return spParaMeta;
}
}
public List<StoreProcedure> StoreProcedures
{
get
{
if (storeProcedures != null)
return storeProcedures;
SqlDataReader innerReader;
SqlCommand innerCommand = new SqlCommand() { Connection = connection };
storeProcedures = new List<StoreProcedure>();
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
innerCommand.CommandText = @"select * from sys.procedures where [name] like 'UP_%' order by [name]";
innerReader = innerCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
while (innerReader.Read())
{
storeProcedures.Add(new StoreProcedure() { Name = innerReader.GetString(innerReader.GetOrdinal("name")) });
}
innerReader.Close();
return storeProcedures;
}
}
public List<StoreProcedure> AllStoreProcedures
{
get
{
if (storeProcedures != null)
return storeProcedures;
SqlDataReader innerReader;
SqlCommand innerCommand = new SqlCommand() { Connection = connection };
storeProcedures = new List<StoreProcedure>();
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
innerCommand.CommandText = @"select * from sys.procedures order by [name]";
innerReader = innerCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
while (innerReader.Read())
{
storeProcedures.Add(new StoreProcedure() { Name = innerReader.GetString(innerReader.GetOrdinal("name")) });
}
innerReader.Close();
return storeProcedures;
}
}
public void FillParameter(StoreProcedure sp)
{
List<SpColumn> columns = new List<SpColumn>();
SqlParameterCollection collection = GetParameterCollectionByProcedure(sp.Name);
for (int j = 0; j < collection.Count; j++)
{
SpColumn spColumn = new SpColumn();
spColumn.CName = collection[j].ParameterName;
spColumn.IsNullable = collection[j].IsNullable;
spColumn.CType = DataTypeMapper.MapFromDBType(collection[j].SqlDbType.ToString());
columns.Add(spColumn);
}
sp.Parameters = columns;
}
public SqlServerProcMetaReader(string conStr)
{
connectionString = conStr;
connection = new SqlConnection();
connection.ConnectionString = connectionString;
dictionaryDefault = new Dictionary<string, Dictionary<string, bool>>();
CreateNecessaryProcedure();
}
private bool IsParameterHasDefaultValue(string procedureName,string parameterName)
{
SqlDataReader innerReader;
SqlCommand innerCommand = new SqlCommand() { Connection = connection };
if (dictionaryDefault.ContainsKey(procedureName))
{
Dictionary<string,bool> values = dictionaryDefault[procedureName];
return values[parameterName];
}
Dictionary<string, bool> subDictionary = new Dictionary<string, bool>();
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
innerCommand.CommandText = "sys_GetParameters";
innerCommand.CommandType = System.Data.CommandType.StoredProcedure;
innerCommand.Parameters.Add("@object_name", procedureName);
innerReader = innerCommand.ExecuteReader(CommandBehavior.CloseConnection);
while (innerReader.Read())
{
subDictionary.Add(innerReader.GetString(innerReader.GetOrdinal("param_name")), innerReader.GetBoolean(innerReader.GetOrdinal("has_default_value")));
}
innerReader.Close();
return subDictionary[parameterName];
}
private void CreateNecessaryProcedure()
{
if (AllStoreProcedures.Where(x => x.Name == "sys_GetParameters").Count() > 0)
return;
SqlCommand innerCommand = new SqlCommand() { Connection = connection };
innerCommand.CommandText = @"CREATE PROCEDURE [dbo].[sys_GetParameters]
@object_name NVARCHAR(511)
AS
BEGIN
SET NOCOUNT ON;
DECLARE
@object_id INT,
@paramID INT,
@paramName SYSNAME,
@definition NVARCHAR(MAX),
@t NVARCHAR(MAX),
@loc1 INT,
@loc2 INT,
@loc3 INT,
@loc4 INT,
@has_default_value BIT;
SET @object_id = OBJECT_ID(@object_name);
IF (@object_id IS NOT NULL)
BEGIN
SELECT @definition = OBJECT_DEFINITION(@object_id);
CREATE TABLE #params
(
parameter_id INT PRIMARY KEY,
has_default_value BIT NOT NULL DEFAULT (0)
);
DECLARE c CURSOR
LOCAL FORWARD_ONLY STATIC READ_ONLY
FOR
SELECT
parameter_id,
[name]
FROM
sys.parameters
WHERE
[object_id] = @object_id;
OPEN c;
FETCH NEXT FROM c INTO @paramID, @paramName;
WHILE (@@FETCH_STATUS = 0)
BEGIN
SELECT
@t = SUBSTRING
(
@definition,
CHARINDEX(@paramName, @definition),
4000
),
@has_default_value = 0;
SET @loc1 = COALESCE(NULLIF(CHARINDEX('''', @t), 0), 4000);
SET @loc2 = COALESCE(NULLIF(CHARINDEX(',', @t), 0), 4000);
SET @loc3 = NULLIF(CHARINDEX('OUTPUT', @t), 0);
SET @loc4 = NULLIF(CHARINDEX('AS', @t), 0);
SET @loc1 = CASE WHEN @loc2 < @loc1 THEN @loc2 ELSE @loc1 END;
SET @loc1 = CASE WHEN @loc3 < @loc1 THEN @loc3 ELSE @loc1 END;
SET @loc1 = CASE WHEN @loc4 < @loc1 THEN @loc4 ELSE @loc1 END;
IF CHARINDEX('=', LTRIM(RTRIM(SUBSTRING(@t, 1, @loc1)))) > 0
SET @has_default_value = 1;
INSERT #params
(
parameter_id,
has_default_value
)
SELECT
@paramID,
@has_default_value;
FETCH NEXT FROM c INTO @paramID, @paramName;
END
SELECT
sp.[object_id],
[object_name] = @object_name,
param_name = sp.[name],
sp.parameter_id,
type_name = UPPER(st.[name]),
sp.max_length,
sp.[precision],
sp.scale,
sp.is_output,
p.has_default_value
FROM
sys.parameters sp
INNER JOIN
#params p
ON
sp.parameter_id = p.parameter_id
INNER JOIN
sys.types st
ON
sp.user_type_id = st.user_type_id
WHERE
sp.[object_id] = @object_id;
CLOSE c;
DEALLOCATE c;
DROP TABLE #params;
END
END
";
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
innerCommand.ExecuteNonQuery();
}
}
}
| zznhgzf-t4-code-generator-clone | T4/T4Common/SqlServerProcMetaReader.cs | C# | asf20 | 14,782 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("T4Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("T4Common")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("625b0de9-91c0-4f17-b161-e3a1c3538d4e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zznhgzf-t4-code-generator-clone | T4/T4Common/Properties/AssemblyInfo.cs | C# | asf20 | 1,392 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace T4Common
{
public enum CodeOutputType
{
Entity,
EntityMapping,
EntityRoot,
ViewEntity,
ViewEntityMapping,
SPEntityMapping,
SPEntity,
SPParameterEntity,
SPBiz,
SPDal,
Biz,
BizView,
BizRoot,
Dal,
DalView,
DalRoot,
Enum,
CSProjEntity,
CSProjBiz,
CSProjDal,
CSProjEnum,
Solution
}
}
| zznhgzf-t4-code-generator-clone | T4/T4Common/CodeOutputType.cs | C# | asf20 | 426 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace T4Common
{
public class StoreProcedure
{
public string Name { get; set; }
public string Description { get; set; }
public List<SpColumn> Parameters { get; set; }
}
}
| zznhgzf-t4-code-generator-clone | T4/T4Common/StoreProcedure.cs | C# | asf20 | 303 |
hg push https://andengine.googlecode.com/hg/
pause | zzy421-andengine | push_google_code.bat | Batchfile | lgpl | 51 |
package org.anddev.andengine.sensor.accelerometer;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:58:38 - 10.03.2010
*/
public interface IAccelerometerListener {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onAccelerometerChanged(final AccelerometerData pAccelerometerData);
}
| zzy421-andengine | src/org/anddev/andengine/sensor/accelerometer/IAccelerometerListener.java | Java | lgpl | 609 |
package org.anddev.andengine.sensor.accelerometer;
import java.util.Arrays;
import org.anddev.andengine.sensor.BaseSensorData;
import android.hardware.SensorManager;
import android.view.Surface;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:50:44 - 10.03.2010
*/
public class AccelerometerData extends BaseSensorData {
// ===========================================================
// Constants
// ===========================================================
private static final IAxisSwap AXISSWAPS[] = new IAxisSwap[4];
static {
AXISSWAPS[Surface.ROTATION_0] = new IAxisSwap() {
@Override
public void swapAxis(final float[] pValues) {
final float x = -pValues[SensorManager.DATA_X];
final float y = pValues[SensorManager.DATA_Y];
pValues[SensorManager.DATA_X] = x;
pValues[SensorManager.DATA_Y] = y;
}
};
AXISSWAPS[Surface.ROTATION_90] = new IAxisSwap() {
@Override
public void swapAxis(final float[] pValues) {
final float x = pValues[SensorManager.DATA_Y];
final float y = pValues[SensorManager.DATA_X];
pValues[SensorManager.DATA_X] = x;
pValues[SensorManager.DATA_Y] = y;
}
};
AXISSWAPS[Surface.ROTATION_180] = new IAxisSwap() {
@Override
public void swapAxis(final float[] pValues) {
final float x = pValues[SensorManager.DATA_X];
final float y = -pValues[SensorManager.DATA_Y];
pValues[SensorManager.DATA_X] = x;
pValues[SensorManager.DATA_Y] = y;
}
};
AXISSWAPS[Surface.ROTATION_270] = new IAxisSwap() {
@Override
public void swapAxis(final float[] pValues) {
final float x = -pValues[SensorManager.DATA_Y];
final float y = -pValues[SensorManager.DATA_X];
pValues[SensorManager.DATA_X] = x;
pValues[SensorManager.DATA_Y] = y;
}
};
}
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public AccelerometerData(final int pDisplayOrientation) {
super(3, pDisplayOrientation);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public float getX() {
return this.mValues[SensorManager.DATA_X];
}
public float getY() {
return this.mValues[SensorManager.DATA_Y];
}
public float getZ() {
return this.mValues[SensorManager.DATA_Z];
}
public void setX(final float pX) {
this.mValues[SensorManager.DATA_X] = pX;
}
public void setY(final float pY) {
this.mValues[SensorManager.DATA_Y] = pY;
}
public void setZ(final float pZ) {
this.mValues[SensorManager.DATA_Z] = pZ;
}
@Override
public void setValues(final float[] pValues) {
super.setValues(pValues);
AccelerometerData.AXISSWAPS[this.mDisplayRotation].swapAxis(this.mValues);
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public String toString() {
return "Accelerometer: " + Arrays.toString(this.mValues);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
private static interface IAxisSwap {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void swapAxis(final float[] pValues);
}
}
| zzy421-andengine | src/org/anddev/andengine/sensor/accelerometer/AccelerometerData.java | Java | lgpl | 4,097 |
package org.anddev.andengine.sensor.accelerometer;
import org.anddev.andengine.sensor.SensorDelay;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:10:34 - 31.10.2010
*/
public class AccelerometerSensorOptions {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
final SensorDelay mSensorDelay;
// ===========================================================
// Constructors
// ===========================================================
public AccelerometerSensorOptions(final SensorDelay pSensorDelay) {
this.mSensorDelay = pSensorDelay;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public SensorDelay getSensorDelay() {
return this.mSensorDelay;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/sensor/accelerometer/AccelerometerSensorOptions.java | Java | lgpl | 1,585 |
package org.anddev.andengine.sensor.orientation;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:30:42 - 25.05.2010
*/
public interface IOrientationListener {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onOrientationChanged(final OrientationData pOrientationData);
}
| zzy421-andengine | src/org/anddev/andengine/sensor/orientation/IOrientationListener.java | Java | lgpl | 599 |
package org.anddev.andengine.sensor.orientation;
import java.util.Arrays;
import org.anddev.andengine.sensor.BaseSensorData;
import org.anddev.andengine.util.constants.MathConstants;
import android.hardware.SensorManager;
import android.view.Surface;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:30:33 - 25.05.2010
*/
public class OrientationData extends BaseSensorData {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float[] mAccelerometerValues = new float[3];
private final float[] mMagneticFieldValues = new float[3];
private final float[] mRotationMatrix = new float[16];
private int mMagneticFieldAccuracy;
// ===========================================================
// Constructors
// ===========================================================
public OrientationData(final int pDisplayRotation) {
super(3, pDisplayRotation);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public float getRoll() {
return super.mValues[SensorManager.DATA_Z];
}
public float getPitch() {
return super.mValues[SensorManager.DATA_Y];
}
public float getYaw() {
return super.mValues[SensorManager.DATA_X];
}
@Override
@Deprecated
public void setValues(final float[] pValues) {
super.setValues(pValues);
}
@Override
@Deprecated
public void setAccuracy(final int pAccuracy) {
super.setAccuracy(pAccuracy);
}
public void setAccelerometerValues(final float[] pValues) {
System.arraycopy(pValues, 0, this.mAccelerometerValues, 0, pValues.length);
this.updateOrientation();
}
public void setMagneticFieldValues(final float[] pValues) {
System.arraycopy(pValues, 0, this.mMagneticFieldValues, 0, pValues.length);
this.updateOrientation();
}
private void updateOrientation() {
SensorManager.getRotationMatrix(this.mRotationMatrix, null, this.mAccelerometerValues, this.mMagneticFieldValues);
// TODO Use dont't use identical matrixes in remapCoordinateSystem, due to performance reasons.
switch(this.mDisplayRotation) {
case Surface.ROTATION_0:
/* Nothing. */
break;
case Surface.ROTATION_90:
SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, this.mRotationMatrix);
break;
// case Surface.ROTATION_180:
// SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix);
// break;
// case Surface.ROTATION_270:
// SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix);
// break;
}
final float[] values = this.mValues;
SensorManager.getOrientation(this.mRotationMatrix, values);
for(int i = values.length - 1; i >= 0; i--) {
values[i] = values[i] * MathConstants.RAD_TO_DEG;
}
}
public int getAccelerometerAccuracy() {
return this.getAccuracy();
}
public void setAccelerometerAccuracy(final int pAccelerometerAccuracy) {
super.setAccuracy(pAccelerometerAccuracy);
}
public int getMagneticFieldAccuracy() {
return this.mMagneticFieldAccuracy;
}
public void setMagneticFieldAccuracy(final int pMagneticFieldAccuracy) {
this.mMagneticFieldAccuracy = pMagneticFieldAccuracy;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public String toString() {
return "Orientation: " + Arrays.toString(this.mValues);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/sensor/orientation/OrientationData.java | Java | lgpl | 4,312 |
package org.anddev.andengine.sensor.orientation;
import org.anddev.andengine.sensor.SensorDelay;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:12:36 - 31.10.2010
*/
public class OrientationSensorOptions {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
final SensorDelay mSensorDelay;
// ===========================================================
// Constructors
// ===========================================================
public OrientationSensorOptions(final SensorDelay pSensorDelay) {
this.mSensorDelay = pSensorDelay;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public SensorDelay getSensorDelay() {
return this.mSensorDelay;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/sensor/orientation/OrientationSensorOptions.java | Java | lgpl | 1,579 |
package org.anddev.andengine.sensor.location;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:39:23 - 31.10.2010
*/
public interface ILocationListener {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* @see {@link LocationListener#onProviderEnabled(String)}
*/
public void onLocationProviderEnabled();
/**
* @see {@link LocationListener#onLocationChanged(Location)}
*/
public void onLocationChanged(final Location pLocation);
public void onLocationLost();
/**
* @see {@link LocationListener#onProviderDisabled(String)}
*/
public void onLocationProviderDisabled();
/**
* @see {@link LocationListener#onStatusChanged(String, int, android.os.Bundle)}
*/
public void onLocationProviderStatusChanged(final LocationProviderStatus pLocationProviderStatus, final Bundle pBundle);
}
| zzy421-andengine | src/org/anddev/andengine/sensor/location/ILocationListener.java | Java | lgpl | 1,250 |
package org.anddev.andengine.sensor.location;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:55:57 - 31.10.2010
*/
public enum LocationProviderStatus {
// ===========================================================
// Elements
// ===========================================================
AVAILABLE,
OUT_OF_SERVICE,
TEMPORARILY_UNAVAILABLE;
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/sensor/location/LocationProviderStatus.java | Java | lgpl | 1,502 |
package org.anddev.andengine.sensor.location;
import org.anddev.andengine.util.constants.TimeConstants;
import android.location.Criteria;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:02:12 - 31.10.2010
*/
public class LocationSensorOptions extends Criteria {
// ===========================================================
// Constants
// ===========================================================
private static final long MINIMUMTRIGGERTIME_DEFAULT = 1 * TimeConstants.MILLISECONDSPERSECOND;
private static final long MINIMUMTRIGGERDISTANCE_DEFAULT = 10;
// ===========================================================
// Fields
// ===========================================================
private boolean mEnabledOnly = true;
private long mMinimumTriggerTime = MINIMUMTRIGGERTIME_DEFAULT;
private long mMinimumTriggerDistance = MINIMUMTRIGGERDISTANCE_DEFAULT;
// ===========================================================
// Constructors
// ===========================================================
/**
* @see {@link LocationSensorOptions#setAccuracy(int)},
* {@link LocationSensorOptions#setAltitudeRequired(boolean)},
* {@link LocationSensorOptions#setBearingRequired(boolean)},
* {@link LocationSensorOptions#setCostAllowed(boolean)},
* {@link LocationSensorOptions#setEnabledOnly(boolean)},
* {@link LocationSensorOptions#setMinimumTriggerDistance(long)},
* {@link LocationSensorOptions#setMinimumTriggerTime(long)},
* {@link LocationSensorOptions#setPowerRequirement(int)},
* {@link LocationSensorOptions#setSpeedRequired(boolean)}.
*/
public LocationSensorOptions() {
}
/**
* @param pAccuracy
* @param pAltitudeRequired
* @param pBearingRequired
* @param pCostAllowed
* @param pPowerRequirement
* @param pSpeedRequired
* @param pEnabledOnly
* @param pMinimumTriggerTime
* @param pMinimumTriggerDistance
*/
public LocationSensorOptions(final int pAccuracy, final boolean pAltitudeRequired, final boolean pBearingRequired, final boolean pCostAllowed, final int pPowerRequirement, final boolean pSpeedRequired, final boolean pEnabledOnly, final long pMinimumTriggerTime, final long pMinimumTriggerDistance) {
this.mEnabledOnly = pEnabledOnly;
this.mMinimumTriggerTime = pMinimumTriggerTime;
this.mMinimumTriggerDistance = pMinimumTriggerDistance;
this.setAccuracy(pAccuracy);
this.setAltitudeRequired(pAltitudeRequired);
this.setBearingRequired(pBearingRequired);
this.setCostAllowed(pCostAllowed);
this.setPowerRequirement(pPowerRequirement);
this.setSpeedRequired(pSpeedRequired);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void setEnabledOnly(final boolean pEnabledOnly) {
this.mEnabledOnly = pEnabledOnly;
}
public boolean isEnabledOnly() {
return this.mEnabledOnly;
}
public long getMinimumTriggerTime() {
return this.mMinimumTriggerTime;
}
public void setMinimumTriggerTime(final long pMinimumTriggerTime) {
this.mMinimumTriggerTime = pMinimumTriggerTime;
}
public long getMinimumTriggerDistance() {
return this.mMinimumTriggerDistance;
}
public void setMinimumTriggerDistance(final long pMinimumTriggerDistance) {
this.mMinimumTriggerDistance = pMinimumTriggerDistance;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/sensor/location/LocationSensorOptions.java | Java | lgpl | 4,011 |
package org.anddev.andengine.sensor;
import java.util.Arrays;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:50:44 - 10.03.2010
*/
public class BaseSensorData {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected final float[] mValues;
protected int mAccuracy;
protected int mDisplayRotation;
// ===========================================================
// Constructors
// ===========================================================
public BaseSensorData(final int pValueCount, int pDisplayRotation) {
this.mValues = new float[pValueCount];
this.mDisplayRotation = pDisplayRotation;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public float[] getValues() {
return this.mValues;
}
public void setValues(final float[] pValues) {
System.arraycopy(pValues, 0, this.mValues, 0, pValues.length);
}
public void setAccuracy(final int pAccuracy) {
this.mAccuracy = pAccuracy;
}
public int getAccuracy() {
return this.mAccuracy;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public String toString() {
return "Values: " + Arrays.toString(this.mValues);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/sensor/BaseSensorData.java | Java | lgpl | 2,006 |
package org.anddev.andengine.sensor;
import android.hardware.SensorManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:14:38 - 31.10.2010
*/
public enum SensorDelay {
// ===========================================================
// Elements
// ===========================================================
NORMAL(SensorManager.SENSOR_DELAY_NORMAL),
UI(SensorManager.SENSOR_DELAY_UI),
GAME(SensorManager.SENSOR_DELAY_GAME),
FASTEST(SensorManager.SENSOR_DELAY_FASTEST);
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int mDelay;
// ===========================================================
// Constructors
// ===========================================================
private SensorDelay(final int pDelay) {
this.mDelay = pDelay;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public int getDelay() {
return this.mDelay;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/sensor/SensorDelay.java | Java | lgpl | 1,800 |
package org.anddev.andengine.level.util.constants;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:23:27 - 11.10.2010
*/
public interface LevelConstants {
// ===========================================================
// Final Fields
// ===========================================================
public static final String TAG_LEVEL = "level";
public static final String TAG_LEVEL_ATTRIBUTE_NAME = "name";
public static final String TAG_LEVEL_ATTRIBUTE_UID = "uid";
public static final String TAG_LEVEL_ATTRIBUTE_WIDTH = "width";
public static final String TAG_LEVEL_ATTRIBUTE_HEIGHT = "height";
// ===========================================================
// Methods
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/level/util/constants/LevelConstants.java | Java | lgpl | 831 |
package org.anddev.andengine.level;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.anddev.andengine.level.util.constants.LevelConstants;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.StreamUtils;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.content.Context;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:16:19 - 11.10.2010
*/
public class LevelLoader implements LevelConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private String mAssetBasePath;
private IEntityLoader mDefaultEntityLoader;
private final HashMap<String, IEntityLoader> mEntityLoaders = new HashMap<String, IEntityLoader>();
// ===========================================================
// Constructors
// ===========================================================
public LevelLoader() {
this("");
}
public LevelLoader(final String pAssetBasePath) {
this.setAssetBasePath(pAssetBasePath);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public IEntityLoader getDefaultEntityLoader() {
return this.mDefaultEntityLoader;
}
public void setDefaultEntityLoader(IEntityLoader pDefaultEntityLoader) {
this.mDefaultEntityLoader = pDefaultEntityLoader;
}
/**
* @param pAssetBasePath must end with '<code>/</code>' or have <code>.length() == 0</code>.
*/
public void setAssetBasePath(final String pAssetBasePath) {
if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) {
this.mAssetBasePath = pAssetBasePath;
} else {
throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero.");
}
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected void onAfterLoadLevel() {
}
protected void onBeforeLoadLevel() {
}
// ===========================================================
// Methods
// ===========================================================
public void registerEntityLoader(final String pEntityName, final IEntityLoader pEntityLoader) {
this.mEntityLoaders.put(pEntityName, pEntityLoader);
}
public void registerEntityLoader(final String[] pEntityNames, final IEntityLoader pEntityLoader) {
final HashMap<String, IEntityLoader> entityLoaders = this.mEntityLoaders;
for(int i = pEntityNames.length - 1; i >= 0; i--) {
entityLoaders.put(pEntityNames[i], pEntityLoader);
}
}
public void loadLevelFromAsset(final Context pContext, final String pAssetPath) throws IOException {
this.loadLevelFromStream(pContext.getAssets().open(this.mAssetBasePath + pAssetPath));
}
public void loadLevelFromResource(final Context pContext, final int pRawResourceID) throws IOException {
this.loadLevelFromStream(pContext.getResources().openRawResource(pRawResourceID));
}
public void loadLevelFromStream(final InputStream pInputStream) throws IOException {
try{
final SAXParserFactory spf = SAXParserFactory.newInstance();
final SAXParser sp = spf.newSAXParser();
final XMLReader xr = sp.getXMLReader();
this.onBeforeLoadLevel();
final LevelParser levelParser = new LevelParser(this.mDefaultEntityLoader, this.mEntityLoaders);
xr.setContentHandler(levelParser);
xr.parse(new InputSource(new BufferedInputStream(pInputStream)));
this.onAfterLoadLevel();
} catch (final SAXException se) {
Debug.e(se);
/* Doesn't happen. */
} catch (final ParserConfigurationException pe) {
Debug.e(pe);
/* Doesn't happen. */
} finally {
StreamUtils.close(pInputStream);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static interface IEntityLoader {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onLoadEntity(final String pEntityName, final Attributes pAttributes);
}
}
| zzy421-andengine | src/org/anddev/andengine/level/LevelLoader.java | Java | lgpl | 4,994 |
package org.anddev.andengine.level;
import java.util.HashMap;
import org.anddev.andengine.level.LevelLoader.IEntityLoader;
import org.anddev.andengine.level.util.constants.LevelConstants;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:35:32 - 11.10.2010
*/
public class LevelParser extends DefaultHandler implements LevelConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final IEntityLoader mDefaultEntityLoader;
private final HashMap<String, IEntityLoader> mEntityLoaders;
// ===========================================================
// Constructors
// ===========================================================
public LevelParser(final IEntityLoader pDefaultEntityLoader, final HashMap<String, IEntityLoader> pEntityLoaders) {
this.mDefaultEntityLoader = pDefaultEntityLoader;
this.mEntityLoaders = pEntityLoaders;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void startElement(final String pUri, final String pLocalName, final String pQualifiedName, final Attributes pAttributes) throws SAXException {
final IEntityLoader entityLoader = this.mEntityLoaders.get(pLocalName);
if(entityLoader != null) {
entityLoader.onLoadEntity(pLocalName, pAttributes);
} else {
if(this.mDefaultEntityLoader != null) {
this.mDefaultEntityLoader.onLoadEntity(pLocalName, pAttributes);
} else {
throw new IllegalArgumentException("Unexpected tag: '" + pLocalName + "'.");
}
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/level/LevelParser.java | Java | lgpl | 2,496 |
package org.anddev.andengine.util.pool;
import org.anddev.andengine.entity.IEntity;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 00:53:22 - 28.08.2010
*/
public class EntityDetachRunnablePoolItem extends RunnablePoolItem {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected IEntity mEntity;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public void setEntity(final IEntity pEntity) {
this.mEntity = pEntity;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void run() {
this.mEntity.detachSelf();
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | zzy421-andengine | src/org/anddev/andengine/util/pool/EntityDetachRunnablePoolItem.java | Java | lgpl | 1,554 |
package org.anddev.andengine.util.pool;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:46:50 - 27.08.2010
*/
public abstract class RunnablePoolItem extends PoolItem implements Runnable {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | zzy421-andengine | src/org/anddev/andengine/util/pool/RunnablePoolItem.java | Java | lgpl | 1,333 |
package org.anddev.andengine.util.pool;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:16:25 - 31.08.2010
*/
public class EntityDetachRunnablePoolUpdateHandler extends RunnablePoolUpdateHandler<EntityDetachRunnablePoolItem> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected EntityDetachRunnablePoolItem onAllocatePoolItem() {
return new EntityDetachRunnablePoolItem();
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/pool/EntityDetachRunnablePoolUpdateHandler.java | Java | lgpl | 1,502 |
package org.anddev.andengine.util.pool;
/**
* @author Valentin Milea
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
*
* @since 23:00:21 - 21.08.2010
* @param <T>
*/
public abstract class Pool<T extends PoolItem> extends GenericPool<T>{
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public Pool() {
super();
}
public Pool(final int pInitialSize) {
super(pInitialSize);
}
public Pool(final int pInitialSize, final int pGrowth) {
super(pInitialSize, pGrowth);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected T onHandleAllocatePoolItem() {
final T poolItem = super.onHandleAllocatePoolItem();
poolItem.mParent = this;
return poolItem;
}
@Override
protected void onHandleObtainItem(final T pPoolItem) {
pPoolItem.mRecycled = false;
pPoolItem.onObtain();
}
@Override
protected void onHandleRecycleItem(final T pPoolItem) {
pPoolItem.onRecycle();
pPoolItem.mRecycled = true;
}
@Override
public synchronized void recyclePoolItem(final T pPoolItem) {
if(pPoolItem.mParent == null) {
throw new IllegalArgumentException("PoolItem not assigned to a pool!");
} else if(!pPoolItem.isFromPool(this)) {
throw new IllegalArgumentException("PoolItem from another pool!");
} else if(pPoolItem.isRecycled()) {
throw new IllegalArgumentException("PoolItem already recycled!");
}
super.recyclePoolItem(pPoolItem);
}
// ===========================================================
// Methods
// ===========================================================
public synchronized boolean ownsPoolItem(final T pPoolItem) {
return pPoolItem.mParent == this;
}
@SuppressWarnings("unchecked")
void recycle(final PoolItem pPoolItem) {
this.recyclePoolItem((T) pPoolItem);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/pool/Pool.java | Java | lgpl | 2,701 |
package org.anddev.andengine.util.pool;
import java.util.ArrayList;
import org.anddev.andengine.engine.handler.IUpdateHandler;
/**
* @author Valentin Milea
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
*
* @since 23:02:58 - 21.08.2010
* @param <T>
*/
public abstract class PoolUpdateHandler<T extends PoolItem> implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final Pool<T> mPool;
private final ArrayList<T> mScheduledPoolItems = new ArrayList<T>();
// ===========================================================
// Constructors
// ===========================================================
public PoolUpdateHandler() {
this.mPool = new Pool<T>() {
@Override
protected T onAllocatePoolItem() {
return PoolUpdateHandler.this.onAllocatePoolItem();
}
};
}
public PoolUpdateHandler(final int pInitialPoolSize) {
this.mPool = new Pool<T>(pInitialPoolSize) {
@Override
protected T onAllocatePoolItem() {
return PoolUpdateHandler.this.onAllocatePoolItem();
}
};
}
public PoolUpdateHandler(final int pInitialPoolSize, final int pGrowth) {
this.mPool = new Pool<T>(pInitialPoolSize, pGrowth) {
@Override
protected T onAllocatePoolItem() {
return PoolUpdateHandler.this.onAllocatePoolItem();
}
};
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract T onAllocatePoolItem();
protected abstract void onHandlePoolItem(final T pPoolItem);
@Override
public void onUpdate(final float pSecondsElapsed) {
final ArrayList<T> scheduledPoolItems = this.mScheduledPoolItems;
synchronized (scheduledPoolItems) {
final int count = scheduledPoolItems.size();
if(count > 0) {
final Pool<T> pool = this.mPool;
T item;
for(int i = 0; i < count; i++) {
item = scheduledPoolItems.get(i);
this.onHandlePoolItem(item);
pool.recyclePoolItem(item);
}
scheduledPoolItems.clear();
}
}
}
@Override
public void reset() {
final ArrayList<T> scheduledPoolItems = this.mScheduledPoolItems;
synchronized (scheduledPoolItems) {
final int count = scheduledPoolItems.size();
final Pool<T> pool = this.mPool;
for(int i = count - 1; i >= 0; i--) {
pool.recyclePoolItem(scheduledPoolItems.get(i));
}
scheduledPoolItems.clear();
}
}
// ===========================================================
// Methods
// ===========================================================
public T obtainPoolItem() {
return this.mPool.obtainPoolItem();
}
public void postPoolItem(final T pPoolItem) {
synchronized (this.mScheduledPoolItems) {
if(pPoolItem == null) {
throw new IllegalArgumentException("PoolItem already recycled!");
} else if(!this.mPool.ownsPoolItem(pPoolItem)) {
throw new IllegalArgumentException("PoolItem from another pool!");
}
this.mScheduledPoolItems.add(pPoolItem);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/pool/PoolUpdateHandler.java | Java | lgpl | 3,727 |
package org.anddev.andengine.util.pool;
/**
* @author Valentin Milea
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
*
* @since 23:02:47 - 21.08.2010
*/
public abstract class PoolItem {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
Pool<? extends PoolItem> mParent;
boolean mRecycled = true;
// ===========================================================
// Constructors
// ===========================================================
public Pool<? extends PoolItem> getParent() {
return this.mParent;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isRecycled() {
return this.mRecycled;
}
public boolean isFromPool(final Pool<? extends PoolItem> pPool) {
return pPool == this.mParent;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
protected void onRecycle() {
}
protected void onObtain() {
}
public void recycle() {
if(this.mParent == null) {
throw new IllegalStateException("Item already recycled!");
}
this.mParent.recycle(this);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | zzy421-andengine | src/org/anddev/andengine/util/pool/PoolItem.java | Java | lgpl | 1,875 |
package org.anddev.andengine.util.pool;
import android.util.SparseArray;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:13:26 - 02.03.2011
*/
public class MultiPool<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final SparseArray<GenericPool<T>> mPools = new SparseArray<GenericPool<T>>();
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void registerPool(final int pID, final GenericPool<T> pPool) {
this.mPools.put(pID, pPool);
}
public T obtainPoolItem(final int pID) {
final GenericPool<T> pool = this.mPools.get(pID);
if(pool == null) {
return null;
} else {
return pool.obtainPoolItem();
}
}
public void recyclePoolItem(final int pID, final T pItem) {
final GenericPool<T> pool = this.mPools.get(pID);
if(pool != null) {
pool.recyclePoolItem(pItem);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/pool/MultiPool.java | Java | lgpl | 1,894 |
package org.anddev.andengine.util.pool;
import java.util.Collections;
import java.util.Stack;
import org.anddev.andengine.util.Debug;
/**
* @author Valentin Milea
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
*
* @since 22:19:55 - 31.08.2010
* @param <T>
*/
public abstract class GenericPool<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final Stack<T> mAvailableItems = new Stack<T>();
private int mUnrecycledCount;
private final int mGrowth;
// ===========================================================
// Constructors
// ===========================================================
public GenericPool() {
this(0);
}
public GenericPool(final int pInitialSize) {
this(pInitialSize, 1);
}
public GenericPool(final int pInitialSize, final int pGrowth) {
if(pGrowth < 0) {
throw new IllegalArgumentException("pGrowth must be at least 0!");
}
this.mGrowth = pGrowth;
if(pInitialSize > 0) {
this.batchAllocatePoolItems(pInitialSize);
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
public synchronized int getUnrecycledCount() {
return this.mUnrecycledCount;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract T onAllocatePoolItem();
// ===========================================================
// Methods
// ===========================================================
/**
* @param pItem every item passes this method just before it gets recycled.
*/
protected void onHandleRecycleItem(final T pItem) {
}
protected T onHandleAllocatePoolItem() {
return this.onAllocatePoolItem();
}
/**
* @param pItem every item that was just obtained from the pool, passes this method.
*/
protected void onHandleObtainItem(final T pItem) {
}
public synchronized void batchAllocatePoolItems(final int pCount) {
final Stack<T> availableItems = this.mAvailableItems;
for(int i = pCount - 1; i >= 0; i--) {
availableItems.push(this.onHandleAllocatePoolItem());
}
}
public synchronized T obtainPoolItem() {
final T item;
if(this.mAvailableItems.size() > 0) {
item = this.mAvailableItems.pop();
} else {
if(this.mGrowth == 1) {
item = this.onHandleAllocatePoolItem();
} else {
this.batchAllocatePoolItems(this.mGrowth);
item = this.mAvailableItems.pop();
}
Debug.i(this.getClass().getName() + "<" + item.getClass().getSimpleName() +"> was exhausted, with " + this.mUnrecycledCount + " item not yet recycled. Allocated " + this.mGrowth + " more.");
}
this.onHandleObtainItem(item);
this.mUnrecycledCount++;
return item;
}
public synchronized void recyclePoolItem(final T pItem) {
if(pItem == null) {
throw new IllegalArgumentException("Cannot recycle null item!");
}
this.onHandleRecycleItem(pItem);
this.mAvailableItems.push(pItem);
this.mUnrecycledCount--;
if(this.mUnrecycledCount < 0) {
Debug.e("More items recycled than obtained!");
}
}
public synchronized void shufflePoolItems() {
Collections.shuffle(this.mAvailableItems);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/pool/GenericPool.java | Java | lgpl | 3,821 |
package org.anddev.andengine.util.pool;
/**
* @author Valentin Milea
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
*
* @since 23:03:58 - 21.08.2010
* @param <T>
*/
public abstract class RunnablePoolUpdateHandler<T extends RunnablePoolItem> extends PoolUpdateHandler<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public RunnablePoolUpdateHandler() {
}
public RunnablePoolUpdateHandler(final int pInitialPoolSize) {
super(pInitialPoolSize);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected abstract T onAllocatePoolItem();
@Override
protected void onHandlePoolItem(final T pRunnablePoolItem) {
pRunnablePoolItem.run();
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/pool/RunnablePoolUpdateHandler.java | Java | lgpl | 1,725 |
package org.anddev.andengine.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.os.Environment;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:53:33 - 20.06.2010
*/
public class FileUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void copyToExternalStorage(final Context pContext, final int pSourceResourceID, final String pFilename) throws FileNotFoundException {
FileUtils.copyToExternalStorage(pContext, pContext.getResources().openRawResource(pSourceResourceID), pFilename);
}
public static void copyToInternalStorage(final Context pContext, final int pSourceResourceID, final String pFilename) throws FileNotFoundException {
FileUtils.copyToInternalStorage(pContext, pContext.getResources().openRawResource(pSourceResourceID), pFilename);
}
public static void copyToExternalStorage(final Context pContext, final String pSourceAssetPath, final String pFilename) throws IOException {
FileUtils.copyToExternalStorage(pContext, pContext.getAssets().open(pSourceAssetPath), pFilename);
}
public static void copyToInternalStorage(final Context pContext, final String pSourceAssetPath, final String pFilename) throws IOException {
FileUtils.copyToInternalStorage(pContext, pContext.getAssets().open(pSourceAssetPath), pFilename);
}
private static void copyToInternalStorage(final Context pContext, final InputStream pInputStream, final String pFilename) throws FileNotFoundException {
StreamUtils.copyAndClose(pInputStream, new FileOutputStream(new File(pContext.getFilesDir(), pFilename)));
}
public static void copyToExternalStorage(final Context pContext, final InputStream pInputStream, final String pFilePath) throws FileNotFoundException {
if (FileUtils.isExternalStorageWriteable()) {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
StreamUtils.copyAndClose(pInputStream, new FileOutputStream(absoluteFilePath));
} else {
throw new IllegalStateException("External Storage is not writeable.");
}
}
public static boolean isFileExistingOnExternalStorage(final Context pContext, final String pFilePath) {
if (FileUtils.isExternalStorageReadable()) {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
final File file = new File(absoluteFilePath);
return file.exists()&& file.isFile();
} else {
throw new IllegalStateException("External Storage is not readable.");
}
}
public static boolean isDirectoryExistingOnExternalStorage(final Context pContext, final String pDirectory) {
if (FileUtils.isExternalStorageReadable()) {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pDirectory);
final File file = new File(absoluteFilePath);
return file.exists() && file.isDirectory();
} else {
throw new IllegalStateException("External Storage is not readable.");
}
}
public static boolean ensureDirectoriesExistOnExternalStorage(final Context pContext, final String pDirectory) {
if(FileUtils.isDirectoryExistingOnExternalStorage(pContext, pDirectory)) {
return true;
}
if (FileUtils.isExternalStorageWriteable()) {
final String absoluteDirectoryPath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pDirectory);
return new File(absoluteDirectoryPath).mkdirs();
} else {
throw new IllegalStateException("External Storage is not writeable.");
}
}
public static InputStream openOnExternalStorage(final Context pContext, final String pFilePath) throws FileNotFoundException {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
return new FileInputStream(absoluteFilePath);
}
public static String[] getDirectoryListOnExternalStorage(final Context pContext, final String pFilePath) throws FileNotFoundException {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
return new File(absoluteFilePath).list();
}
public static String[] getDirectoryListOnExternalStorage(final Context pContext, final String pFilePath, final FilenameFilter pFilenameFilter) throws FileNotFoundException {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
return new File(absoluteFilePath).list(pFilenameFilter);
}
public static String getAbsolutePathOnInternalStorage(final Context pContext, final String pFilePath) {
return pContext.getFilesDir().getAbsolutePath() + pFilePath;
}
public static String getAbsolutePathOnExternalStorage(final Context pContext, final String pFilePath) {
return Environment.getExternalStorageDirectory() + "/Android/data/" + pContext.getApplicationInfo().packageName + "/files/" + pFilePath;
}
public static boolean isExternalStorageWriteable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public static boolean isExternalStorageReadable() {
final String state = Environment.getExternalStorageState();
return state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
}
public static void copyFile(final File pIn, final File pOut) throws IOException {
final FileInputStream fis = new FileInputStream(pIn);
final FileOutputStream fos = new FileOutputStream(pOut);
try {
StreamUtils.copy(fis, fos);
} finally {
StreamUtils.close(fis);
StreamUtils.close(fos);
}
}
/**
* Deletes all files and sub-directories under <code>dir</code>. Returns
* true if all deletions were successful. If a deletion fails, the method
* stops attempting to delete and returns false.
*
* @param pFileOrDirectory
* @return
*/
public static boolean deleteDirectory(final File pFileOrDirectory) {
if(pFileOrDirectory.isDirectory()) {
final String[] children = pFileOrDirectory.list();
final int childrenCount = children.length;
for(int i = 0; i < childrenCount; i++) {
final boolean success = FileUtils.deleteDirectory(new File(pFileOrDirectory, children[i]));
if(!success) {
return false;
}
}
}
// The directory is now empty so delete it
return pFileOrDirectory.delete();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/FileUtils.java | Java | lgpl | 7,600 |
package org.anddev.andengine.util;
import org.anddev.andengine.util.constants.Constants;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 18:55:12 - 02.08.2010
*/
public class SimplePreferences implements Constants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static SharedPreferences INSTANCE;
private static Editor EDITORINSTANCE;
// ===========================================================
// Constructors
// ===========================================================
public static SharedPreferences getInstance(final Context pContext) {
if(SimplePreferences.INSTANCE == null) {
SimplePreferences.INSTANCE = PreferenceManager.getDefaultSharedPreferences(pContext);
}
return SimplePreferences.INSTANCE;
}
public static Editor getEditorInstance(final Context pContext) {
if(SimplePreferences.EDITORINSTANCE == null) {
SimplePreferences.EDITORINSTANCE = SimplePreferences.getInstance(pContext).edit();
}
return SimplePreferences.EDITORINSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static int incrementAccessCount(final Context pContext, final String pKey) {
return SimplePreferences.incrementAccessCount(pContext, pKey, 1);
}
public static int incrementAccessCount(final Context pContext, final String pKey, final int pIncrement) {
final SharedPreferences prefs = SimplePreferences.getInstance(pContext);
final int accessCount = prefs.getInt(pKey, 0);
final int newAccessCount = accessCount + pIncrement;
prefs.edit().putInt(pKey, newAccessCount).commit();
return newAccessCount;
}
public static int getAccessCount(final Context pCtx, final String pKey) {
return SimplePreferences.getInstance(pCtx).getInt(pKey, 0);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/SimplePreferences.java | Java | lgpl | 2,825 |
package org.anddev.andengine.util;
import java.util.ArrayList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:20:08 - 27.12.2010
*/
public class SmartList<T> extends ArrayList<T> {
// ===========================================================
// Constants
// ===========================================================
private static final long serialVersionUID = -8335986399182700102L;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public SmartList() {
}
public SmartList(final int pCapacity) {
super(pCapacity);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
/**
* @param pItem the item to remove.
* @param pParameterCallable to be called with the removed item, if it was removed.
*/
public boolean remove(final T pItem, final ParameterCallable<T> pParameterCallable) {
final boolean removed = this.remove(pItem);
if(removed) {
pParameterCallable.call(pItem);
}
return removed;
}
public T remove(final IMatcher<T> pMatcher) {
for(int i = 0; i < this.size(); i++) {
if(pMatcher.matches(this.get(i))) {
return this.remove(i);
}
}
return null;
}
public T remove(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) {
for(int i = this.size() - 1; i >= 0; i--) {
if(pMatcher.matches(this.get(i))) {
final T removed = this.remove(i);
pParameterCallable.call(removed);
return removed;
}
}
return null;
}
public boolean removeAll(final IMatcher<T> pMatcher) {
boolean result = false;
for(int i = this.size() - 1; i >= 0; i--) {
if(pMatcher.matches(this.get(i))) {
this.remove(i);
result = true;
}
}
return result;
}
/**
* @param pMatcher to find the items.
* @param pParameterCallable to be called with each matched item after it was removed.
*/
public boolean removeAll(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) {
boolean result = false;
for(int i = this.size() - 1; i >= 0; i--) {
if(pMatcher.matches(this.get(i))) {
final T removed = this.remove(i);
pParameterCallable.call(removed);
result = true;
}
}
return result;
}
public void clear(final ParameterCallable<T> pParameterCallable) {
for(int i = this.size() - 1; i >= 0; i--) {
final T removed = this.remove(i);
pParameterCallable.call(removed);
}
}
public T find(final IMatcher<T> pMatcher) {
for(int i = this.size() - 1; i >= 0; i--) {
final T item = this.get(i);
if(pMatcher.matches(item)) {
return item;
}
}
return null;
}
public void call(final ParameterCallable<T> pParameterCallable) {
for(int i = this.size() - 1; i >= 0; i--) {
final T item = this.get(i);
pParameterCallable.call(item);
}
}
public void call(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) {
for(int i = this.size() - 1; i >= 0; i--) {
final T item = this.get(i);
if(pMatcher.matches(item)) {
pParameterCallable.call(item);
}
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/SmartList.java | Java | lgpl | 3,968 |
package org.anddev.andengine.util;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:55:35 - 08.09.2009
*/
public class ViewUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static View inflate(final Context pContext, final int pLayoutID){
return LayoutInflater.from(pContext).inflate(pLayoutID, null);
}
public static View inflate(final Context pContext, final int pLayoutID, final ViewGroup pViewGroup){
return LayoutInflater.from(pContext).inflate(pLayoutID, pViewGroup, true);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/ViewUtils.java | Java | lgpl | 1,742 |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:15:23 - 24.07.2010
*/
public enum VerticalAlign {
// ===========================================================
// Elements
// ===========================================================
TOP,
CENTER,
BOTTOM;
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/VerticalAlign.java | Java | lgpl | 1,451 |
package org.anddev.andengine.util.sort;
import java.util.Comparator;
import java.util.List;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:14:31 - 06.08.2010
* @param <T>
*/
public class InsertionSorter<T> extends Sorter<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void sort(final T[] pArray, final int pStart, final int pEnd, final Comparator<T> pComparator) {
for(int i = pStart + 1; i < pEnd; i++) {
final T current = pArray[i];
T prev = pArray[i - 1];
if(pComparator.compare(current, prev) < 0) {
int j = i;
do {
pArray[j--] = prev;
} while(j > pStart && pComparator.compare(current, prev = pArray[j - 1]) < 0);
pArray[j] = current;
}
}
return;
}
@Override
public void sort(final List<T> pList, final int pStart, final int pEnd, final Comparator<T> pComparator) {
for(int i = pStart + 1; i < pEnd; i++) {
final T current = pList.get(i);
T prev = pList.get(i - 1);
if(pComparator.compare(current, prev) < 0) {
int j = i;
do {
pList.set(j--, prev);
} while(j > pStart && pComparator.compare(current, prev = pList.get(j - 1)) < 0);
pList.set(j, current);
}
}
return;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | zzy421-andengine | src/org/anddev/andengine/util/sort/InsertionSorter.java | Java | lgpl | 2,318 |
package org.anddev.andengine.util.sort;
import java.util.Comparator;
import java.util.List;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:14:39 - 06.08.2010
* @param <T>
*/
public abstract class Sorter<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
public abstract void sort(final T[] pArray, final int pStart, final int pEnd, final Comparator<T> pComparator);
public abstract void sort(final List<T> pList, final int pStart, final int pEnd, final Comparator<T> pComparator);
// ===========================================================
// Methods
// ===========================================================
public final void sort(final T[] pArray, final Comparator<T> pComparator){
this.sort(pArray, 0, pArray.length, pComparator);
}
public final void sort(final List<T> pList, final Comparator<T> pComparator){
this.sort(pList, 0, pList.size(), pComparator);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/sort/Sorter.java | Java | lgpl | 1,870 |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:47:33 - 11.05.2010
*/
public enum HorizontalAlign {
// ===========================================================
// Elements
// ===========================================================
LEFT,
CENTER,
RIGHT;
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/HorizontalAlign.java | Java | lgpl | 1,453 |
package org.anddev.andengine.util;
import java.util.concurrent.Callable;
import org.anddev.andengine.ui.activity.BaseActivity.CancelledException;
import org.anddev.andengine.util.progress.IProgressListener;
import org.anddev.andengine.util.progress.ProgressCallable;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.view.Window;
import android.view.WindowManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 18:11:54 - 07.03.2011
*/
public class ActivityUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void requestFullscreen(final Activity pActivity) {
final Window window = pActivity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
window.requestFeature(Window.FEATURE_NO_TITLE);
}
/**
* @param pActivity
* @param pScreenBrightness [0..1]
*/
public static void setScreenBrightness(final Activity pActivity, final float pScreenBrightness) {
final Window window = pActivity.getWindow();
final WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
windowLayoutParams.screenBrightness = pScreenBrightness;
window.setAttributes(windowLayoutParams);
}
public static void keepScreenOn(final Activity pActivity) {
pActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback) {
ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, null, false);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback) {
ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, false);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final boolean pCancelable) {
ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, null, pCancelable);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final boolean pCancelable) {
ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, pCancelable);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, pExceptionCallback, false);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, pExceptionCallback, false);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback, final boolean pCancelable) {
ActivityUtils.doAsync(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID), pCallable, pCallback, pExceptionCallback, pCancelable);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback, final boolean pCancelable) {
new AsyncTask<Void, Void, T>() {
private ProgressDialog mPD;
private Exception mException = null;
@Override
public void onPreExecute() {
this.mPD = ProgressDialog.show(pContext, pTitle, pMessage, true, pCancelable);
if(pCancelable) {
this.mPD.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(final DialogInterface pDialogInterface) {
pExceptionCallback.onCallback(new CancelledException());
pDialogInterface.dismiss();
}
});
}
super.onPreExecute();
}
@Override
public T doInBackground(final Void... params) {
try {
return pCallable.call();
} catch (final Exception e) {
this.mException = e;
}
return null;
}
@Override
public void onPostExecute(final T result) {
try {
this.mPD.dismiss();
} catch (final Exception e) {
Debug.e("Error", e);
}
if(this.isCancelled()) {
this.mException = new CancelledException();
}
if(this.mException == null) {
pCallback.onCallback(result);
} else {
if(pExceptionCallback == null) {
Debug.e("Error", this.mException);
} else {
pExceptionCallback.onCallback(this.mException);
}
}
super.onPostExecute(result);
}
}.execute((Void[]) null);
}
public static <T> void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback) {
ActivityUtils.doProgressAsync(pContext, pTitleResID, pCallable, pCallback, null);
}
public static <T> void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
new AsyncTask<Void, Integer, T>() {
private ProgressDialog mPD;
private Exception mException = null;
@Override
public void onPreExecute() {
this.mPD = new ProgressDialog(pContext);
this.mPD.setTitle(pTitleResID);
this.mPD.setIcon(android.R.drawable.ic_menu_save);
this.mPD.setIndeterminate(false);
this.mPD.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.mPD.show();
super.onPreExecute();
}
@Override
public T doInBackground(final Void... params) {
try {
return pCallable.call(new IProgressListener() {
@Override
public void onProgressChanged(final int pProgress) {
onProgressUpdate(pProgress);
}
});
} catch (final Exception e) {
this.mException = e;
}
return null;
}
@Override
public void onProgressUpdate(final Integer... values) {
this.mPD.setProgress(values[0]);
}
@Override
public void onPostExecute(final T result) {
try {
this.mPD.dismiss();
} catch (final Exception e) {
Debug.e("Error", e);
/* Nothing. */
}
if(this.isCancelled()) {
this.mException = new CancelledException();
}
if(this.mException == null) {
pCallback.onCallback(result);
} else {
if(pExceptionCallback == null) {
Debug.e("Error", this.mException);
} else {
pExceptionCallback.onCallback(this.mException);
}
}
super.onPostExecute(result);
}
}.execute((Void[]) null);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final AsyncCallable<T> pAsyncCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
final ProgressDialog pd = ProgressDialog.show(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID));
pAsyncCallable.call(new Callback<T>() {
@Override
public void onCallback(final T result) {
try {
pd.dismiss();
} catch (final Exception e) {
Debug.e("Error", e);
/* Nothing. */
}
pCallback.onCallback(result);
}
}, pExceptionCallback);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/ActivityUtils.java | Java | lgpl | 9,148 |
package org.anddev.andengine.util.path;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:00:24 - 16.08.2010
*/
public interface ITiledMap<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
public int getTileColumns();
public int getTileRows();
public void onTileVisitedByPathFinder(final int pTileColumn, int pTileRow);
public boolean isTileBlocked(final T pEntity, final int pTileColumn, final int pTileRow);
public float getStepCost(final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow);
}
| zzy421-andengine | src/org/anddev/andengine/util/path/ITiledMap.java | Java | lgpl | 880 |
package org.anddev.andengine.util.path;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:19:11 - 17.08.2010
*/
public enum Direction {
// ===========================================================
// Elements
// ===========================================================
UP(0, -1), DOWN(0, 1), LEFT(-1, 0), RIGHT(1, 0);
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int mDeltaX;
private final int mDeltaY;
// ===========================================================
// Constructors
// ===========================================================
private Direction(final int pDeltaX, final int pDeltaY) {
this.mDeltaX = pDeltaX;
this.mDeltaY = pDeltaY;
}
public static Direction fromDelta(final int pDeltaX, final int pDeltaY) {
if(pDeltaX == 0) {
if(pDeltaY == 1) {
return DOWN;
} else if(pDeltaY == -1) {
return UP;
}
} else if (pDeltaY == 0) {
if(pDeltaX == 1) {
return RIGHT;
} else if(pDeltaX == -1) {
return LEFT;
}
}
throw new IllegalArgumentException();
}
// ===========================================================
// Getter & Setter
// ===========================================================
public int getDeltaX() {
return this.mDeltaX;
}
public int getDeltaY() {
return this.mDeltaY;
}
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/path/Direction.java | Java | lgpl | 2,141 |
package org.anddev.andengine.util.path;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:57:13 - 16.08.2010
*/
public interface IPathFinder<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
public Path findPath(final T pEntity, final int pMaxCost, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow);
}
| zzy421-andengine | src/org/anddev/andengine/util/path/IPathFinder.java | Java | lgpl | 663 |
package org.anddev.andengine.util.path.astar;
import org.anddev.andengine.util.path.ITiledMap;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:58:01 - 16.08.2010
*/
public class ManhattanHeuristic<T> implements IAStarHeuristic<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getExpectedRestCost(final ITiledMap<T> pTiledMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) {
return Math.abs(pTileFromX - pTileToX) + Math.abs(pTileToX - pTileToY);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/path/astar/ManhattanHeuristic.java | Java | lgpl | 1,643 |
package org.anddev.andengine.util.path.astar;
import org.anddev.andengine.util.path.ITiledMap;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:58:01 - 16.08.2010
*/
public class EuclideanHeuristic<T> implements IAStarHeuristic<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getExpectedRestCost(final ITiledMap<T> pTileMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) {
final float dX = pTileToX - pTileFromX;
final float dY = pTileToY - pTileFromY;
return FloatMath.sqrt(dX * dX + dY * dY);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/path/astar/EuclideanHeuristic.java | Java | lgpl | 1,734 |
package org.anddev.andengine.util.path.astar;
import org.anddev.andengine.util.path.ITiledMap;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:58:01 - 16.08.2010
*/
public class NullHeuristic<T> implements IAStarHeuristic<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getExpectedRestCost(final ITiledMap<T> pTiledMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) {
return 0;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/path/astar/NullHeuristic.java | Java | lgpl | 1,576 |
package org.anddev.andengine.util.path.astar;
import org.anddev.andengine.util.path.ITiledMap;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:59:20 - 16.08.2010
*/
public interface IAStarHeuristic<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
public float getExpectedRestCost(final ITiledMap<T> pTiledMap, final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow);
}
| zzy421-andengine | src/org/anddev/andengine/util/path/astar/IAStarHeuristic.java | Java | lgpl | 747 |
package org.anddev.andengine.util.path.astar;
import java.util.ArrayList;
import java.util.Collections;
import org.anddev.andengine.util.path.IPathFinder;
import org.anddev.andengine.util.path.ITiledMap;
import org.anddev.andengine.util.path.Path;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:16:17 - 16.08.2010
*/
public class AStarPathFinder<T> implements IPathFinder<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final ArrayList<Node> mVisitedNodes = new ArrayList<Node>();
private final ArrayList<Node> mOpenNodes = new ArrayList<Node>();
private final ITiledMap<T> mTiledMap;
private final int mMaxSearchDepth;
private final Node[][] mNodes;
private final boolean mAllowDiagonalMovement;
private final IAStarHeuristic<T> mAStarHeuristic;
// ===========================================================
// Constructors
// ===========================================================
public AStarPathFinder(final ITiledMap<T> pTiledMap, final int pMaxSearchDepth, final boolean pAllowDiagonalMovement) {
this(pTiledMap, pMaxSearchDepth, pAllowDiagonalMovement, new EuclideanHeuristic<T>());
}
public AStarPathFinder(final ITiledMap<T> pTiledMap, final int pMaxSearchDepth, final boolean pAllowDiagonalMovement, final IAStarHeuristic<T> pAStarHeuristic) {
this.mAStarHeuristic = pAStarHeuristic;
this.mTiledMap = pTiledMap;
this.mMaxSearchDepth = pMaxSearchDepth;
this.mAllowDiagonalMovement = pAllowDiagonalMovement;
this.mNodes = new Node[pTiledMap.getTileRows()][pTiledMap.getTileColumns()];
final Node[][] nodes = this.mNodes;
for(int x = pTiledMap.getTileColumns() - 1; x >= 0; x--) {
for(int y = pTiledMap.getTileRows() - 1; y >= 0; y--) {
nodes[y][x] = new Node(x, y);
}
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Path findPath(final T pEntity, final int pMaxCost, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow) {
final ITiledMap<T> tiledMap = this.mTiledMap;
if(tiledMap.isTileBlocked(pEntity, pToTileColumn, pToTileRow)) {
return null;
}
/* Drag some fields to local variables. */
final ArrayList<Node> openNodes = this.mOpenNodes;
final ArrayList<Node> visitedNodes = this.mVisitedNodes;
final Node[][] nodes = this.mNodes;
final Node fromNode = nodes[pFromTileRow][pFromTileColumn];
final Node toNode = nodes[pToTileRow][pToTileColumn];
final IAStarHeuristic<T> aStarHeuristic = this.mAStarHeuristic;
final boolean allowDiagonalMovement = this.mAllowDiagonalMovement;
final int maxSearchDepth = this.mMaxSearchDepth;
/* Initialize algorithm. */
fromNode.mCost = 0;
fromNode.mDepth = 0;
toNode.mParent = null;
visitedNodes.clear();
openNodes.clear();
openNodes.add(fromNode);
int currentDepth = 0;
while(currentDepth < maxSearchDepth && !openNodes.isEmpty()) {
/* The first Node in the open list is the one with the lowest cost. */
final Node current = openNodes.remove(0);
if(current == toNode) {
break;
}
visitedNodes.add(current);
/* Loop over all neighbors of this tile. */
for(int dX = -1; dX <= 1; dX++) {
for(int dY = -1; dY <= 1; dY++) {
if((dX == 0) && (dY == 0)) {
continue;
}
if(!allowDiagonalMovement) {
if((dX != 0) && (dY != 0)) {
continue;
}
}
final int neighborTileColumn = dX + current.mTileColumn;
final int neighborTileRow = dY + current.mTileRow;
if(!this.isTileBlocked(pEntity, pFromTileColumn, pFromTileRow, neighborTileColumn, neighborTileRow)) {
final float neighborCost = current.mCost + tiledMap.getStepCost(pEntity, current.mTileColumn, current.mTileRow, neighborTileColumn, neighborTileRow);
final Node neighbor = nodes[neighborTileRow][neighborTileColumn];
tiledMap.onTileVisitedByPathFinder(neighborTileColumn, neighborTileRow);
/* Re-evaluate if there is a better path. */
if(neighborCost < neighbor.mCost) {
// TODO Is this ever possible with AStar ??
if(openNodes.contains(neighbor)) {
openNodes.remove(neighbor);
}
if(visitedNodes.contains(neighbor)) {
visitedNodes.remove(neighbor);
}
}
if(!openNodes.contains(neighbor) && !(visitedNodes.contains(neighbor))) {
neighbor.mCost = neighborCost;
if(neighbor.mCost <= pMaxCost) {
neighbor.mExpectedRestCost = aStarHeuristic.getExpectedRestCost(tiledMap, pEntity, neighborTileColumn, neighborTileRow, pToTileColumn, pToTileRow);
currentDepth = Math.max(currentDepth, neighbor.setParent(current));
openNodes.add(neighbor);
/* Ensure always the node with the lowest cost+heuristic
* will be used next, simply by sorting. */
Collections.sort(openNodes);
}
}
}
}
}
}
/* Check if a path was found. */
if(toNode.mParent == null) {
return null;
}
/* Traceback path. */
final Path path = new Path();
Node tmp = nodes[pToTileRow][pToTileColumn];
while(tmp != fromNode) {
path.prepend(tmp.mTileColumn, tmp.mTileRow);
tmp = tmp.mParent;
}
path.prepend(pFromTileColumn, pFromTileRow);
return path;
}
// ===========================================================
// Methods
// ===========================================================
protected boolean isTileBlocked(final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow) {
if((pToTileColumn < 0) || (pToTileRow < 0) || (pToTileColumn >= this.mTiledMap.getTileColumns()) || (pToTileRow >= this.mTiledMap.getTileRows())) {
return true;
} else if((pFromTileColumn == pToTileColumn) && (pFromTileRow == pToTileRow)) {
return true;
}
return this.mTiledMap.isTileBlocked(pEntity, pToTileColumn, pToTileRow);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
private static class Node implements Comparable<Node> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
Node mParent;
int mDepth;
final int mTileColumn;
final int mTileRow;
float mCost;
float mExpectedRestCost;
// ===========================================================
// Constructors
// ===========================================================
public Node(final int pTileColumn, final int pTileRow) {
this.mTileColumn = pTileColumn;
this.mTileRow = pTileRow;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public int setParent(final Node parent) {
this.mDepth = parent.mDepth + 1;
this.mParent = parent;
return this.mDepth;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public int compareTo(final Node pOther) {
final float totalCost = this.mExpectedRestCost + this.mCost;
final float totalCostOther = pOther.mExpectedRestCost + pOther.mCost;
if (totalCost < totalCostOther) {
return -1;
} else if (totalCost > totalCostOther) {
return 1;
} else {
return 0;
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
}
| zzy421-andengine | src/org/anddev/andengine/util/path/astar/AStarPathFinder.java | Java | lgpl | 8,670 |
package org.anddev.andengine.util.path;
import java.util.ArrayList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:00:24 - 16.08.2010
*/
public class Path {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final ArrayList<Step> mSteps = new ArrayList<Step>();
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public int getLength() {
return this.mSteps.size();
}
public Step getStep(final int pIndex) {
return this.mSteps.get(pIndex);
}
public Direction getDirectionToPreviousStep(final int pIndex) {
if(pIndex == 0) {
return null;
} else {
final int dX = this.getTileColumn(pIndex - 1) - this.getTileColumn(pIndex);
final int dY = this.getTileRow(pIndex - 1) - this.getTileRow(pIndex);
return Direction.fromDelta(dX, dY);
}
}
public Direction getDirectionToNextStep(final int pIndex) {
if(pIndex == this.getLength() - 1) {
return null;
} else {
final int dX = this.getTileColumn(pIndex + 1) - this.getTileColumn(pIndex);
final int dY = this.getTileRow(pIndex + 1) - this.getTileRow(pIndex);
return Direction.fromDelta(dX, dY);
}
}
public int getTileColumn(final int pIndex) {
return this.getStep(pIndex).getTileColumn();
}
public int getTileRow(final int pIndex) {
return this.getStep(pIndex).getTileRow();
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void append(final int pTileColumn, final int pTileRow) {
this.append(new Step(pTileColumn, pTileRow));
}
public void append(final Step pStep) {
this.mSteps.add(pStep);
}
public void prepend(final int pTileColumn, final int pTileRow) {
this.prepend(new Step(pTileColumn, pTileRow));
}
public void prepend(final Step pStep) {
this.mSteps.add(0, pStep);
}
public boolean contains(final int pTileColumn, final int pTileRow) {
final ArrayList<Step> steps = this.mSteps;
for(int i = steps.size() - 1; i >= 0; i--) {
final Step step = steps.get(i);
if(step.getTileColumn() == pTileColumn && step.getTileRow() == pTileRow) {
return true;
}
}
return false;
}
public int getFromTileRow() {
return this.getTileRow(0);
}
public int getFromTileColumn() {
return this.getTileColumn(0);
}
public int getToTileRow() {
return this.getTileRow(this.mSteps.size() - 1);
}
public int getToTileColumn() {
return this.getTileColumn(this.mSteps.size() - 1);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public class Step {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int mTileColumn;
private final int mTileRow;
// ===========================================================
// Constructors
// ===========================================================
public Step(final int pTileColumn, final int pTileRow) {
this.mTileColumn = pTileColumn;
this.mTileRow = pTileRow;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public int getTileColumn() {
return this.mTileColumn;
}
public int getTileRow() {
return this.mTileRow;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public int hashCode() {
return this.mTileColumn << 16 + this.mTileRow;
}
@Override
public boolean equals(final Object pOther) {
if(this == pOther) {
return true;
}
if(pOther == null) {
return false;
}
if(this.getClass() != pOther.getClass()) {
return false;
}
final Step other = (Step) pOther;
if(this.mTileColumn != other.mTileColumn) {
return false;
}
if(this.mTileRow != other.mTileRow) {
return false;
}
return true;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
}
| zzy421-andengine | src/org/anddev/andengine/util/path/Path.java | Java | lgpl | 5,414 |
package org.anddev.andengine.util;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.util.Scanner;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:48:56 - 03.09.2009
*/
public class StreamUtils {
// ===========================================================
// Constants
// ===========================================================
public static final int IO_BUFFER_SIZE = 8 * 1024;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static final String readFully(final InputStream pInputStream) throws IOException {
final StringBuilder sb = new StringBuilder();
final Scanner sc = new Scanner(pInputStream);
while(sc.hasNextLine()) {
sb.append(sc.nextLine());
}
return sb.toString();
}
public static byte[] streamToBytes(final InputStream pInputStream) throws IOException {
return StreamUtils.streamToBytes(pInputStream, -1);
}
public static byte[] streamToBytes(final InputStream pInputStream, final int pReadLimit) throws IOException {
final ByteArrayOutputStream os = new ByteArrayOutputStream((pReadLimit == -1) ? IO_BUFFER_SIZE : pReadLimit);
StreamUtils.copy(pInputStream, os, pReadLimit);
return os.toByteArray();
}
public static void copy(final InputStream pInputStream, final OutputStream pOutputStream) throws IOException {
StreamUtils.copy(pInputStream, pOutputStream, -1);
}
public static void copy(final InputStream pInputStream, final byte[] pData) throws IOException {
int dataOffset = 0;
final byte[] buf = new byte[IO_BUFFER_SIZE];
int read;
while((read = pInputStream.read(buf)) != -1) {
System.arraycopy(buf, 0, pData, dataOffset, read);
dataOffset += read;
}
}
public static void copy(final InputStream pInputStream, final ByteBuffer pByteBuffer) throws IOException {
final byte[] buf = new byte[IO_BUFFER_SIZE];
int read;
while((read = pInputStream.read(buf)) != -1) {
pByteBuffer.put(buf, 0, read);
}
}
/**
* Copy the content of the input stream into the output stream, using a temporary
* byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}.
*
* @param pInputStream The input stream to copy from.
* @param pOutputStream The output stream to copy to.
* @param pByteLimit not more than so much bytes to read, or unlimited if smaller than 0.
*
* @throws IOException If any error occurs during the copy.
*/
public static void copy(final InputStream pInputStream, final OutputStream pOutputStream, final long pByteLimit) throws IOException {
if(pByteLimit < 0) {
final byte[] buf = new byte[IO_BUFFER_SIZE];
int read;
while((read = pInputStream.read(buf)) != -1) {
pOutputStream.write(buf, 0, read);
}
} else {
final byte[] buf = new byte[IO_BUFFER_SIZE];
final int bufferReadLimit = Math.min((int)pByteLimit, IO_BUFFER_SIZE);
long pBytesLeftToRead = pByteLimit;
int read;
while((read = pInputStream.read(buf, 0, bufferReadLimit)) != -1) {
if(pBytesLeftToRead > read) {
pOutputStream.write(buf, 0, read);
pBytesLeftToRead -= read;
} else {
pOutputStream.write(buf, 0, (int) pBytesLeftToRead);
break;
}
}
}
pOutputStream.flush();
}
public static boolean copyAndClose(final InputStream pInputStream, final OutputStream pOutputStream) {
try {
StreamUtils.copy(pInputStream, pOutputStream, -1);
return true;
} catch (final IOException e) {
return false;
} finally {
StreamUtils.close(pInputStream);
StreamUtils.close(pOutputStream);
}
}
/**
* Closes the specified stream.
*
* @param pCloseable The stream to close.
*/
public static void close(final Closeable pCloseable) {
if(pCloseable != null) {
try {
pCloseable.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
/**
* Flushes and closes the specified stream.
*
* @param pOutputStream The stream to close.
*/
public static void flushCloseStream(final OutputStream pOutputStream) {
if(pOutputStream != null) {
try {
pOutputStream.flush();
} catch (final IOException e) {
e.printStackTrace();
} finally {
StreamUtils.close(pOutputStream);
}
}
}
/**
* Flushes and closes the specified stream.
*
* @param pWriter The Writer to close.
*/
public static void flushCloseWriter(final Writer pWriter) {
if(pWriter != null) {
try {
pWriter.flush();
} catch (final IOException e) {
e.printStackTrace();
} finally {
StreamUtils.close(pWriter);
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/StreamUtils.java | Java | lgpl | 5,723 |
package org.anddev.andengine.util;
import android.util.FloatMath;
/**
* <p>This class is basically a java-space replacement for the native {@link android.graphics.Matrix} class.</p>
*
* <p>Math taken from <a href="http://www.senocular.com/flash/tutorials/transformmatrix/">senocular.com</a>.</p>
*
* This class represents an affine transformation with the following matrix:
* <pre> [ a , b , 0 ]
* [ c , d , 0 ]
* [ tx, ty, 1 ]</pre>
* where:
* <ul>
* <li><b>a</b> is the <b>x scale</b></li>
* <li><b>b</b> is the <b>y skew</b></li>
* <li><b>c</b> is the <b>x skew</b></li>
* <li><b>d</b> is the <b>y scale</b></li>
* <li><b>tx</b> is the <b>x translation</b></li>
* <li><b>ty</b> is the <b>y translation</b></li>
* </ul>
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:47:18 - 23.12.2010
*/
public class Transformation {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float a = 1.0f; /* x scale */
private float b = 0.0f; /* y skew */
private float c = 0.0f; /* x skew */
private float d = 1.0f; /* y scale */
private float tx = 0.0f; /* x translation */
private float ty = 0.0f; /* y translation */
// ===========================================================
// Constructors
// ===========================================================
public Transformation() {
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public String toString() {
return "Transformation{[" + this.a + ", " + this.c + ", " + this.tx + "][" + this.b + ", " + this.d + ", " + this.ty + "][0.0, 0.0, 1.0]}";
}
// ===========================================================
// Methods
// ===========================================================
public void reset() {
this.setToIdentity();
}
public void setToIdentity() {
this.a = 1.0f;
this.d = 1.0f;
this.b = 0.0f;
this.c = 0.0f;
this.tx = 0.0f;
this.ty = 0.0f;
}
public void setTo(final Transformation pTransformation) {
this.a = pTransformation.a;
this.d = pTransformation.d;
this.b = pTransformation.b;
this.c = pTransformation.c;
this.tx = pTransformation.tx;
this.ty = pTransformation.ty;
}
public void preTranslate(final float pX, final float pY) {
this.tx += pX * this.a + pY * this.c;
this.ty += pX * this.b + pY * this.d;
}
public void postTranslate(final float pX, final float pY) {
this.tx += pX;
this.ty += pY;
}
public Transformation setToTranslate(final float pX, final float pY) {
this.a = 1.0f;
this.b = 0.0f;
this.c = 0.0f;
this.d = 1.0f;
this.tx = pX;
this.ty = pY;
return this;
}
public void preScale(final float pScaleX, final float pScaleY) {
this.a *= pScaleX;
this.b *= pScaleX;
this.c *= pScaleY;
this.d *= pScaleY;
}
public void postScale(final float pScaleX, final float pScaleY) {
this.a = this.a * pScaleX;
this.b = this.b * pScaleY;
this.c = this.c * pScaleX;
this.d = this.d * pScaleY;
this.tx = this.tx * pScaleX;
this.ty = this.ty * pScaleY;
}
public Transformation setToScale(final float pScaleX, final float pScaleY) {
this.a = pScaleX;
this.b = 0.0f;
this.c = 0.0f;
this.d = pScaleY;
this.tx = 0.0f;
this.ty = 0.0f;
return this;
}
public void preRotate(final float pAngle) {
final float angleRad = MathUtils.degToRad(pAngle);
final float sin = FloatMath.sin(angleRad);
final float cos = FloatMath.cos(angleRad);
final float a = this.a;
final float b = this.b;
final float c = this.c;
final float d = this.d;
this.a = cos * a + sin * c;
this.b = cos * b + sin * d;
this.c = cos * c - sin * a;
this.d = cos * d - sin * b;
}
public void postRotate(final float pAngle) {
final float angleRad = MathUtils.degToRad(pAngle);
final float sin = FloatMath.sin(angleRad);
final float cos = FloatMath.cos(angleRad);
final float a = this.a;
final float b = this.b;
final float c = this.c;
final float d = this.d;
final float tx = this.tx;
final float ty = this.ty;
this.a = a * cos - b * sin;
this.b = a * sin + b * cos;
this.c = c * cos - d * sin;
this.d = c * sin + d * cos;
this.tx = tx * cos - ty * sin;
this.ty = tx * sin + ty * cos;
}
public Transformation setToRotate(final float pAngle) {
final float angleRad = MathUtils.degToRad(pAngle);
final float sin = FloatMath.sin(angleRad);
final float cos = FloatMath.cos(angleRad);
this.a = cos;
this.b = sin;
this.c = -sin;
this.d = cos;
this.tx = 0.0f;
this.ty = 0.0f;
return this;
}
public void postConcat(final Transformation pTransformation) {
this.postConcat(pTransformation.a, pTransformation.b, pTransformation.c, pTransformation.d, pTransformation.tx, pTransformation.ty);
}
private void postConcat(final float pA, final float pB, final float pC, final float pD, final float pTX, final float pTY) {
final float a = this.a;
final float b = this.b;
final float c = this.c;
final float d = this.d;
final float tx = this.tx;
final float ty = this.ty;
this.a = a * pA + b * pC;
this.b = a * pB + b * pD;
this.c = c * pA + d * pC;
this.d = c * pB + d * pD;
this.tx = tx * pA + ty * pC + pTX;
this.ty = tx * pB + ty * pD + pTY;
}
public void preConcat(final Transformation pTransformation) {
this.preConcat(pTransformation.a, pTransformation.b, pTransformation.c, pTransformation.d, pTransformation.tx, pTransformation.ty);
}
private void preConcat(final float pA, final float pB, final float pC, final float pD, final float pTX, final float pTY) {
final float a = this.a;
final float b = this.b;
final float c = this.c;
final float d = this.d;
final float tx = this.tx;
final float ty = this.ty;
this.a = pA * a + pB * c;
this.b = pA * b + pB * d;
this.c = pC * a + pD * c;
this.d = pC * b + pD * d;
this.tx = pTX * a + pTY * c + tx;
this.ty = pTX * b + pTY * d + ty;
}
public void transform(final float[] pVertices) {
int count = pVertices.length >> 1;
int i = 0;
int j = 0;
while(--count >= 0) {
final float x = pVertices[i++];
final float y = pVertices[i++];
pVertices[j++] = x * this.a + y * this.c + this.tx;
pVertices[j++] = x * this.b + y * this.d + this.ty;
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | zzy421-andengine | src/org/anddev/andengine/util/Transformation.java | Java | lgpl | 7,118 |
package org.anddev.andengine.util;
import android.graphics.Color;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:13:45 - 04.08.2010
*/
public class ColorUtils {
// ===========================================================
// Constants
// ===========================================================
private static final float[] HSV_TO_COLOR = new float[3];
private static final int HSV_TO_COLOR_HUE_INDEX = 0;
private static final int HSV_TO_COLOR_SATURATION_INDEX = 1;
private static final int HSV_TO_COLOR_VALUE_INDEX = 2;
private static final int COLOR_FLOAT_TO_INT_FACTOR = 255;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
/**
* @param pHue [0 .. 360)
* @param pSaturation [0...1]
* @param pValue [0...1]
*/
public static int HSVToColor(final float pHue, final float pSaturation, final float pValue) {
HSV_TO_COLOR[HSV_TO_COLOR_HUE_INDEX] = pHue;
HSV_TO_COLOR[HSV_TO_COLOR_SATURATION_INDEX] = pSaturation;
HSV_TO_COLOR[HSV_TO_COLOR_VALUE_INDEX] = pValue;
return Color.HSVToColor(HSV_TO_COLOR);
}
public static int RGBToColor(final float pRed, final float pGreen, final float pBlue) {
return Color.rgb((int)(pRed * COLOR_FLOAT_TO_INT_FACTOR), (int)(pGreen * COLOR_FLOAT_TO_INT_FACTOR), (int)(pBlue * COLOR_FLOAT_TO_INT_FACTOR));
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/ColorUtils.java | Java | lgpl | 2,258 |
package org.anddev.andengine.util.levelstats;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.anddev.andengine.util.Callback;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.MathUtils;
import org.anddev.andengine.util.SimplePreferences;
import org.anddev.andengine.util.StreamUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.content.SharedPreferences;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 21:13:55 - 18.10.2010
*/
public class LevelStatsDBConnector {
// ===========================================================
// Constants
// ===========================================================
private static final String PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID = "preferences.levelstatsdbconnector.playerid";
// ===========================================================
// Fields
// ===========================================================
private final String mSecret;
private final String mSubmitURL;
private final int mPlayerID;
// ===========================================================
// Constructors
// ===========================================================
public LevelStatsDBConnector(final Context pContext, final String pSecret, final String pSubmitURL) {
this.mSecret = pSecret;
this.mSubmitURL = pSubmitURL;
final SharedPreferences simplePreferences = SimplePreferences.getInstance(pContext);
final int playerID = simplePreferences.getInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID, -1);
if(playerID != -1) {
this.mPlayerID = playerID;
} else {
this.mPlayerID = MathUtils.random(1000000000, Integer.MAX_VALUE);
SimplePreferences.getEditorInstance(pContext).putInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID, this.mPlayerID).commit();
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
public void submitAsync(final int pLevelID, final boolean pSolved, final int pSecondsElapsed) {
this.submitAsync(pLevelID, pSolved, pSecondsElapsed, null);
}
public void submitAsync(final int pLevelID, final boolean pSolved, final int pSecondsElapsed, final Callback<Boolean> pCallback) {
new Thread(new Runnable() {
@Override
public void run() {
try{
/* Create a new HttpClient and Post Header. */
final HttpClient httpClient = new DefaultHttpClient();
final HttpPost httpPost = new HttpPost(LevelStatsDBConnector.this.mSubmitURL);
/* Append POST data. */
final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("level_id", String.valueOf(pLevelID)));
nameValuePairs.add(new BasicNameValuePair("solved", (pSolved) ? "1" : "0"));
nameValuePairs.add(new BasicNameValuePair("secondsplayed", String.valueOf(pSecondsElapsed)));
nameValuePairs.add(new BasicNameValuePair("player_id", String.valueOf(LevelStatsDBConnector.this.mPlayerID)));
nameValuePairs.add(new BasicNameValuePair("secret", String.valueOf(LevelStatsDBConnector.this.mSecret)));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/* Execute HTTP Post Request. */
final HttpResponse httpResponse = httpClient.execute(httpPost);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if(statusCode == HttpStatus.SC_OK) {
final String response = StreamUtils.readFully(httpResponse.getEntity().getContent());
if(response.equals("<success/>")) {
if(pCallback != null) {
pCallback.onCallback(true);
}
} else {
if(pCallback != null) {
pCallback.onCallback(false);
}
}
} else {
if(pCallback != null) {
pCallback.onCallback(false);
}
}
}catch(final IOException e) {
Debug.e(e);
if(pCallback != null) {
pCallback.onCallback(false);
}
}
}
}).start();
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/levelstats/LevelStatsDBConnector.java | Java | lgpl | 5,003 |
package org.anddev.andengine.util;
import android.util.SparseArray;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:51:29 - 20.08.2010
* @param <T>
*/
public class Library<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected final SparseArray<T> mItems;
// ===========================================================
// Constructors
// ===========================================================
public Library() {
this.mItems = new SparseArray<T>();
}
public Library(final int pInitialCapacity) {
this.mItems = new SparseArray<T>(pInitialCapacity);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void put(final int pID, final T pItem) {
final T existingItem = this.mItems.get(pID);
if(existingItem == null) {
this.mItems.put(pID, pItem);
} else {
throw new IllegalArgumentException("ID: '" + pID + "' is already associated with item: '" + existingItem.toString() + "'.");
}
}
public void remove(final int pID) {
this.mItems.remove(pID);
}
public T get(final int pID) {
return this.mItems.get(pID);
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/Library.java | Java | lgpl | 2,001 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.anddev.andengine.util;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An InputStream that does Base64 decoding on the data read through
* it.
*/
public class Base64InputStream extends FilterInputStream {
private final Base64.Coder coder;
private static byte[] EMPTY = new byte[0];
private static final int BUFFER_SIZE = 2048;
private boolean eof;
private byte[] inputBuffer;
private int outputStart;
private int outputEnd;
/**
* An InputStream that performs Base64 decoding on the data read
* from the wrapped stream.
*
* @param in the InputStream to read the source data from
* @param flags bit flags for controlling the decoder; see the
* constants in {@link Base64}
*/
public Base64InputStream(final InputStream in, final int flags) {
this(in, flags, false);
}
/**
* Performs Base64 encoding or decoding on the data read from the
* wrapped InputStream.
*
* @param in the InputStream to read the source data from
* @param flags bit flags for controlling the decoder; see the
* constants in {@link Base64}
* @param encode true to encode, false to decode
*
* @hide
*/
public Base64InputStream(final InputStream in, final int flags, final boolean encode) {
super(in);
this.eof = false;
this.inputBuffer = new byte[BUFFER_SIZE];
if (encode) {
this.coder = new Base64.Encoder(flags, null);
} else {
this.coder = new Base64.Decoder(flags, null);
}
this.coder.output = new byte[this.coder.maxOutputSize(BUFFER_SIZE)];
this.outputStart = 0;
this.outputEnd = 0;
}
@Override
public boolean markSupported() {
return false;
}
@Override
public void mark(final int readlimit) {
throw new UnsupportedOperationException();
}
@Override
public void reset() {
throw new UnsupportedOperationException();
}
@Override
public void close() throws IOException {
this.in.close();
this.inputBuffer = null;
}
@Override
public int available() {
return this.outputEnd - this.outputStart;
}
@Override
public long skip(final long n) throws IOException {
if (this.outputStart >= this.outputEnd) {
this.refill();
}
if (this.outputStart >= this.outputEnd) {
return 0;
}
final long bytes = Math.min(n, this.outputEnd-this.outputStart);
this.outputStart += bytes;
return bytes;
}
@Override
public int read() throws IOException {
if (this.outputStart >= this.outputEnd) {
this.refill();
}
if (this.outputStart >= this.outputEnd) {
return -1;
} else {
return this.coder.output[this.outputStart++];
}
}
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
if (this.outputStart >= this.outputEnd) {
this.refill();
}
if (this.outputStart >= this.outputEnd) {
return -1;
}
final int bytes = Math.min(len, this.outputEnd-this.outputStart);
System.arraycopy(this.coder.output, this.outputStart, b, off, bytes);
this.outputStart += bytes;
return bytes;
}
/**
* Read data from the input stream into inputBuffer, then
* decode/encode it into the empty coder.output, and reset the
* outputStart and outputEnd pointers.
*/
private void refill() throws IOException {
if (this.eof) {
return;
}
final int bytesRead = this.in.read(this.inputBuffer);
boolean success;
if (bytesRead == -1) {
this.eof = true;
success = this.coder.process(EMPTY, 0, 0, true);
} else {
success = this.coder.process(this.inputBuffer, 0, bytesRead, false);
}
if (!success) {
throw new IOException("bad base-64");
}
this.outputEnd = this.coder.op;
this.outputStart = 0;
}
}
| zzy421-andengine | src/org/anddev/andengine/util/Base64InputStream.java | Java | lgpl | 4,433 |
package org.anddev.andengine.util;
import org.anddev.andengine.util.pool.GenericPool;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:07:53 - 23.02.2011
*/
public class TransformationPool {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static final GenericPool<Transformation> POOL = new GenericPool<Transformation>() {
@Override
protected Transformation onAllocatePoolItem() {
return new Transformation();
}
};
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
public static Transformation obtain() {
return POOL.obtainPoolItem();
}
public static void recycle(final Transformation pTransformation) {
pTransformation.setToIdentity();
POOL.recyclePoolItem(pTransformation);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | zzy421-andengine | src/org/anddev/andengine/util/TransformationPool.java | Java | lgpl | 1,778 |
package org.anddev.andengine.util;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:42:15 - 18.09.2009
*/
public class SocketUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void closeSocket(final DatagramSocket pDatagramSocket) {
if(pDatagramSocket != null && !pDatagramSocket.isClosed()) {
pDatagramSocket.close();
}
}
public static void closeSocket(final Socket pSocket) {
if(pSocket != null && !pSocket.isClosed()) {
try {
pSocket.close();
} catch (final IOException e) {
Debug.e(e);
}
}
}
public static void closeSocket(final ServerSocket pServerSocket) {
if(pServerSocket != null && !pServerSocket.isClosed()) {
try {
pServerSocket.close();
} catch (final IOException e) {
Debug.e(e);
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/SocketUtils.java | Java | lgpl | 2,020 |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:52:44 - 03.01.2010
*/
public interface Callable<T> {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return the computed result.
* @throws Exception if unable to compute a result.
*/
public T call() throws Exception;
} | zzy421-andengine | src/org/anddev/andengine/util/Callable.java | Java | lgpl | 706 |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:35:42 - 01.05.2011
*/
public class ArrayUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static <T> T random(final T[] pArray) {
return pArray[MathUtils.random(0, pArray.length - 1)];
}
public static void reverse(final byte[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
byte tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final short[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
short tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final int[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
int tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final long[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
long tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final float[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
float tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final double[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
double tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final Object[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
Object tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static boolean equals(final byte[] pArrayA, final int pOffsetA, final byte[] pArrayB, final int pOffsetB, final int pLength) {
final int lastIndexA = pOffsetA + pLength;
if(lastIndexA > pArrayA.length) {
throw new ArrayIndexOutOfBoundsException(pArrayA.length);
}
final int lastIndexB = pOffsetB + pLength;
if(lastIndexB > pArrayB.length) {
throw new ArrayIndexOutOfBoundsException(pArrayB.length);
}
for(int a = pOffsetA, b = pOffsetB; a < lastIndexA; a++, b++) {
if(pArrayA[a] != pArrayB[b]) {
return false;
}
}
return true;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/ArrayUtils.java | Java | lgpl | 3,883 |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 19:01:08 - 03.04.2010
*/
public class StringUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static String padFront(final String pString, final char pPadChar, final int pLength) {
final int padCount = pLength - pString.length();
if(padCount <= 0) {
return pString;
} else {
final StringBuilder sb = new StringBuilder();
for(int i = padCount - 1; i >= 0; i--) {
sb.append(pPadChar);
}
sb.append(pString);
return sb.toString();
}
}
public static int countOccurrences(final String pString, final char pCharacter) {
int count = 0;
int lastOccurrence = pString.indexOf(pCharacter, 0);
while (lastOccurrence != -1) {
count++;
lastOccurrence = pString.indexOf(pCharacter, lastOccurrence + 1);
}
return count;
}
/**
* Split a String by a Character, i.e. Split lines by using '\n'.<br/>
* Same behavior as <code>String.split("" + pCharacter);</code> .
*
* @param pString
* @param pCharacter
* @return
*/
public static String[] split(final String pString, final char pCharacter) {
return StringUtils.split(pString, pCharacter, null);
}
/**
* Split a String by a Character, i.e. Split lines by using '\n'.<br/>
* Same behavior as <code>String.split("" + pCharacter);</code> .
*
* @param pString
* @param pCharacter
* @param pReuse tries to reuse the String[] if the length is the same as the length needed.
* @return
*/
public static String[] split(final String pString, final char pCharacter, final String[] pReuse) {
final int partCount = StringUtils.countOccurrences(pString, pCharacter) + 1;
final boolean reuseable = pReuse != null && pReuse.length == partCount;
final String[] out = (reuseable) ? pReuse : new String[partCount];
if(partCount == 0) {
out[0] = pString;
} else {
int from = 0;
int to;
for (int i = 0; i < partCount - 1; i++) {
to = pString.indexOf(pCharacter, from);
out[i] = pString.substring(from, to);
from = to + 1;
}
out[partCount - 1] = pString.substring(from, pString.length());
}
return out;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/StringUtils.java | Java | lgpl | 3,326 |
package org.anddev.andengine.util.modifier;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:48:13 - 03.09.2010
* @param <T>
*/
public abstract class BaseDurationModifier<T> extends BaseModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float mSecondsElapsed;
protected final float mDuration;
// ===========================================================
// Constructors
// ===========================================================
public BaseDurationModifier(final float pDuration) {
this.mDuration = pDuration;
}
public BaseDurationModifier(final float pDuration, final IModifierListener<T> pModifierListener) {
super(pModifierListener);
this.mDuration = pDuration;
}
protected BaseDurationModifier(final BaseDurationModifier<T> pBaseModifier) {
this(pBaseModifier.mDuration);
}
// ===========================================================
// Getter & Setter
// ===========================================================
@Override
public float getSecondsElapsed() {
return this.mSecondsElapsed;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getDuration() {
return this.mDuration;
}
protected abstract void onManagedUpdate(final float pSecondsElapsed, final T pItem);
protected abstract void onManagedInitialize(final T pItem);
@Override
public final float onUpdate(final float pSecondsElapsed, final T pItem) {
if(this.mFinished){
return 0;
} else {
if(this.mSecondsElapsed == 0) {
this.onManagedInitialize(pItem);
this.onModifierStarted(pItem);
}
final float secondsElapsedUsed;
if(this.mSecondsElapsed + pSecondsElapsed < this.mDuration) {
secondsElapsedUsed = pSecondsElapsed;
} else {
secondsElapsedUsed = this.mDuration - this.mSecondsElapsed;
}
this.mSecondsElapsed += secondsElapsedUsed;
this.onManagedUpdate(secondsElapsedUsed, pItem);
if(this.mDuration != -1 && this.mSecondsElapsed >= this.mDuration) {
this.mSecondsElapsed = this.mDuration;
this.mFinished = true;
this.onModifierFinished(pItem);
}
return secondsElapsedUsed;
}
}
@Override
public void reset() {
this.mFinished = false;
this.mSecondsElapsed = 0;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/BaseDurationModifier.java | Java | lgpl | 3,033 |
package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.modifier.IModifier.IModifierListener;
import org.anddev.andengine.util.modifier.util.ModifierUtils;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 19:39:25 - 19.03.2010
*/
public class SequenceModifier<T> extends BaseModifier<T> implements IModifierListener<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private ISubSequenceModifierListener<T> mSubSequenceModifierListener;
private final IModifier<T>[] mSubSequenceModifiers;
private int mCurrentSubSequenceModifierIndex;
private float mSecondsElapsed;
private final float mDuration;
private boolean mFinishedCached;
// ===========================================================
// Constructors
// ===========================================================
public SequenceModifier(final IModifier<T> ... pModifiers) throws IllegalArgumentException {
this(null, null, pModifiers);
}
public SequenceModifier(final ISubSequenceModifierListener<T> pSubSequenceModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException {
this(pSubSequenceModifierListener, null, pModifiers);
}
public SequenceModifier(final IModifierListener<T> pModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException {
this(null, pModifierListener, pModifiers);
}
public SequenceModifier(final ISubSequenceModifierListener<T> pSubSequenceModifierListener, final IModifierListener<T> pModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException {
super(pModifierListener);
if (pModifiers.length == 0) {
throw new IllegalArgumentException("pModifiers must not be empty!");
}
this.mSubSequenceModifierListener = pSubSequenceModifierListener;
this.mSubSequenceModifiers = pModifiers;
this.mDuration = ModifierUtils.getSequenceDurationOfModifier(pModifiers);
pModifiers[0].addModifierListener(this);
}
@SuppressWarnings("unchecked")
protected SequenceModifier(final SequenceModifier<T> pSequenceModifier) throws DeepCopyNotSupportedException {
this.mDuration = pSequenceModifier.mDuration;
final IModifier<T>[] otherModifiers = pSequenceModifier.mSubSequenceModifiers;
this.mSubSequenceModifiers = new IModifier[otherModifiers.length];
final IModifier<T>[] shapeModifiers = this.mSubSequenceModifiers;
for(int i = shapeModifiers.length - 1; i >= 0; i--) {
shapeModifiers[i] = otherModifiers[i].deepCopy();
}
shapeModifiers[0].addModifierListener(this);
}
@Override
public SequenceModifier<T> deepCopy() throws DeepCopyNotSupportedException{
return new SequenceModifier<T>(this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public ISubSequenceModifierListener<T> getSubSequenceModifierListener() {
return this.mSubSequenceModifierListener;
}
public void setSubSequenceModifierListener(final ISubSequenceModifierListener<T> pSubSequenceModifierListener) {
this.mSubSequenceModifierListener = pSubSequenceModifierListener;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getSecondsElapsed() {
return this.mSecondsElapsed;
}
@Override
public float getDuration() {
return this.mDuration;
}
@Override
public float onUpdate(final float pSecondsElapsed, final T pItem) {
if(this.mFinished){
return 0;
} else {
float secondsElapsedRemaining = pSecondsElapsed;
this.mFinishedCached = false;
while(secondsElapsedRemaining > 0 && !this.mFinishedCached) {
secondsElapsedRemaining -= this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].onUpdate(secondsElapsedRemaining, pItem);
}
this.mFinishedCached = false;
final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining;
this.mSecondsElapsed += secondsElapsedUsed;
return secondsElapsedUsed;
}
}
@Override
public void reset() {
if(this.isFinished()) {
this.mSubSequenceModifiers[this.mSubSequenceModifiers.length - 1].removeModifierListener(this);
} else {
this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].removeModifierListener(this);
}
this.mCurrentSubSequenceModifierIndex = 0;
this.mFinished = false;
this.mSecondsElapsed = 0;
this.mSubSequenceModifiers[0].addModifierListener(this);
final IModifier<T>[] shapeModifiers = this.mSubSequenceModifiers;
for(int i = shapeModifiers.length - 1; i >= 0; i--) {
shapeModifiers[i].reset();
}
}
@Override
public void onModifierStarted(final IModifier<T> pModifier, final T pItem) {
if(this.mCurrentSubSequenceModifierIndex == 0) {
this.onModifierStarted(pItem);
}
if(this.mSubSequenceModifierListener != null) {
this.mSubSequenceModifierListener.onSubSequenceStarted(pModifier, pItem, this.mCurrentSubSequenceModifierIndex);
}
}
@Override
public void onModifierFinished(final IModifier<T> pModifier, final T pItem) {
if(this.mSubSequenceModifierListener != null) {
this.mSubSequenceModifierListener.onSubSequenceFinished(pModifier, pItem, this.mCurrentSubSequenceModifierIndex);
}
pModifier.removeModifierListener(this);
this.mCurrentSubSequenceModifierIndex++;
if(this.mCurrentSubSequenceModifierIndex < this.mSubSequenceModifiers.length) {
final IModifier<T> nextSubSequenceModifier = this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex];
nextSubSequenceModifier.addModifierListener(this);
} else {
this.mFinished = true;
this.mFinishedCached = true;
this.onModifierFinished(pItem);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public interface ISubSequenceModifierListener<T> {
public void onSubSequenceStarted(final IModifier<T> pModifier, final T pItem, final int pIndex);
public void onSubSequenceFinished(final IModifier<T> pModifier, final T pItem, final int pIndex);
}
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/SequenceModifier.java | Java | lgpl | 6,738 |
package org.anddev.andengine.util.modifier;
import java.util.Comparator;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:17:50 - 19.03.2010
*/
public interface IModifier<T> {
// ===========================================================
// Final Fields
// ===========================================================
public static final Comparator<IModifier<?>> MODIFIER_COMPARATOR_DURATION_DESCENDING = new Comparator<IModifier<?>>() {
@Override
public int compare(final IModifier<?> pModifierA, final IModifier<?> pModifierB) {
final float durationA = pModifierA.getDuration();
final float durationB = pModifierB.getDuration();
if (durationA < durationB) {
return 1;
} else if (durationA > durationB) {
return -1;
} else {
return 0;
}
}
};
// ===========================================================
// Methods
// ===========================================================
public void reset();
public boolean isFinished();
public boolean isRemoveWhenFinished();
public void setRemoveWhenFinished(final boolean pRemoveWhenFinished);
public IModifier<T> deepCopy() throws DeepCopyNotSupportedException;
public float getSecondsElapsed();
public float getDuration();
public float onUpdate(final float pSecondsElapsed, final T pItem);
public void addModifierListener(final IModifierListener<T> pModifierListener);
public boolean removeModifierListener(final IModifierListener<T> pModifierListener);
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static interface IModifierListener<T> {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onModifierStarted(final IModifier<T> pModifier, final T pItem);
public void onModifierFinished(final IModifier<T> pModifier, final T pItem);
}
public static class DeepCopyNotSupportedException extends RuntimeException {
// ===========================================================
// Constants
// ===========================================================
private static final long serialVersionUID = -5838035434002587320L;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/IModifier.java | Java | lgpl | 3,513 |
package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.modifier.IModifier.IModifierListener;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:18:37 - 03.09.2010
* @param <T>
*/
public class LoopModifier<T> extends BaseModifier<T> implements IModifierListener<T> {
// ===========================================================
// Constants
// ===========================================================
public static final int LOOP_CONTINUOUS = -1;
// ===========================================================
// Fields
// ===========================================================
private float mSecondsElapsed;
private final float mDuration;
private final IModifier<T> mModifier;
private ILoopModifierListener<T> mLoopModifierListener;
private final int mLoopCount;
private int mLoop;
private boolean mModifierStartedCalled;
private boolean mFinishedCached;
// ===========================================================
// Constructors
// ===========================================================
public LoopModifier(final IModifier<T> pModifier) {
this(pModifier, LOOP_CONTINUOUS);
}
public LoopModifier(final IModifier<T> pModifier, final int pLoopCount) {
this(pModifier, pLoopCount, null, (IModifierListener<T>)null);
}
public LoopModifier(final IModifier<T> pModifier, final int pLoopCount, final IModifierListener<T> pModifierListener) {
this(pModifier, pLoopCount, null, pModifierListener);
}
public LoopModifier(final IModifier<T> pModifier, final int pLoopCount, final ILoopModifierListener<T> pLoopModifierListener) {
this(pModifier, pLoopCount, pLoopModifierListener, (IModifierListener<T>)null);
}
public LoopModifier(final IModifier<T> pModifier, final int pLoopCount, final ILoopModifierListener<T> pLoopModifierListener, final IModifierListener<T> pModifierListener) {
super(pModifierListener);
this.mModifier = pModifier;
this.mLoopCount = pLoopCount;
this.mLoopModifierListener = pLoopModifierListener;
this.mLoop = 0;
this.mDuration = pLoopCount == LOOP_CONTINUOUS ? Float.POSITIVE_INFINITY : pModifier.getDuration() * pLoopCount; // TODO Check if POSITIVE_INFINITY works correct with i.e. SequenceModifier
this.mModifier.addModifierListener(this);
}
protected LoopModifier(final LoopModifier<T> pLoopModifier) throws DeepCopyNotSupportedException {
this(pLoopModifier.mModifier.deepCopy(), pLoopModifier.mLoopCount);
}
@Override
public LoopModifier<T> deepCopy() throws DeepCopyNotSupportedException {
return new LoopModifier<T>(this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public ILoopModifierListener<T> getLoopModifierListener() {
return this.mLoopModifierListener;
}
public void setLoopModifierListener(final ILoopModifierListener<T> pLoopModifierListener) {
this.mLoopModifierListener = pLoopModifierListener;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getSecondsElapsed() {
return this.mSecondsElapsed;
}
@Override
public float getDuration() {
return this.mDuration;
}
@Override
public float onUpdate(final float pSecondsElapsed, final T pItem) {
if(this.mFinished){
return 0;
} else {
float secondsElapsedRemaining = pSecondsElapsed;
this.mFinishedCached = false;
while(secondsElapsedRemaining > 0 && !this.mFinishedCached) {
secondsElapsedRemaining -= this.mModifier.onUpdate(secondsElapsedRemaining, pItem);
}
this.mFinishedCached = false;
final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining;
this.mSecondsElapsed += secondsElapsedUsed;
return secondsElapsedUsed;
}
}
@Override
public void reset() {
this.mLoop = 0;
this.mSecondsElapsed = 0;
this.mModifierStartedCalled = false;
this.mModifier.reset();
}
// ===========================================================
// Methods
// ===========================================================
@Override
public void onModifierStarted(final IModifier<T> pModifier, final T pItem) {
if(!this.mModifierStartedCalled) {
this.mModifierStartedCalled = true;
this.onModifierStarted(pItem);
}
if(this.mLoopModifierListener != null) {
this.mLoopModifierListener.onLoopStarted(this, this.mLoop, this.mLoopCount);
}
}
@Override
public void onModifierFinished(final IModifier<T> pModifier, final T pItem) {
if(this.mLoopModifierListener != null) {
this.mLoopModifierListener.onLoopFinished(this, this.mLoop, this.mLoopCount);
}
if(this.mLoopCount == LOOP_CONTINUOUS) {
this.mSecondsElapsed = 0;
this.mModifier.reset();
} else {
this.mLoop++;
if(this.mLoop >= this.mLoopCount) {
this.mFinished = true;
this.mFinishedCached = true;
this.onModifierFinished(pItem);
} else {
this.mSecondsElapsed = 0;
this.mModifier.reset();
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public interface ILoopModifierListener<T> {
public void onLoopStarted(final LoopModifier<T> pLoopModifier, final int pLoop, final int pLoopCount);
public void onLoopFinished(final LoopModifier<T> pLoopModifier, final int pLoop, final int pLoopCount);
}
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/LoopModifier.java | Java | lgpl | 5,705 |
package org.anddev.andengine.util.modifier.util;
import org.anddev.andengine.util.modifier.IModifier;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:16:36 - 03.09.2010
*/
public class ModifierUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static float getSequenceDurationOfModifier(final IModifier<?>[] pModifiers){
float duration = Float.MIN_VALUE;
for(int i = pModifiers.length - 1; i >= 0; i--) {
duration += pModifiers[i].getDuration();
}
return duration;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/util/ModifierUtils.java | Java | lgpl | 1,607 |
package org.anddev.andengine.util.modifier;
import java.util.ArrayList;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.util.SmartList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:34:57 - 03.09.2010
*/
public class ModifierList<T> extends SmartList<IModifier<T>> implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
private static final long serialVersionUID = 1610345592534873475L;
// ===========================================================
// Fields
// ===========================================================
private final T mTarget;
// ===========================================================
// Constructors
// ===========================================================
public ModifierList(final T pTarget) {
this.mTarget = pTarget;
}
public ModifierList(final T pTarget, final int pCapacity){
super(pCapacity);
this.mTarget = pTarget;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public T getTarget() {
return this.mTarget;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onUpdate(final float pSecondsElapsed) {
final ArrayList<IModifier<T>> modifiers = this;
final int modifierCount = this.size();
if(modifierCount > 0) {
for(int i = modifierCount - 1; i >= 0; i--) {
final IModifier<T> modifier = modifiers.get(i);
modifier.onUpdate(pSecondsElapsed, this.mTarget);
if(modifier.isFinished() && modifier.isRemoveWhenFinished()) {
modifiers.remove(i);
}
}
}
}
@Override
public void reset() {
final ArrayList<IModifier<T>> modifiers = this;
for(int i = modifiers.size() - 1; i >= 0; i--) {
modifiers.get(i).reset();
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ModifierList.java | Java | lgpl | 2,475 |
package org.anddev.andengine.util.modifier.ease;
import org.anddev.andengine.util.constants.MathConstants;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseSineIn implements IEaseFunction, MathConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseSineIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseSineIn() {
}
public static EaseSineIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseSineIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseSineIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return -FloatMath.cos(pPercentage * PI_HALF) + 1;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseSineIn.java | Java | lgpl | 1,925 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseExponentialOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseExponentialOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseExponentialOut() {
}
public static EaseExponentialOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseExponentialOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseExponentialOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return (pPercentage == 1) ? 1 : (-(float)Math.pow(2, -10 * pPercentage) + 1);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseExponentialOut.java | Java | lgpl | 1,891 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 17:13:17 - 26.07.2010
*/
public interface IEaseFunction {
// ===========================================================
// Final Fields
// ===========================================================
public static final IEaseFunction DEFAULT = EaseLinear.getInstance();
// ===========================================================
// Methods
// ===========================================================
public float getPercentage(final float pSecondsElapsed, final float pDuration);
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/IEaseFunction.java | Java | lgpl | 686 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuartInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuartInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuartInOut() {
}
public static EaseQuartInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuartInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseQuartIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseQuartOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseQuartInOut.java | Java | lgpl | 1,885 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuadIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuadIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuadIn() {
}
public static EaseQuadIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuadIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseQuadIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return pPercentage * pPercentage;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseQuadIn.java | Java | lgpl | 1,799 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuadInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuadInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuadInOut() {
}
public static EaseQuadInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuadInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseQuadIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseQuadOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseQuadInOut.java | Java | lgpl | 1,878 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuadOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuadOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuadOut() {
}
public static EaseQuadOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuadOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseQuadOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return -pPercentage * (pPercentage - 2);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseQuadOut.java | Java | lgpl | 1,812 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseBackOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseBackOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseBackOut() {
}
public static EaseBackOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseBackOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseBackOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
final float t = pPercentage - 1;
return 1 + t * t * ((1.70158f + 1) * t + 1.70158f);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseBackOut.java | Java | lgpl | 1,859 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseBounceInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseBounceInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseBounceInOut() {
}
public static EaseBounceInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseBounceInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseBounceIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseBounceOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseBounceInOut.java | Java | lgpl | 1,892 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseStrongOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseStrongOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseStrongOut() {
}
public static EaseStrongOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseStrongOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseStrongOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
final float t = pPercentage - 1;
return 1 + (t * t * t * t * t);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseStrongOut.java | Java | lgpl | 1,851 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseExponentialInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseExponentialInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseExponentialInOut() {
}
public static EaseExponentialInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseExponentialInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseExponentialIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseExponentialOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseExponentialInOut.java | Java | lgpl | 1,927 |
package org.anddev.andengine.util.modifier.ease;
import org.anddev.andengine.util.constants.MathConstants;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseElasticOut implements IEaseFunction, MathConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseElasticOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseElasticOut() {
}
public static EaseElasticOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseElasticOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseElasticOut.getValue(pSecondsElapsed, pDuration, pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pSecondsElapsed, final float pDuration, final float pPercentageDone) {
if(pSecondsElapsed == 0) {
return 0;
}
if(pSecondsElapsed == pDuration) {
return 1;
}
final float p = pDuration * 0.3f;
final float s = p / 4;
return 1 + (float)Math.pow(2, -10 * pPercentageDone) * FloatMath.sin((pPercentageDone * pDuration - s) * PI_TWICE / p);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseElasticOut.java | Java | lgpl | 2,276 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseCircularInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseCircularInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseCircularInOut() {
}
public static EaseCircularInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseCircularInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseCircularIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseCircularOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseCircularInOut.java | Java | lgpl | 1,906 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseCubicIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseCubicIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseCubicIn() {
}
public static EaseCubicIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseCubicIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseCubicIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return pPercentage * pPercentage * pPercentage;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseCubicIn.java | Java | lgpl | 1,819 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseStrongIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseStrongIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseStrongIn() {
}
public static EaseStrongIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseStrongIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseStrongIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return pPercentage * pPercentage * pPercentage * pPercentage * pPercentage;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseStrongIn.java | Java | lgpl | 1,853 |
package org.anddev.andengine.util.modifier.ease;
import org.anddev.andengine.util.constants.MathConstants;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseSineOut implements IEaseFunction, MathConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseSineOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseSineOut() {
}
public static EaseSineOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseSineOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseSineOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return FloatMath.sin(pPercentage * PI_HALF);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseSineOut.java | Java | lgpl | 1,926 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseStrongInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseStrongInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseStrongInOut() {
}
public static EaseStrongInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseStrongInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseStrongIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseStrongOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseStrongInOut.java | Java | lgpl | 1,892 |
package org.anddev.andengine.util.modifier.ease;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseCircularIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseCircularIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseCircularIn() {
}
public static EaseCircularIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseCircularIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseCircularIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return -(FloatMath.sqrt(1 - pPercentage * pPercentage) - 1.0f);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseCircularIn.java | Java | lgpl | 1,887 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseCubicInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseCubicInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseCubicInOut() {
}
public static EaseCubicInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseCubicInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseCubicIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseCubicOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseCubicInOut.java | Java | lgpl | 1,885 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuintIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuintIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuintIn() {
}
public static EaseQuintIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuintIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseQuintIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return pPercentage * pPercentage * pPercentage * pPercentage * pPercentage;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseQuintIn.java | Java | lgpl | 1,847 |
package org.anddev.andengine.util.modifier.ease;
import org.anddev.andengine.util.constants.MathConstants;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseElasticIn implements IEaseFunction, MathConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseElasticIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseElasticIn() {
}
public static EaseElasticIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseElasticIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseElasticIn.getValue(pSecondsElapsed, pDuration, pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pSecondsElapsed, final float pDuration, final float pPercentage) {
if(pSecondsElapsed == 0) {
return 0;
}
if(pSecondsElapsed == pDuration) {
return 1;
}
final float p = pDuration * 0.3f;
final float s = p / 4;
final float t = pPercentage - 1;
return -(float)Math.pow(2, 10 * t) * FloatMath.sin((t * pDuration - s) * PI_TWICE / p);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseElasticIn.java | Java | lgpl | 2,270 |
package org.anddev.andengine.util.modifier.ease;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseCircularOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseCircularOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseCircularOut() {
}
public static EaseCircularOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseCircularOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseCircularOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
final float t = pPercentage - 1;
return FloatMath.sqrt(1 - t * t);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseCircularOut.java | Java | lgpl | 1,899 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuartIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuartIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuartIn() {
}
public static EaseQuartIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuartIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseQuartIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return pPercentage * pPercentage * pPercentage * pPercentage;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseQuartIn.java | Java | lgpl | 1,833 |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseBackIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
private static final float OVERSHOOT_CONSTANT = 1.70158f;
// ===========================================================
// Fields
// ===========================================================
private static EaseBackIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseBackIn() {
}
public static EaseBackIn getInstance() {
if(null == INSTANCE) {
INSTANCE = new EaseBackIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseBackIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return pPercentage * pPercentage * ((OVERSHOOT_CONSTANT + 1) * pPercentage - OVERSHOOT_CONSTANT);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| zzy421-andengine | src/org/anddev/andengine/util/modifier/ease/EaseBackIn.java | Java | lgpl | 1,925 |