diff options
author | Xavier Ducrohet <xav@google.com> | 2013-11-12 09:36:20 -0800 |
---|---|---|
committer | Xavier Ducrohet <xav@google.com> | 2013-11-13 17:49:15 -0800 |
commit | d3cc5cac69f3e2229a353554f6f50d969610ce3d (patch) | |
tree | a1b26dc124de68c0c569a61f66a1e76ce0056efd | |
parent | bf5e87934a87b5f922e8502a6aba61dffc494863 (diff) | |
download | build-d3cc5cac69f3e2229a353554f6f50d969610ce3d.tar.gz |
NDK Integration first pass.
Change-Id: Ib34a975c5bbbc559fc20f3b582566e7e3d69044b
54 files changed, 3548 insertions, 88 deletions
diff --git a/builder-test-api/src/main/java/com/android/builder/testing/api/DeviceConnector.java b/builder-test-api/src/main/java/com/android/builder/testing/api/DeviceConnector.java index 243bdc2..48208e8 100644 --- a/builder-test-api/src/main/java/com/android/builder/testing/api/DeviceConnector.java +++ b/builder-test-api/src/main/java/com/android/builder/testing/api/DeviceConnector.java @@ -23,6 +23,7 @@ import com.android.utils.ILogger; import com.google.common.annotations.Beta; import java.io.File; +import java.util.List; /** * A connector to a device to install/uninstall APKs, and run shell command. @@ -60,10 +61,18 @@ public abstract class DeviceConnector implements IShellEnabledDevice { */ public abstract void uninstallPackage(@NonNull String packageName, int timeout, ILogger logger) throws DeviceException; + /** + * Returns the API level of the device, or 0 if it could not be queried. + * @return the api level + */ public abstract int getApiLevel(); + /** + * The device supported ABIs. This is in preferred order. + * @return the list of supported ABIs + */ @NonNull - public abstract String getAbi(); + public abstract List<String> getAbis(); public abstract int getDensity(); diff --git a/builder/src/main/java/com/android/builder/AndroidBuilder.java b/builder/src/main/java/com/android/builder/AndroidBuilder.java index 9a6fa79..83e345d 100644 --- a/builder/src/main/java/com/android/builder/AndroidBuilder.java +++ b/builder/src/main/java/com/android/builder/AndroidBuilder.java @@ -65,6 +65,7 @@ import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; @@ -166,6 +167,7 @@ public class AndroidBuilder { /** * Helper method to get the boot classpath to be used during compilation. */ + @NonNull public static List<String> getBootClasspath(@NonNull SdkParser sdkParser) { List<String> classpath = Lists.newArrayList(); @@ -195,12 +197,18 @@ public class AndroidBuilder { * Returns an {@link AaptRunner} able to run aapt commands. * @return an AaptRunner object */ + @NonNull public AaptRunner getAaptRunner() { return new AaptRunner( mBuildTools.getPath(BuildToolInfo.PathId.AAPT), mCmdLineRunner); } + @NonNull + public CommandLineRunner getCommandLineRunner() { + return mCmdLineRunner; + } + /** * Generate the BuildConfig class for the project. * @param packageName the package in which to generate the class @@ -1074,7 +1082,8 @@ public class AndroidBuilder { * @param classesDexLocation the location of the classes.dex file * @param packagedJars the jars that are packaged (libraries + jar dependencies) * @param javaResourcesLocation the processed Java resource folder - * @param jniLibsLocation the location of the compiled JNI libraries + * @param jniLibsFolders the folders containing jni shared libraries + * @param abiFilters optional ABI filter * @param jniDebugBuild whether the app should include jni debug data * @param signingConfig the signing configuration * @param outApkLocation location of the APK. @@ -1091,7 +1100,8 @@ public class AndroidBuilder { @NonNull String classesDexLocation, @NonNull List<File> packagedJars, @Nullable String javaResourcesLocation, - @Nullable String jniLibsLocation, + @Nullable Collection<File> jniLibsFolders, + @Nullable Set<String> abiFilters, boolean jniDebugBuild, @Nullable SigningConfig signingConfig, @NonNull String outApkLocation) throws DuplicateFileException, FileNotFoundException, @@ -1128,8 +1138,10 @@ public class AndroidBuilder { } // also add resources from library projects and jars - if (jniLibsLocation != null) { - packager.addNativeLibraries(jniLibsLocation); + if (jniLibsFolders != null) { + for (File jniFolder : jniLibsFolders) { + packager.addNativeLibraries(jniFolder, abiFilters); + } } packager.sealApk(); diff --git a/builder/src/main/java/com/android/builder/DefaultSdkParser.java b/builder/src/main/java/com/android/builder/DefaultSdkParser.java index 3f52971..6244fb9 100644 --- a/builder/src/main/java/com/android/builder/DefaultSdkParser.java +++ b/builder/src/main/java/com/android/builder/DefaultSdkParser.java @@ -50,6 +50,7 @@ import static com.android.SdkConstants.FN_SOURCE_PROP; public class DefaultSdkParser implements SdkParser { private final String mSdkLocation; + private final File mNdkLocation; private SdkManager mManager; private IAndroidTarget mTarget; @@ -60,12 +61,13 @@ public class DefaultSdkParser implements SdkParser { private File mAdb; private File mZipAlign; - public DefaultSdkParser(@NonNull String sdkLocation) { + public DefaultSdkParser(@NonNull String sdkLocation, @Nullable File ndkLocation) { if (!sdkLocation.endsWith(File.separator)) { mSdkLocation = sdkLocation + File.separator; } else { mSdkLocation = sdkLocation; } + mNdkLocation = ndkLocation; } @Override @@ -211,4 +213,10 @@ public class DefaultSdkParser implements SdkParser { return mTools; } + + @Nullable + @Override + public File getNdkLocation() { + return mNdkLocation; + } } diff --git a/builder/src/main/java/com/android/builder/PlatformSdkParser.java b/builder/src/main/java/com/android/builder/PlatformSdkParser.java index 3325ea0..d0e1828 100644 --- a/builder/src/main/java/com/android/builder/PlatformSdkParser.java +++ b/builder/src/main/java/com/android/builder/PlatformSdkParser.java @@ -165,4 +165,10 @@ public class PlatformSdkParser implements SdkParser { } return mHostTools; } + + @Nullable + @Override + public File getNdkLocation() { + return null; + } } diff --git a/builder/src/main/java/com/android/builder/SdkParser.java b/builder/src/main/java/com/android/builder/SdkParser.java index 7c4e0c2..c247694 100644 --- a/builder/src/main/java/com/android/builder/SdkParser.java +++ b/builder/src/main/java/com/android/builder/SdkParser.java @@ -94,6 +94,13 @@ public interface SdkParser { @NonNull File getAdb(); + /** + * Returns the location of artifact repositories built-in the SDK. + * @return a non null list of repository folders. + */ @NonNull List<File> getRepositories(); + + @Nullable + File getNdkLocation(); }
\ No newline at end of file diff --git a/builder/src/main/java/com/android/builder/VariantConfiguration.java b/builder/src/main/java/com/android/builder/VariantConfiguration.java index 10994db..a5978d4 100644 --- a/builder/src/main/java/com/android/builder/VariantConfiguration.java +++ b/builder/src/main/java/com/android/builder/VariantConfiguration.java @@ -948,7 +948,7 @@ public class VariantConfiguration implements TestData { @Nullable @Override public Set<String> getSupportedAbis() { - // no ndk support yet, so return null + // TODO no ndk support yet, so return null return null; } } diff --git a/builder/src/main/java/com/android/builder/internal/packaging/Packager.java b/builder/src/main/java/com/android/builder/internal/packaging/Packager.java index 445d607..f60323e 100644 --- a/builder/src/main/java/com/android/builder/internal/packaging/Packager.java +++ b/builder/src/main/java/com/android/builder/internal/packaging/Packager.java @@ -39,6 +39,7 @@ import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; import java.util.regex.Pattern; @@ -402,7 +403,7 @@ public final class Packager implements IArchiveBuilder { * * This may or may not copy gdbserver into the apk based on whether the debug mode is set. * - * @param jniLibLocation the root folder containing the abi folders which contain the .so + * @param nativeFolder the root folder containing the abi folders which contain the .so * * @throws PackagerException if an error occurred * @throws SealedPackageException if the APK is already sealed. @@ -411,14 +412,12 @@ public final class Packager implements IArchiveBuilder { * * @see #setJniDebugMode(boolean) */ - public void addNativeLibraries(String jniLibLocation) + public void addNativeLibraries(@NonNull File nativeFolder, @Nullable Set<String> abiFilters) throws PackagerException, SealedPackageException, DuplicateFileException { if (mIsSealed) { throw new SealedPackageException("APK is already sealed"); } - File nativeFolder = new File(jniLibLocation); - if (!nativeFolder.isDirectory()) { // not a directory? check if it's a file or doesn't exist if (nativeFolder.exists()) { @@ -434,6 +433,10 @@ public final class Packager implements IArchiveBuilder { if (abiList != null) { for (File abi : abiList) { + if (abiFilters != null && !abiFilters.contains(abi.getName())) { + continue; + } + if (abi.isDirectory()) { // ignore files File[] libs = abi.listFiles(); diff --git a/builder/src/main/java/com/android/builder/testing/ConnectedDevice.java b/builder/src/main/java/com/android/builder/testing/ConnectedDevice.java index 8a1aa64..7e6ae77 100644 --- a/builder/src/main/java/com/android/builder/testing/ConnectedDevice.java +++ b/builder/src/main/java/com/android/builder/testing/ConnectedDevice.java @@ -25,9 +25,11 @@ import com.android.ddmlib.IShellOutputReceiver; import com.android.ddmlib.ShellCommandUnresponsiveException; import com.android.ddmlib.TimeoutException; import com.android.utils.ILogger; +import com.google.common.collect.Lists; import java.io.File; import java.io.IOException; +import java.util.List; import java.util.concurrent.TimeUnit; /** @@ -115,8 +117,19 @@ public class ConnectedDevice extends DeviceConnector { @NonNull @Override - public String getAbi() { - return null; //To change body of implemented methods use File | Settings | File Templates. + public List<String> getAbis() { + List<String> abis = Lists.newArrayListWithExpectedSize(2); + String abi = iDevice.getProperty(IDevice.PROP_DEVICE_CPU_ABI); + if (abi != null) { + abis.add(abi); + } + + abi = iDevice.getProperty(IDevice.PROP_DEVICE_CPU_ABI2); + if (abi != null) { + abis.add(abi); + } + + return abis; } @Override diff --git a/builder/src/main/java/com/android/builder/testing/SimpleTestRunner.java b/builder/src/main/java/com/android/builder/testing/SimpleTestRunner.java index 85114d4..237d871 100644 --- a/builder/src/main/java/com/android/builder/testing/SimpleTestRunner.java +++ b/builder/src/main/java/com/android/builder/testing/SimpleTestRunner.java @@ -26,6 +26,7 @@ import com.android.utils.ILogger; import java.io.File; import java.util.List; +import java.util.Set; /** * Basic {@link TestRunner} running tests on all devices. @@ -47,21 +48,11 @@ public class SimpleTestRunner implements TestRunner { WaitableExecutor<Boolean> executor = new WaitableExecutor<Boolean>(maxThreads); - int minSdkVersion = testData.getMinSdkVersion(); for (DeviceConnector device : deviceList) { - int deviceApiLevel = device.getApiLevel(); - if (minSdkVersion <= deviceApiLevel) { + if (filterOutDevice(device, testData, logger, projectName, variantName)) { executor.execute(new SimpleTestCallable(device, projectName, variantName, testApk, testedApk, testData, resultsDir, timeout, logger)); - } else { - if (deviceApiLevel == 0) { - logger.info("Skipping device '%s' for '%s:%s': Unknown API Level", - device.getName(), projectName, variantName); - } else { - logger.info("Skipping device '%s' for '%s:%s'", - device.getName(), projectName, variantName); - } } } @@ -82,4 +73,45 @@ public class SimpleTestRunner implements TestRunner { return success; } + + private boolean filterOutDevice(@NonNull DeviceConnector device, @NonNull TestData testData, + @NonNull ILogger logger, + @NonNull String projectName, @NonNull String variantName) { + int deviceApiLevel = device.getApiLevel(); + if (deviceApiLevel == 0) { + logger.info("Skipping device '%s' for '%s:%s': Unknown API Level", + device.getName(), projectName, variantName); + return false; + } + + if (testData.getMinSdkVersion() > deviceApiLevel) { + logger.info("Skipping device '%s' for '%s:%s'", + device.getName(), projectName, variantName); + + return false; + } + + Set<String> appAbis = testData.getSupportedAbis(); + if (appAbis != null) { + List<String> deviceAbis = device.getAbis(); + if (deviceAbis == null || deviceAbis.isEmpty()) { + logger.info("Skipping device '%s' for '%s:%s': Unknown ABI", + device.getName(), projectName, variantName); + return false; + } + + boolean compatibleAbi = false; + for (String deviceAbi : deviceAbis) { + if (appAbis.contains(deviceAbi)) { + compatibleAbi = true; + } + } + + if (!compatibleAbi) { + return false; + } + } + + return true; + } } diff --git a/builder/src/main/java/com/android/builder/testing/TestData.java b/builder/src/main/java/com/android/builder/testing/TestData.java index 0bc7b61..a736026 100644 --- a/builder/src/main/java/com/android/builder/testing/TestData.java +++ b/builder/src/main/java/com/android/builder/testing/TestData.java @@ -52,6 +52,10 @@ public interface TestData { int getMinSdkVersion(); + /** + * List of supported ABIs. Null means all. + * @return a list of abi or null for all + */ @Nullable Set<String> getSupportedAbis(); } diff --git a/gradle/src/build-test/groovy/com/android/build/gradle/AutomatedBuildTest.java b/gradle/src/build-test/groovy/com/android/build/gradle/AutomatedBuildTest.java index 3167459..e06ae21 100644 --- a/gradle/src/build-test/groovy/com/android/build/gradle/AutomatedBuildTest.java +++ b/gradle/src/build-test/groovy/com/android/build/gradle/AutomatedBuildTest.java @@ -37,9 +37,9 @@ public class AutomatedBuildTest extends BuildTest { "aidl", "api", "applibtest", "assets", "attrOrder", "basic", "dependencies", "dependencyChecker", "flavored", "flavorlib", "flavors", "libProguardJarDep", "libProguardLibDep", "libTestDep", "libsTest", "localJars", "migrated", "multiproject", - "multires", "overlay1", "overlay2", "pkgOverride", "proguard", "proguardLib", - "renderscript", "renderscriptInLib", "renderscriptMultiSrc", "sameNamedLibs", - "tictactoe" /*, "autorepo"*/ + "multires", "ndkSanAngeles", "overlay1", "overlay2", "pkgOverride", "proguard", + "proguardLib", "renderscript", "renderscriptInLib", "renderscriptMultiSrc", + "sameNamedLibs", "tictactoe" /*, "autorepo"*/ }; private static final String[] sReportProjects = new String[] { diff --git a/gradle/src/build-test/groovy/com/android/build/gradle/BuildTest.java b/gradle/src/build-test/groovy/com/android/build/gradle/BuildTest.java index 092d8eb..c81d0db 100644 --- a/gradle/src/build-test/groovy/com/android/build/gradle/BuildTest.java +++ b/gradle/src/build-test/groovy/com/android/build/gradle/BuildTest.java @@ -33,11 +33,13 @@ abstract class BuildTest extends BaseTest { protected File testDir; protected File sdkDir; + protected File ndkDir; @Override protected void setUp() throws Exception { testDir = getTestDir(); sdkDir = getSdkDir(); + ndkDir = getNdkDir(); } /** @@ -59,12 +61,10 @@ abstract class BuildTest extends BaseTest { File project = new File(testDir, name); File buildGradle = new File(project, "build.gradle"); - if (!buildGradle.isFile()) { - return null; - } + assertTrue("Missing build.gradle for " + name, buildGradle.isFile()); // build the project - runGradleTasks(sdkDir, gradleVersion, project, tasks); + runGradleTasks(sdkDir, ndkDir, gradleVersion, project, tasks); return project; } diff --git a/gradle/src/build-test/groovy/com/android/build/gradle/ManualBuildTest.java b/gradle/src/build-test/groovy/com/android/build/gradle/ManualBuildTest.java index af0bd32..423107a 100644 --- a/gradle/src/build-test/groovy/com/android/build/gradle/ManualBuildTest.java +++ b/gradle/src/build-test/groovy/com/android/build/gradle/ManualBuildTest.java @@ -19,10 +19,10 @@ package com.android.build.gradle; import com.google.common.base.Charsets; import com.google.common.io.Files; +import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; -import javax.imageio.ImageIO; /** * Some manual tests for building projects. @@ -55,13 +55,13 @@ public class ManualBuildTest extends BuildTest { File repo = new File(testDir, "repo"); try { - runGradleTasks(sdkDir, BasePlugin.GRADLE_MIN_VERSION, + runGradleTasks(sdkDir, ndkDir, BasePlugin.GRADLE_MIN_VERSION, new File(repo, "util"), "clean", "uploadArchives"); - runGradleTasks(sdkDir, BasePlugin.GRADLE_MIN_VERSION, + runGradleTasks(sdkDir, ndkDir, BasePlugin.GRADLE_MIN_VERSION, new File(repo, "baseLibrary"), "clean", "uploadArchives"); - runGradleTasks(sdkDir, BasePlugin.GRADLE_MIN_VERSION, + runGradleTasks(sdkDir, ndkDir, BasePlugin.GRADLE_MIN_VERSION, new File(repo, "library"), "clean", "uploadArchives"); - runGradleTasks(sdkDir, BasePlugin.GRADLE_MIN_VERSION, + runGradleTasks(sdkDir, ndkDir, BasePlugin.GRADLE_MIN_VERSION, new File(repo, "app"), "clean", "assemble"); } finally { // clean up the test repository. @@ -75,7 +75,7 @@ public class ManualBuildTest extends BuildTest { File project = new File(testDir, "libProguard"); File fileOutput = new File(project, "build/proguard/release"); - runGradleTasks(sdkDir, BasePlugin.GRADLE_MIN_VERSION, + runGradleTasks(sdkDir, ndkDir, BasePlugin.GRADLE_MIN_VERSION, project, "clean", "build"); checkFile(fileOutput, "mapping.txt", new String[]{"int proguardInt -> a"}); @@ -87,7 +87,7 @@ public class ManualBuildTest extends BuildTest { File debugFileOutput = new File(project, "build/bundles/debug"); File releaseFileOutput = new File(project, "build/bundles/release"); - runGradleTasks(sdkDir, BasePlugin.GRADLE_MIN_VERSION, + runGradleTasks(sdkDir, ndkDir, BasePlugin.GRADLE_MIN_VERSION, project, "clean", "build"); checkFile(debugFileOutput, "proguard.txt", new String[]{"A"}); checkFile(releaseFileOutput, "proguard.txt", new String[]{"A", "B", "C"}); @@ -97,7 +97,7 @@ public class ManualBuildTest extends BuildTest { // custom because we want to run deviceCheck even without devices, since we use // a fake DeviceProvider that doesn't use a device, but only record the calls made // to the DeviceProvider and the DeviceConnector. - runGradleTasks(sdkDir, BasePlugin.GRADLE_MIN_VERSION, + runGradleTasks(sdkDir, ndkDir, BasePlugin.GRADLE_MIN_VERSION, new File(testDir, "3rdPartyTests"), "clean", "deviceCheck"); } diff --git a/gradle/src/main/groovy/com/android/build/gradle/AppPlugin.groovy b/gradle/src/main/groovy/com/android/build/gradle/AppPlugin.groovy index 19b6de7..7367c00 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/AppPlugin.groovy +++ b/gradle/src/main/groovy/com/android/build/gradle/AppPlugin.groovy @@ -561,6 +561,9 @@ class AppPlugin extends com.android.build.gradle.BasePlugin implements Plugin<Pr // Add a compile task createCompileTask(variant, null/*testedVariant*/) + // Add NDK tasks + createNdkTasks(variant) + addPackageTasks(variant, assembleTask) } } diff --git a/gradle/src/main/groovy/com/android/build/gradle/BaseExtension.groovy b/gradle/src/main/groovy/com/android/build/gradle/BaseExtension.groovy index e800753..889a70a 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/BaseExtension.groovy +++ b/gradle/src/main/groovy/com/android/build/gradle/BaseExtension.groovy @@ -72,7 +72,7 @@ public abstract class BaseExtension { this.plugin = plugin defaultConfig = instantiator.newInstance(ProductFlavorDsl.class, BuilderConstants.MAIN, - project.fileResolver) + project.fileResolver, instantiator) aaptOptions = instantiator.newInstance(AaptOptionsImpl.class) dexOptions = instantiator.newInstance(DexOptionsImpl.class) diff --git a/gradle/src/main/groovy/com/android/build/gradle/BasePlugin.groovy b/gradle/src/main/groovy/com/android/build/gradle/BasePlugin.groovy index 36482e5..59d9192 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/BasePlugin.groovy +++ b/gradle/src/main/groovy/com/android/build/gradle/BasePlugin.groovy @@ -29,6 +29,7 @@ import com.android.build.gradle.internal.dependency.LibraryDependencyImpl import com.android.build.gradle.internal.dependency.ManifestDependencyImpl import com.android.build.gradle.internal.dependency.SymbolFileProviderImpl import com.android.build.gradle.internal.dependency.VariantDependencies +import com.android.build.gradle.internal.dsl.NdkConfigDsl import com.android.build.gradle.internal.dsl.SigningConfigDsl import com.android.build.gradle.internal.model.ModelBuilder import com.android.build.gradle.internal.tasks.AndroidReportTask @@ -56,6 +57,7 @@ import com.android.build.gradle.tasks.GenerateBuildConfig import com.android.build.gradle.tasks.Lint import com.android.build.gradle.tasks.MergeAssets import com.android.build.gradle.tasks.MergeResources +import com.android.build.gradle.tasks.NdkCompile import com.android.build.gradle.tasks.PackageApplication import com.android.build.gradle.tasks.PreDex import com.android.build.gradle.tasks.ProcessAndroidResources @@ -303,7 +305,11 @@ public abstract class BasePlugin { } File getSdkDirectory() { - return sdk.directory + return sdk.sdkDirectory + } + + File getNdkDirectory() { + return sdk.ndkDirectory } ILogger getLogger() { @@ -611,7 +617,7 @@ public abstract class BasePlugin { Copy processResources = project.tasks.create("process${variantData.name}JavaRes", ProcessResources); - variantData.processJavaResources = processResources + variantData.processJavaResourcesTask = processResources // set the input processResources.from(((AndroidSourceSet) variantConfiguration.defaultSourceSet).resources) @@ -655,13 +661,13 @@ public abstract class BasePlugin { protected void createCompileTask(BaseVariantData variantData, BaseVariantData testedVariantData) { - def compileTask = project.tasks.create("compile${variantData.name}", JavaCompile) + def compileTask = project.tasks.create("compile${variantData.name}Java", JavaCompile) variantData.javaCompileTask = compileTask compileTask.dependsOn variantData.sourceGenTask VariantConfiguration config = variantData.variantConfiguration - List<Object> sourceList = new ArrayList<Object>(); + List<Object> sourceList = Lists.newArrayList() sourceList.add(((AndroidSourceSet) config.defaultSourceSet).java) sourceList.add({ variantData.processResourcesTask.sourceOutputDir }) sourceList.add({ variantData.generateBuildConfigTask.sourceOutputDir }) @@ -718,6 +724,69 @@ public abstract class BasePlugin { } } + protected void createNdkTasks(@NonNull BaseVariantData variantData) { + NdkCompile ndkCompile = project.tasks.create( + "compile${variantData.name}Ndk", NdkCompile) + + ndkCompile.plugin = this + ndkCompile.variant = variantData + variantData.ndkCompileTask = ndkCompile + + VariantConfiguration variantConfig = variantData.variantConfiguration + + ndkCompile.conventionMapping.sourceFolders = { + + Set<File> sourceList = Sets.newHashSet() + + sourceList.addAll(((AndroidSourceSet) variantConfig.defaultSourceSet).jni.srcDirs) + + if (variantConfig.getType() != VariantConfiguration.Type.TEST) { + sourceList.addAll(((AndroidSourceSet) variantConfig.buildTypeSourceSet).jni.srcDirs) + } + if (variantConfig.hasFlavors()) { + for (SourceProvider flavorSourceSet : variantConfig.flavorSourceSets) { + sourceList.addAll(((AndroidSourceSet) flavorSourceSet).jni.srcDirs) + } + } + + return sourceList + } + + ndkCompile.conventionMapping.generatedMakefile = { + project.file("$project.buildDir/ndk/$variantData.dirName/Android.mk") + } + + ndkCompile.conventionMapping.ndkConfig = { + + //noinspection GroovyAssignabilityCheck + NdkConfigDsl mergedConfig = new NdkConfigDsl(variantConfig.defaultConfig.ndkConfig) + if (variantConfig.hasFlavors()) { + for (DefaultProductFlavor flavorConfig : variantConfig.flavorConfigs) { + //noinspection GroovyAssignabilityCheck + mergedConfig.append(flavorConfig.ndkConfig) + } + } + if (variantConfig.getType() != VariantConfiguration.Type.TEST) { + //noinspection GroovyAssignabilityCheck + mergedConfig.append(variantConfig.buildType.ndkConfig) + } + + return mergedConfig + } + + ndkCompile.conventionMapping.debuggable = { + variantConfig.buildType.jniDebugBuild + } + + ndkCompile.conventionMapping.objFolder = { + project.file("$project.buildDir/ndk/$variantData.dirName/obj") + } + + ndkCompile.conventionMapping.soFolder = { + project.file("$project.buildDir/ndk/$variantData.dirName/lib") + } + } + /** * Creates the tasks to build the test apk. * @@ -770,6 +839,9 @@ public abstract class BasePlugin { // Add a task to compile the test application createCompileTask(variantData, testedVariantData) + // Add NDK tasks + createNdkTasks(variantData) + addPackageTasks(variantData, null) if (assembleTest != null) { @@ -1166,7 +1238,7 @@ public abstract class BasePlugin { // Add a task to generate application package def packageApp = project.tasks.create("package${variantData.name}", PackageApplication) variantData.packageApplicationTask = packageApp - packageApp.dependsOn variantData.processResourcesTask, dexTask, variantData.processJavaResources + packageApp.dependsOn variantData.processResourcesTask, dexTask, variantData.processJavaResourcesTask, variantData.ndkCompileTask packageApp.plugin = this packageApp.variant = variantData @@ -1179,7 +1251,15 @@ public abstract class BasePlugin { packageApp.conventionMapping.dexFile = { dexTask.outputFile } packageApp.conventionMapping.packagedJars = { config.packagedJars } packageApp.conventionMapping.javaResourceDir = { - getOptionalDir(variantData.processJavaResources.destinationDir) + getOptionalDir(variantData.processJavaResourcesTask.destinationDir) + } + packageApp.conventionMapping.jniFolders = { + // for now only the project's compilation output. + // TODO add dependencies + Collections.singleton(variantData.ndkCompileTask.soFolder) + } + packageApp.conventionMapping.abiFilters = { + variantData.ndkCompileTask.getNdkConfig().abiFilters } packageApp.conventionMapping.jniDebugBuild = { config.buildType.jniDebugBuild } diff --git a/gradle/src/main/groovy/com/android/build/gradle/LibraryExtension.groovy b/gradle/src/main/groovy/com/android/build/gradle/LibraryExtension.groovy index 6d6015b..e1cf6a3 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/LibraryExtension.groovy +++ b/gradle/src/main/groovy/com/android/build/gradle/LibraryExtension.groovy @@ -45,9 +45,12 @@ public class LibraryExtension extends BaseExtension { BuilderConstants.DEBUG) debugSigningConfig.initDebug() - debug = instantiator.newInstance(BuildTypeDsl.class, BuilderConstants.DEBUG, project.fileResolver) + debug = instantiator.newInstance(BuildTypeDsl.class, + BuilderConstants.DEBUG, project.fileResolver, instantiator) debug.init(debugSigningConfig) - release = instantiator.newInstance(BuildTypeDsl.class, BuilderConstants.RELEASE, project.fileResolver) + + release = instantiator.newInstance(BuildTypeDsl.class, + BuilderConstants.RELEASE, project.fileResolver, instantiator) release.init(null) } diff --git a/gradle/src/main/groovy/com/android/build/gradle/LibraryPlugin.groovy b/gradle/src/main/groovy/com/android/build/gradle/LibraryPlugin.groovy index 9df0ce1..c45a827 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/LibraryPlugin.groovy +++ b/gradle/src/main/groovy/com/android/build/gradle/LibraryPlugin.groovy @@ -232,6 +232,9 @@ public class LibraryPlugin extends BasePlugin implements Plugin<Project> { // Add a compile task createCompileTask(variantData, null/*testedVariant*/) + // Add NDK tasks + createNdkTasks(variantData) + // package the aidl files into the bundle folder Sync packageAidl = project.tasks.create("package${variantData.name}Aidl", Sync) // packageAidl from 3 sources. the order is important to make sure the override works well. @@ -281,9 +284,9 @@ public class LibraryPlugin extends BasePlugin implements Plugin<Project> { // jar the classes. Jar jar = project.tasks.create("package${buildType.name.capitalize()}Jar", Jar); - jar.dependsOn variantData.javaCompileTask, variantData.processJavaResources + jar.dependsOn variantData.javaCompileTask, variantData.processJavaResourcesTask jar.from(variantData.javaCompileTask.outputs); - jar.from(variantData.processJavaResources.destinationDir) + jar.from(variantData.processJavaResourcesTask.destinationDir) jar.destinationDir = project.file("$project.buildDir/$DIR_BUNDLES/${variantData.dirName}") jar.archiveName = "classes.jar" diff --git a/gradle/src/main/groovy/com/android/build/gradle/internal/Sdk.groovy b/gradle/src/main/groovy/com/android/build/gradle/internal/Sdk.groovy index 022239c..88c8726 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/internal/Sdk.groovy +++ b/gradle/src/main/groovy/com/android/build/gradle/internal/Sdk.groovy @@ -43,6 +43,7 @@ public class Sdk { private boolean isSdkParserInitialized = false private File androidSdkDir + private File androidNdkDir private boolean isPlatformSdk = false private BaseExtension extension @@ -80,7 +81,7 @@ public class Sdk { if (isPlatformSdk) { parser = new PlatformSdkParser(androidSdkDir.absolutePath) } else { - parser = new DefaultSdkParser(androidSdkDir.absolutePath) + parser = new DefaultSdkParser(androidSdkDir.absolutePath, androidNdkDir) } List<File> repositories = parser.repositories @@ -130,11 +131,16 @@ public class Sdk { return theParser } - public File getDirectory() { + public File getSdkDirectory() { checkLocation() return androidSdkDir } + public File getNdkDirectory() { + checkLocation() + return androidNdkDir + } + private void checkLocation() { // don't complain in test mode if (TEST_SDK_DIR != null) { @@ -179,6 +185,12 @@ public class Sdk { "No sdk.dir property defined in local.properties file.") } } + + def ndkDirProp = properties.getProperty('ndk.dir') + if (ndkDirProp != null) { + androidNdkDir = new File(ndkDirProp) + } + } else { String envVar = System.getenv("ANDROID_HOME") if (envVar != null) { @@ -189,6 +201,11 @@ public class Sdk { androidSdkDir = new File(property) } } + + envVar = System.getenv("ANDROID_NDK_HOME") + if (envVar != null) { + androidNdkDir = new File(envVar) + } } } } diff --git a/gradle/src/main/groovy/com/android/build/gradle/internal/api/ApplicationVariantImpl.java b/gradle/src/main/groovy/com/android/build/gradle/internal/api/ApplicationVariantImpl.java index efbbad3..ed0afe4 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/internal/api/ApplicationVariantImpl.java +++ b/gradle/src/main/groovy/com/android/build/gradle/internal/api/ApplicationVariantImpl.java @@ -172,7 +172,7 @@ public class ApplicationVariantImpl implements ApplicationVariant { @Override @NonNull public Copy getProcessJavaResources() { - return variantData.processJavaResources; + return variantData.processJavaResourcesTask; } @Override diff --git a/gradle/src/main/groovy/com/android/build/gradle/internal/api/LibraryVariantImpl.java b/gradle/src/main/groovy/com/android/build/gradle/internal/api/LibraryVariantImpl.java index a4acfd6..7ed4c6b 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/internal/api/LibraryVariantImpl.java +++ b/gradle/src/main/groovy/com/android/build/gradle/internal/api/LibraryVariantImpl.java @@ -158,7 +158,7 @@ public class LibraryVariantImpl implements LibraryVariant { @Override @NonNull public Copy getProcessJavaResources() { - return variantData.processJavaResources; + return variantData.processJavaResourcesTask; } @Override diff --git a/gradle/src/main/groovy/com/android/build/gradle/internal/api/TestVariantImpl.java b/gradle/src/main/groovy/com/android/build/gradle/internal/api/TestVariantImpl.java index 305c2e5..37eb618 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/internal/api/TestVariantImpl.java +++ b/gradle/src/main/groovy/com/android/build/gradle/internal/api/TestVariantImpl.java @@ -170,7 +170,7 @@ public class TestVariantImpl implements TestVariant { @Override @NonNull public Copy getProcessJavaResources() { - return variantData.processJavaResources; + return variantData.processJavaResourcesTask; } @Override diff --git a/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/BuildTypeDsl.groovy b/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/BuildTypeDsl.groovy index e8fa660..8a3cf68 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/BuildTypeDsl.groovy +++ b/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/BuildTypeDsl.groovy @@ -19,7 +19,9 @@ import com.android.annotations.NonNull import com.android.builder.BuilderConstants import com.android.builder.DefaultBuildType import com.android.builder.model.SigningConfig +import org.gradle.api.Action import org.gradle.api.internal.file.FileResolver +import org.gradle.internal.reflect.Instantiator /** * DSL overlay to make methods that accept String... work. @@ -30,9 +32,14 @@ public class BuildTypeDsl extends DefaultBuildType implements Serializable { @NonNull private final FileResolver fileResolver - BuildTypeDsl(@NonNull String name, @NonNull FileResolver fileResolver) { + private final NdkConfigDsl ndkConfig + + BuildTypeDsl(@NonNull String name, + @NonNull FileResolver fileResolver, + @NonNull Instantiator instantiator) { super(name) this.fileResolver = fileResolver + ndkConfig = instantiator.newInstance(NdkConfigDsl.class) } public void init(SigningConfig debugSigningConfig) { @@ -56,6 +63,10 @@ public class BuildTypeDsl extends DefaultBuildType implements Serializable { return true } + public NdkConfigDsl getNdkConfig() { + return ndkConfig + } + // -- DSL Methods. TODO remove once the instantiator does what I expect it to do. public void buildConfig(String... lines) { @@ -101,4 +112,8 @@ public class BuildTypeDsl extends DefaultBuildType implements Serializable { } return this; } + + void ndk(Action<NdkConfigDsl> action) { + action.execute(ndkConfig) + } } diff --git a/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/BuildTypeFactory.java b/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/BuildTypeFactory.java index 3bdfe19..486727e 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/BuildTypeFactory.java +++ b/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/BuildTypeFactory.java @@ -40,6 +40,6 @@ public class BuildTypeFactory implements NamedDomainObjectFactory<DefaultBuildTy @Override public DefaultBuildType create(String name) { - return instantiator.newInstance(BuildTypeDsl.class, name, fileResolver); + return instantiator.newInstance(BuildTypeDsl.class, name, fileResolver, instantiator); } } diff --git a/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/GroupableProductFlavorDsl.groovy b/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/GroupableProductFlavorDsl.groovy index d60334b..621ac85 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/GroupableProductFlavorDsl.groovy +++ b/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/GroupableProductFlavorDsl.groovy @@ -18,6 +18,7 @@ package com.android.build.gradle.internal.dsl import com.android.annotations.NonNull import org.gradle.api.internal.file.FileResolver +import org.gradle.internal.reflect.Instantiator /** * A version of ProductFlavorDsl that can receive a group name @@ -27,7 +28,10 @@ public class GroupableProductFlavorDsl extends ProductFlavorDsl { String flavorGroup - public GroupableProductFlavorDsl(@NonNull String name, @NonNull FileResolver fileResolver) { - super(name, fileResolver) + public GroupableProductFlavorDsl( + @NonNull String name, + @NonNull FileResolver fileResolver, + @NonNull Instantiator instantiator) { + super(name, fileResolver, instantiator) } } diff --git a/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/GroupableProductFlavorFactory.java b/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/GroupableProductFlavorFactory.java index 7ad9043..ed422d9 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/GroupableProductFlavorFactory.java +++ b/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/GroupableProductFlavorFactory.java @@ -40,6 +40,7 @@ class GroupableProductFlavorFactory implements NamedDomainObjectFactory<Groupabl @Override public GroupableProductFlavorDsl create(String name) { - return instantiator.newInstance(GroupableProductFlavorDsl.class, name, fileResolver); + return instantiator.newInstance(GroupableProductFlavorDsl.class, + name, fileResolver, instantiator); } } diff --git a/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/NdkConfigDsl.java b/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/NdkConfigDsl.java new file mode 100644 index 0000000..8765f3b --- /dev/null +++ b/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/NdkConfigDsl.java @@ -0,0 +1,142 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.build.gradle.internal.dsl; + +import com.android.annotations.NonNull; +import com.google.common.collect.Sets; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.Optional; + +import java.io.Serializable; +import java.util.Collections; +import java.util.Set; + +/** + */ +public class NdkConfigDsl implements Serializable { + private static final long serialVersionUID = 1L; + + private String moduleName; + private String cFlags; + private String ldLibs; + private Set<String> abiFilters; + + public NdkConfigDsl() { + } + + public NdkConfigDsl(@NonNull NdkConfigDsl ndkConfig) { + moduleName = ndkConfig.moduleName; + cFlags = ndkConfig.cFlags; + ldLibs = ndkConfig.ldLibs; + setSrcDirs(ndkConfig.abiFilters); + } + + @Input @Optional + public String getModuleName() { + return moduleName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } + + @Input @Optional + public String getcFlags() { + return cFlags; + } + + public void setcFlags(String cFlags) { + this.cFlags = cFlags; + } + + @Input @Optional + public String getLdLibs() { + return ldLibs; + } + + public void setLdLibs(String ldLibs) { + this.ldLibs = ldLibs; + } + + @Input @Optional + public Set<String> getAbiFilters() { + return abiFilters; + } + + @NonNull + public NdkConfigDsl abiFilter(String filter) { + if (abiFilters == null) { + abiFilters = Sets.newHashSetWithExpectedSize(2); + } + abiFilters.add(filter); + return this; + } + + @NonNull + public NdkConfigDsl abiFilters(String... filters) { + if (abiFilters == null) { + abiFilters = Sets.newHashSetWithExpectedSize(2); + } + Collections.addAll(abiFilters, filters); + return this; + } + + @NonNull + public NdkConfigDsl setSrcDirs(Iterable<String> filters) { + if (filters != null) { + if (abiFilters == null) { + abiFilters = Sets.newHashSetWithExpectedSize(2); + } else { + abiFilters.clear(); + } + for (String filter : filters) { + abiFilters.add(filter); + } + } else { + abiFilters = null; + } + return this; + } + + public void append(@NonNull NdkConfigDsl ndkConfig) { + // override + if (ndkConfig.moduleName != null) { + moduleName = ndkConfig.moduleName; + } + if (ndkConfig.abiFilters != null) { + if (abiFilters == null) { + abiFilters = Sets.newHashSetWithExpectedSize(ndkConfig.abiFilters.size()); + } else { + abiFilters.clear(); + } + abiFilters.addAll(ndkConfig.abiFilters); + } + + // append + if (cFlags == null) { + cFlags = ndkConfig.cFlags; + } else if (ndkConfig.cFlags != null) { + cFlags = cFlags + " " + ndkConfig.cFlags; + } + + if (ldLibs == null) { + ldLibs = ndkConfig.ldLibs; + } else if (ndkConfig.ldLibs != null) { + ldLibs = ldLibs + " " + ndkConfig.ldLibs; + } + } +} diff --git a/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/ProductFlavorDsl.groovy b/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/ProductFlavorDsl.groovy index 4ae05cb..daeb0ff 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/ProductFlavorDsl.groovy +++ b/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/ProductFlavorDsl.groovy @@ -17,8 +17,9 @@ package com.android.build.gradle.internal.dsl import com.android.annotations.NonNull import com.android.builder.DefaultProductFlavor +import org.gradle.api.Action import org.gradle.api.internal.file.FileResolver - +import org.gradle.internal.reflect.Instantiator /** * DSL overlay to make methods that accept String... work. */ @@ -28,9 +29,19 @@ class ProductFlavorDsl extends DefaultProductFlavor { @NonNull private final FileResolver fileResolver - ProductFlavorDsl(String name, @NonNull FileResolver fileResolver) { + private final NdkConfigDsl ndkConfig + + ProductFlavorDsl(@NonNull String name, + @NonNull FileResolver fileResolver, + @NonNull Instantiator instantiator) { super(name) this.fileResolver = fileResolver + + ndkConfig = instantiator.newInstance(NdkConfigDsl.class) + } + + public NdkConfigDsl getNdkConfig() { + return ndkConfig } // -- DSL Methods. TODO remove once the instantiator does what I expect it to do. @@ -45,37 +56,41 @@ class ProductFlavorDsl extends DefaultProductFlavor { @NonNull public ProductFlavorDsl proguardFile(Object proguardFile) { - proguardFiles.add(fileResolver.resolve(proguardFile)); - return this; + proguardFiles.add(fileResolver.resolve(proguardFile)) + return this } @NonNull public ProductFlavorDsl proguardFiles(Object... proguardFileArray) { - proguardFiles.addAll(fileResolver.resolveFiles(proguardFileArray).files); - return this; + proguardFiles.addAll(fileResolver.resolveFiles(proguardFileArray).files) + return this } @NonNull public ProductFlavorDsl setProguardFiles(Iterable<?> proguardFileIterable) { - proguardFiles.clear(); + proguardFiles.clear() for (Object proguardFile : proguardFileIterable) { - proguardFiles.add(fileResolver.resolve(proguardFile)); + proguardFiles.add(fileResolver.resolve(proguardFile)) } - return this; + return this } @NonNull public ProductFlavorDsl consumerProguardFiles(Object... proguardFileArray) { - consumerProguardFiles.addAll(fileResolver.resolveFiles(proguardFileArray).files); - return this; + consumerProguardFiles.addAll(fileResolver.resolveFiles(proguardFileArray).files) + return this } @NonNull public ProductFlavorDsl setconsumerProguardFiles(Iterable<?> proguardFileIterable) { - consumerProguardFiles.clear(); + consumerProguardFiles.clear() for (Object proguardFile : proguardFileIterable) { - consumerProguardFiles.add(fileResolver.resolve(proguardFile)); + consumerProguardFiles.add(fileResolver.resolve(proguardFile)) } - return this; + return this + } + + void ndk(Action<NdkConfigDsl> action) { + action.execute(ndkConfig) } } diff --git a/gradle/src/main/groovy/com/android/build/gradle/internal/model/ProductFlavorImpl.java b/gradle/src/main/groovy/com/android/build/gradle/internal/model/ProductFlavorImpl.java index dbd30d6..37e022d 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/internal/model/ProductFlavorImpl.java +++ b/gradle/src/main/groovy/com/android/build/gradle/internal/model/ProductFlavorImpl.java @@ -44,7 +44,6 @@ class ProductFlavorImpl implements ProductFlavor, Serializable { private Boolean mTestHandleProfiling = null; private Boolean mTestFunctionalTest = null; - @NonNull static ProductFlavorImpl cloneFlavor(ProductFlavor productFlavor) { ProductFlavorImpl clonedFlavor = new ProductFlavorImpl(); diff --git a/gradle/src/main/groovy/com/android/build/gradle/internal/variant/BaseVariantData.java b/gradle/src/main/groovy/com/android/build/gradle/internal/variant/BaseVariantData.java index db804f9..a85d8be 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/internal/variant/BaseVariantData.java +++ b/gradle/src/main/groovy/com/android/build/gradle/internal/variant/BaseVariantData.java @@ -24,6 +24,7 @@ import com.android.build.gradle.tasks.AidlCompile; import com.android.build.gradle.tasks.GenerateBuildConfig; import com.android.build.gradle.tasks.MergeAssets; import com.android.build.gradle.tasks.MergeResources; +import com.android.build.gradle.tasks.NdkCompile; import com.android.build.gradle.tasks.ProcessAndroidResources; import com.android.build.gradle.tasks.ProcessManifest; import com.android.build.gradle.tasks.RenderscriptCompile; @@ -61,7 +62,8 @@ public abstract class BaseVariantData { public JavaCompile javaCompileTask; public ProGuardTask proguardTask; - public Copy processJavaResources; + public Copy processJavaResourcesTask; + public NdkCompile ndkCompileTask; private Object outputFile; diff --git a/gradle/src/main/groovy/com/android/build/gradle/tasks/NdkCompile.groovy b/gradle/src/main/groovy/com/android/build/gradle/tasks/NdkCompile.groovy new file mode 100644 index 0000000..ab38543 --- /dev/null +++ b/gradle/src/main/groovy/com/android/build/gradle/tasks/NdkCompile.groovy @@ -0,0 +1,199 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.build.gradle.tasks + +import com.android.annotations.NonNull +import com.android.build.gradle.internal.dsl.NdkConfigDsl +import com.android.build.gradle.internal.tasks.BaseTask +import com.android.sdklib.IAndroidTarget +import com.google.common.base.Charsets +import com.google.common.base.Joiner +import com.google.common.collect.Lists +import com.google.common.io.Files +import org.gradle.api.GradleException +import org.gradle.api.file.FileTree +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.Nested +import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.TaskAction +import org.gradle.api.tasks.incremental.IncrementalTaskInputs +import org.gradle.api.tasks.util.PatternSet + +/** + */ +class NdkCompile extends BaseTask { + + Set<File> sourceFolders + + @OutputFile + File generatedMakefile + + @Nested + NdkConfigDsl ndkConfig + + @Input + boolean debuggable + + @OutputDirectory + File soFolder + + @OutputDirectory + File objFolder + + @InputFiles + public FileTree getSource() { + FileTree src = null + Set<File> sources = getSourceFolders() + if (!sources.isEmpty()) { + src = getProject().files(new ArrayList<Object>(sources)).getAsFileTree() + } + return src == null ? getProject().files().getAsFileTree() : src + } + + @TaskAction + void taskAction(IncrementalTaskInputs inputs) { + + FileTree sourceFileTree = getSource() + Set<File> sourceFiles = sourceFileTree.matching(new PatternSet().exclude("**/*.h")).files + File makefile = getGeneratedMakefile() + + if (sourceFiles.isEmpty()) { + makefile.delete() + emptyFolder(getSoFolder()) + emptyFolder(getObjFolder()) + return + } + + File ndkDirectory = getPlugin().ndkDirectory + if (ndkDirectory == null || !ndkDirectory.isDirectory()) { + throw new GradleException("NDK not configured") + } + + boolean generateMakefile = false + + if (!inputs.isIncremental()) { + project.logger.info("Unable do incremental execution: full task run") + generateMakefile = true + emptyFolder(getSoFolder()) + emptyFolder(getObjFolder()) + } else { + // look for added or removed files *only* + + //noinspection GroovyAssignabilityCheck + inputs.outOfDate { change -> + if (change.isAdded()) { + generateMakefile = true + } + } + + //noinspection GroovyAssignabilityCheck + inputs.removed { change -> + generateMakefile = true + } + } + + if (generateMakefile) { + writeMakefile(sourceFiles, makefile) + } + + // now build + runNdkBuild(ndkDirectory, makefile) + } + + private void writeMakefile(@NonNull Set<File> sourceFiles, @NonNull File makefile) { + NdkConfigDsl ndk = getNdkConfig() + + StringBuilder sb = new StringBuilder() + + sb.append( + "LOCAL_PATH := \$(call my-dir)\n" + + "include \$(CLEAR_VARS)\n\n") + + sb.append("LOCAL_MODULE := ").append(ndk.moduleName != null ? ndk.moduleName : project.name).append('\n') + + if (ndk.cFlags != null) { + sb.append("LOCAL_CFLAGS := ").append(ndk.cFlags).append('\n') + } + + if (ndk.ldLibs != null) { + sb.append("LOCAL_LDLIBS := ").append(ndk.ldLibs).append('\n') + } + + sb.append("LOCAL_SRC_FILES := \\\n") + for (File sourceFile : sourceFiles) { + sb.append('\t').append(sourceFile.absolutePath).append(" \\\n") + } + sb.append('\n') + + sb.append( + "\ninclude \$(BUILD_SHARED_LIBRARY)\n") + + Files.write(sb.toString(), makefile, Charsets.UTF_8) + } + + private void runNdkBuild(@NonNull File ndkLocation, @NonNull File makefile) { + NdkConfigDsl ndk = getNdkConfig() + + List<String> commands = Lists.newArrayList() + + commands.add(ndkLocation.absolutePath + File.separator + "ndk-build") + + commands.add("NDK_PROJECT_PATH=null") + + commands.add("APP_BUILD_SCRIPT=" + makefile.absolutePath) + + // target + IAndroidTarget target = getPlugin().loadedSdkParser.target + if (!target.isPlatform()) { + target = target.parent + } + commands.add("APP_PLATFORM=" + target.hashString()) + + // include paths + for (File sourceFolder : getSourceFolders()) { + commands.add("-I") + commands.add(sourceFolder.absolutePath) + } + + // temp out + commands.add("NDK_OUT=" + getObjFolder().absolutePath) + + // libs out + commands.add("NDK_LIBS_OUT=" + getSoFolder().absolutePath) + + // debug builds + if (getDebuggable()) { + commands.add("NDK_DEBUG=1") + } + + Set<String> abiFilters = ndk.abiFilters + if (abiFilters != null && !abiFilters.isEmpty()) { + if (abiFilters.size() == 1) { + commands.add("APP_ABI=" + abiFilters.iterator().next()) + } else { + Joiner joiner = Joiner.on(',').skipNulls() + commands.add("APP_ABI=" + joiner.join(abiFilters.iterator())) + } + } else { + commands.add("APP_ABI=all") + } + + getBuilder().commandLineRunner.runCmdLine(commands, null) + } +} diff --git a/gradle/src/main/groovy/com/android/build/gradle/tasks/PackageApplication.groovy b/gradle/src/main/groovy/com/android/build/gradle/tasks/PackageApplication.groovy index 549d765..fd827c1 100644 --- a/gradle/src/main/groovy/com/android/build/gradle/tasks/PackageApplication.groovy +++ b/gradle/src/main/groovy/com/android/build/gradle/tasks/PackageApplication.groovy @@ -19,6 +19,7 @@ import com.android.build.gradle.internal.dsl.SigningConfigDsl import com.android.build.gradle.internal.tasks.IncrementalTask import com.android.build.gradle.internal.tasks.OutputFileTask import com.android.builder.packaging.DuplicateFileException +import org.gradle.api.file.FileTree import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputDirectory import org.gradle.api.tasks.InputFile @@ -41,12 +42,14 @@ public class PackageApplication extends IncrementalTask implements OutputFileTas @InputDirectory @Optional File javaResourceDir - @InputDirectory @Optional - File jniDir + Set<File> jniFolders @OutputFile File outputFile + @Input @Optional + Set<String> abiFilters + // ----- PRIVATE TASK API ----- @InputFiles @@ -58,6 +61,17 @@ public class PackageApplication extends IncrementalTask implements OutputFileTas @Nested @Optional SigningConfigDsl signingConfig + @InputFiles + public FileTree getNativeLibraries() { + FileTree src = null + Set<File> folders = getJniFolders() + if (!folders.isEmpty()) { + src = getProject().files(new ArrayList<Object>(folders)).getAsFileTree() + } + return src == null ? getProject().files().getAsFileTree() : src + } + + @Override protected void doFullTaskAction() { try { @@ -66,7 +80,8 @@ public class PackageApplication extends IncrementalTask implements OutputFileTas getDexFile().absolutePath, getPackagedJars(), getJavaResourceDir()?.absolutePath, - getJniDir()?.absolutePath, + getJniFolders(), + getAbiFilters(), getJniDebugBuild(), getSigningConfig(), getOutputFile().absolutePath) @@ -81,5 +96,4 @@ public class PackageApplication extends IncrementalTask implements OutputFileTas throw new BuildException(e.getMessage(), e); } } - } diff --git a/gradle/src/test/groovy/com/android/build/gradle/internal/dsl/BuildTypeDslTest.groovy b/gradle/src/test/groovy/com/android/build/gradle/internal/dsl/BuildTypeDslTest.groovy index 3744b79..c63b2e9 100644 --- a/gradle/src/test/groovy/com/android/build/gradle/internal/dsl/BuildTypeDslTest.groovy +++ b/gradle/src/test/groovy/com/android/build/gradle/internal/dsl/BuildTypeDslTest.groovy @@ -74,7 +74,7 @@ public class BuildTypeDslTest extends BaseTest { Project project = ProjectBuilder.builder().withProjectDir( new File(testDir, "basic")).build() - BuildTypeDsl object1 = new BuildTypeDsl("foo", project.fileResolver) + BuildTypeDsl object1 = new BuildTypeDsl("foo", project.fileResolver, project.instantiator) // change every value from their default. object1.setDebuggable(true) @@ -87,7 +87,7 @@ public class BuildTypeDslTest extends BaseTest { object1.setSigningConfig(new SigningConfigDsl("blah")) object1.setZipAlign(false) - BuildTypeDsl object2 = new BuildTypeDsl(object1.name, project.fileResolver) + BuildTypeDsl object2 = new BuildTypeDsl(object1.name, project.fileResolver, project.instantiator) object2.initWith(object1) assertEquals(object1, object2) diff --git a/gradle/src/test/groovy/com/android/build/gradle/internal/test/BaseTest.groovy b/gradle/src/test/groovy/com/android/build/gradle/internal/test/BaseTest.groovy index 5a96009..ac62126 100755 --- a/gradle/src/test/groovy/com/android/build/gradle/internal/test/BaseTest.groovy +++ b/gradle/src/test/groovy/com/android/build/gradle/internal/test/BaseTest.groovy @@ -16,6 +16,7 @@ package com.android.build.gradle.internal.test import com.android.annotations.NonNull +import com.android.annotations.Nullable import com.android.sdklib.internal.project.ProjectProperties import com.android.sdklib.internal.project.ProjectPropertiesWorkingCopy import junit.framework.TestCase @@ -100,10 +101,31 @@ public abstract class BaseTest extends TestCase { return null } - protected static File createLocalProp(File project, File sdkDir) { + /** + * Returns the SDK folder as built from the Android source tree. + * @return + */ + protected File getNdkDir() { + String androidHome = System.getenv("ANDROID_NDK_HOME"); + if (androidHome != null) { + File f = new File(androidHome); + if (f.isDirectory()) { + return f; + } else { + System.out.println("Failed to find NDK in ANDROID_NDK_HOME=" + androidHome) + } + } + } + + protected static File createLocalProp(@NonNull File project, + @NonNull File sdkDir, + @Nullable File ndkDir) { ProjectPropertiesWorkingCopy localProp = ProjectProperties.create( project.absolutePath, ProjectProperties.PropertyType.LOCAL) localProp.setProperty(ProjectProperties.PROPERTY_SDK, sdkDir.absolutePath) + if (ndkDir != null) { + localProp.setProperty(ProjectProperties.PROPERTY_NDK, ndkDir.absolutePath) + } localProp.save() return (File) localProp.file @@ -112,14 +134,15 @@ public abstract class BaseTest extends TestCase { protected File runTasksOn(String name, String gradleVersion, String... tasks) { File project = new File(testDir, name) - runGradleTasks(sdkDir, gradleVersion, project, tasks) + runGradleTasks(sdkDir, ndkDir, gradleVersion, project, tasks) return project; } - protected static void runGradleTasks(File sdkDir, String gradleVersion, + protected static void runGradleTasks(File sdkDir, File ndkDir, + String gradleVersion, File project, String... tasks) { - File localProp = createLocalProp(project, sdkDir) + File localProp = createLocalProp(project, sdkDir, ndkDir) try { diff --git a/tests/3rdPartyTests/buildSrc/src/main/java/com/android/tests/basic/buildscript/FakeDevice.java b/tests/3rdPartyTests/buildSrc/src/main/java/com/android/tests/basic/buildscript/FakeDevice.java index 9fbe9e1..df810fe 100644 --- a/tests/3rdPartyTests/buildSrc/src/main/java/com/android/tests/basic/buildscript/FakeDevice.java +++ b/tests/3rdPartyTests/buildSrc/src/main/java/com/android/tests/basic/buildscript/FakeDevice.java @@ -12,6 +12,7 @@ import com.google.common.collect.Lists; import java.io.File; import java.io.IOException; +import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; @@ -120,8 +121,8 @@ public class FakeDevice extends DeviceConnector { } @NonNull - public String getAbi() { - return "fake"; + public List<String> getAbis() { + return Collections.singletonList("fake"); } public int getDensity() { diff --git a/tests/ndkSanAngeles/Android.mk b/tests/ndkSanAngeles/Android.mk new file mode 100644 index 0000000..5663edf --- /dev/null +++ b/tests/ndkSanAngeles/Android.mk @@ -0,0 +1,17 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := sanangeles + +LOCAL_CFLAGS := -DANDROID_NDK \ + -DDISABLE_IMPORTGL + +LOCAL_SRC_FILES := \ + importgl.c \ + demo.c \ + app-android.c \ + +LOCAL_LDLIBS := -lGLESv1_CM -ldl -llog + +include $(BUILD_SHARED_LIBRARY) diff --git a/tests/ndkSanAngeles/README.txt b/tests/ndkSanAngeles/README.txt new file mode 100644 index 0000000..38b8a4a --- /dev/null +++ b/tests/ndkSanAngeles/README.txt @@ -0,0 +1,77 @@ +------------------------------------------------------------------------
+San Angeles Observation OpenGL ES version example
+Copyright 2004-2005 Jetro Lauha
+Web: http://iki.fi/jetro/
+See file license.txt for licensing information.
+------------------------------------------------------------------------
+
+This is an OpenGL ES port of the small self-running demonstration
+called "San Angeles Observation", which was first presented in the
+Assembly'2004 event. It won the first place in the 4 KB intro
+competition category.
+
+The demonstration features a sightseeing of a futuristic city
+having many different kind of buildings and items. Everything is
+flat shaded with three different lights.
+
+The original version was made for desktop with OpenGL. It was
+naturally heavily size optimized in order to fit it in the size
+limit. For this OpenGL ES version example much of the code is
+cleaned up and the sound is removed. Also detail level is lowered,
+although it still contains over 60000 faces.
+
+The Win32 (2000/XP) binary package of original version is
+available from this address: http://jet.ro/files/angeles.zip
+
+First version of this OpenGL ES port was submitted to the Khronos
+OpenGL ES Coding Challenge held in 2004-2005.
+
+As a code example, this source shows the following:
+ * How to create a minimal and portable ad hoc framework
+ for small testing/demonstration programs. This framework
+ compiles for both desktop and PocketPC Win32 environment,
+ and a separate source is included for Linux with X11.
+ * How to dynamically find and use the OpenGL ES DLL or
+ shared object, so that the library is not needed at
+ the compile/link stage.
+ * How to use the basic features of OpenGL ES 1.0/1.1
+ Common Lite, such as vertex arrays, color arrays and
+ lighting.
+ * How to create a self contained small demonstration
+ application with objects generated using procedural
+ algorithms.
+
+As the original version was optimized for size instead of
+performance, that holds true for this OpenGL ES version as
+well. Thus the performance could be significantly increased,
+for example by changing the code to use glDrawElements
+instead of glDrawArrays. The code uses only OpenGL ES 1.0
+Common Lite -level function calls without any extensions.
+
+The reference OpenGL ES implementations used for this application:
+ * Hybrid's OpenGL ES API Implementation (Gerbera) version 2.0.4
+ Prebuilt Win32 PC executable: SanOGLES-Gerbera.exe
+ * PowerVR MBX SDK, OpenGL ES Windows PC Emulation version 1.04.14.0170
+ Prebuilt Win32 PC executable: SanOGLES-PVRSDK.exe
+
+Note that DISABLE_IMPORTGL preprocessor macro can be used
+to specify not to use dynamic runtime binding of the library.
+You also need to define preprocessor macro PVRSDK to compile
+the source with PowerVR OpenGL ES SDK.
+
+The demo application is briefly tested with a few other OpenGL ES
+implementations as well (e.g. Vincent, GLESonGL on Linux, Dell
+Axim X50v). Most of these other implementations rendered the demo
+erroneously in some aspect. This may indicate that the demo source
+could still have some work to do with compatibility and correct
+API usage, although the non-conforming implementations are most
+probably unfinished as well.
+
+Thanks and Acknowledgements:
+
+* Toni Lönnberg (!Cube) created the music for original version, which
+ is not featured in this OpenGL ES port.
+* Sara Kapli (st Rana) for additional camera work.
+* Paul Bourke for information about the supershapes.
+
+------------------------------------------------------------------------
diff --git a/tests/ndkSanAngeles/build.gradle b/tests/ndkSanAngeles/build.gradle new file mode 100644 index 0000000..6f28e85 --- /dev/null +++ b/tests/ndkSanAngeles/build.gradle @@ -0,0 +1,40 @@ +buildscript { + repositories { + maven { url '../../../../out/host/gradle/repo' } + } + dependencies { + classpath 'com.android.tools.build:gradle:0.6.2-SNAPSHOT' + } +} +apply plugin: 'android' + +android { + compileSdkVersion 15 + buildToolsVersion "18.0.1" + + defaultConfig { + ndk { + moduleName "sanangeles" + cFlags "-DANDROID_NDK -DDISABLE_IMPORTGL" + ldLibs "-lGLESv1_CM -ldl -llog" + } + } + + productFlavors { + x86 { + ndk { + abiFilter "x86" + } + } + arm { + ndk { + abiFilter "armeabi-v7a" + } + } + mips { + ndk { + abiFilter "mips" + } + } + } +}
\ No newline at end of file diff --git a/tests/ndkSanAngeles/license-BSD.txt b/tests/ndkSanAngeles/license-BSD.txt new file mode 100644 index 0000000..8924e3c --- /dev/null +++ b/tests/ndkSanAngeles/license-BSD.txt @@ -0,0 +1,34 @@ +This is the BSD-style license for the "San Angeles Observation"
+OpenGL ES version example source code
+---------------------------------------------------------------
+
+San Angeles Observation OpenGL ES version example
+Copyright (c) 2004-2005, Jetro Lauha
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+ * Neither the name of the software product's copyright owner nor
+ the names of its contributors may be used to endorse or promote
+ products derived from this software without specific prior written
+ permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/tests/ndkSanAngeles/license-LGPL.txt b/tests/ndkSanAngeles/license-LGPL.txt new file mode 100644 index 0000000..b1e3f5a --- /dev/null +++ b/tests/ndkSanAngeles/license-LGPL.txt @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + <one line to give the library's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + <signature of Ty Coon>, 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/tests/ndkSanAngeles/license.txt b/tests/ndkSanAngeles/license.txt new file mode 100644 index 0000000..620841e --- /dev/null +++ b/tests/ndkSanAngeles/license.txt @@ -0,0 +1,19 @@ +San Angeles Observation OpenGL ES version example
+Copyright 2004-2005 Jetro Lauha
+All rights reserved.
+Web: http://iki.fi/jetro/
+
+This source is free software; you can redistribute it and/or
+modify it under the terms of EITHER:
+ (1) The GNU Lesser General Public License as published by the Free
+ Software Foundation; either version 2.1 of the License, or (at
+ your option) any later version. The text of the GNU Lesser
+ General Public License is included with this source in the
+ file LICENSE-LGPL.txt.
+ (2) The BSD-style license that is included with this source in
+ the file LICENSE-BSD.txt.
+
+This source is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files
+LICENSE-LGPL.txt and LICENSE-BSD.txt for more details.
diff --git a/tests/ndkSanAngeles/misc/app-linux.c b/tests/ndkSanAngeles/misc/app-linux.c new file mode 100644 index 0000000..6b573f2 --- /dev/null +++ b/tests/ndkSanAngeles/misc/app-linux.c @@ -0,0 +1,247 @@ +/* San Angeles Observation OpenGL ES version example + * Copyright 2004-2005 Jetro Lauha + * All rights reserved. + * Web: http://iki.fi/jetro/ + * + * This source is free software; you can redistribute it and/or + * modify it under the terms of EITHER: + * (1) The GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at + * your option) any later version. The text of the GNU Lesser + * General Public License is included with this source in the + * file LICENSE-LGPL.txt. + * (2) The BSD-style license that is included with this source in + * the file LICENSE-BSD.txt. + * + * This source is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files + * LICENSE-LGPL.txt and LICENSE-BSD.txt for more details. + * + * $Id: app-linux.c,v 1.4 2005/02/08 18:42:48 tonic Exp $ + * $Revision: 1.4 $ + * + * Parts of this source file is based on test/example code from + * GLESonGL implementation by David Blythe. Here is copy of the + * license notice from that source: + * + * Copyright (C) 2003 David Blythe All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * DAVID BLYTHE BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include <stdlib.h> +#include <stdio.h> +#include <sys/time.h> +#include <X11/Xlib.h> +#include <X11/Xutil.h> +#include <X11/keysym.h> + +#include "importgl.h" + +#include "app.h" + + +int gAppAlive = 1; + +static const char sAppName[] = + "San Angeles Observation OpenGL ES version example (Linux)"; +static Display *sDisplay; +static Window sWindow; +static int sWindowWidth = WINDOW_DEFAULT_WIDTH; +static int sWindowHeight = WINDOW_DEFAULT_HEIGHT; +static EGLDisplay sEglDisplay = EGL_NO_DISPLAY; +static EGLConfig sEglConfig; +static EGLContext sEglContext = EGL_NO_CONTEXT; +static EGLSurface sEglSurface = EGL_NO_SURFACE; + + +static void checkGLErrors() +{ + GLenum error = glGetError(); + if (error != GL_NO_ERROR) + fprintf(stderr, "GL Error: 0x%04x\n", (int)error); +} + + +static void checkEGLErrors() +{ + EGLint error = eglGetError(); + // GLESonGL seems to be returning 0 when there is no errors? + if (error && error != EGL_SUCCESS) + fprintf(stderr, "EGL Error: 0x%04x\n", (int)error); +} + + +// Initializes and opens both X11 display and OpenGL ES. +static int initGraphics() +{ + static const EGLint configAttribs[] = + { +#if (WINDOW_BPP == 16) + EGL_RED_SIZE, 5, + EGL_GREEN_SIZE, 5, + EGL_BLUE_SIZE, 5, +#elif (WINDOW_BPP == 32) + EGL_RED_SIZE, 8, + EGL_GREEN_SIZE, 8, + EGL_BLUE_SIZE, 8, +#else +#error WINDOW_BPP must be 16 or 32 +#endif + EGL_DEPTH_SIZE, 16, + EGL_ALPHA_SIZE, EGL_DONT_CARE, + EGL_STENCIL_SIZE, EGL_DONT_CARE, + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_NONE + }; + EGLBoolean success; + EGLint numConfigs; + EGLint majorVersion; + EGLint minorVersion; + + int importGLResult; + importGLResult = importGLInit(); + if (!importGLResult) + return 0; + + sDisplay = XOpenDisplay(NULL); + + sEglDisplay = eglGetDisplay(sDisplay); + success = eglInitialize(sEglDisplay, &majorVersion, &minorVersion); + if (success != EGL_FALSE) + success = eglGetConfigs(sEglDisplay, NULL, 0, &numConfigs); + if (success != EGL_FALSE) + success = eglChooseConfig(sEglDisplay, configAttribs, + &sEglConfig, 1, &numConfigs); + if (success != EGL_FALSE) + { + sEglContext = eglCreateContext(sEglDisplay, sEglConfig, NULL, NULL); + if (sEglContext == EGL_NO_CONTEXT) + success = EGL_FALSE; + } + if (success != EGL_FALSE) + { + XSetWindowAttributes swa; + XVisualInfo *vi, tmp; + XSizeHints sh; + int n; + EGLint vid; + + eglGetConfigAttrib(sEglDisplay, sEglConfig, + EGL_NATIVE_VISUAL_ID, &vid); + tmp.visualid = vid; + vi = XGetVisualInfo(sDisplay, VisualIDMask, &tmp, &n); + swa.colormap = XCreateColormap(sDisplay, + RootWindow(sDisplay, vi->screen), + vi->visual, AllocNone); + sh.flags = PMinSize | PMaxSize; + sh.min_width = sh.max_width = sWindowWidth; + sh.min_height = sh.max_height = sWindowHeight; + swa.border_pixel = 0; + swa.event_mask = ExposureMask | StructureNotifyMask | + KeyPressMask | ButtonPressMask | ButtonReleaseMask; + sWindow = XCreateWindow(sDisplay, RootWindow(sDisplay, vi->screen), + 0, 0, sWindowWidth, sWindowHeight, + 0, vi->depth, InputOutput, vi->visual, + CWBorderPixel | CWColormap | CWEventMask, + &swa); + XMapWindow(sDisplay, sWindow); + XSetStandardProperties(sDisplay, sWindow, sAppName, sAppName, + None, (void *)0, 0, &sh); + } + if (success != EGL_FALSE) + { + sEglSurface = eglCreateWindowSurface(sEglDisplay, sEglConfig, + (NativeWindowType)sWindow, NULL); + if (sEglSurface == EGL_NO_SURFACE) + success = EGL_FALSE; + } + if (success != EGL_FALSE) + success = eglMakeCurrent(sEglDisplay, sEglSurface, + sEglSurface, sEglContext); + + if (success == EGL_FALSE) + checkEGLErrors(); + + return success != EGL_FALSE; +} + + +static void deinitGraphics() +{ + eglMakeCurrent(sEglDisplay, NULL, NULL, NULL); + eglDestroyContext(sEglDisplay, sEglContext); + eglDestroySurface(sEglDisplay, sEglSurface); + eglTerminate(sEglDisplay); + importGLDeinit(); +} + + +int main(int argc, char *argv[]) +{ + // not referenced: + argc = argc; + argv = argv; + + if (!initGraphics()) + { + fprintf(stderr, "Graphics initialization failed.\n"); + return EXIT_FAILURE; + } + + appInit(); + + while (gAppAlive) + { + struct timeval timeNow; + + while (XPending(sDisplay)) + { + XEvent ev; + XNextEvent(sDisplay, &ev); + switch (ev.type) + { + case KeyPress: + { + unsigned int keycode, keysym; + keycode = ((XKeyEvent *)&ev)->keycode; + keysym = XKeycodeToKeysym(sDisplay, keycode, 0); + if (keysym == XK_Return || keysym == XK_Escape) + gAppAlive = 0; + } + break; + } + } + + if (gAppAlive) + { + gettimeofday(&timeNow, NULL); + appRender(timeNow.tv_sec * 1000 + timeNow.tv_usec / 1000, + sWindowWidth, sWindowHeight); + checkGLErrors(); + eglSwapBuffers(sEglDisplay, sEglSurface); + checkEGLErrors(); + } + } + + appDeinit(); + deinitGraphics(); + + return EXIT_SUCCESS; +} diff --git a/tests/ndkSanAngeles/misc/app-win32.c b/tests/ndkSanAngeles/misc/app-win32.c new file mode 100644 index 0000000..b47577e --- /dev/null +++ b/tests/ndkSanAngeles/misc/app-win32.c @@ -0,0 +1,294 @@ +/* San Angeles Observation OpenGL ES version example + * Copyright 2004-2005 Jetro Lauha + * All rights reserved. + * Web: http://iki.fi/jetro/ + * + * This source is free software; you can redistribute it and/or + * modify it under the terms of EITHER: + * (1) The GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at + * your option) any later version. The text of the GNU Lesser + * General Public License is included with this source in the + * file LICENSE-LGPL.txt. + * (2) The BSD-style license that is included with this source in + * the file LICENSE-BSD.txt. + * + * This source is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files + * LICENSE-LGPL.txt and LICENSE-BSD.txt for more details. + * + * $Id: app-win32.c,v 1.6 2005/02/24 20:29:00 tonic Exp $ + * $Revision: 1.6 $ + */ + +#define WIN32_LEAN_AND_MEAN +#include <windows.h> +#include <tchar.h> +#ifdef UNDER_CE +#include <aygshell.h> +#endif + +#include <stdio.h> + +#include "importgl.h" + +#include "app.h" + + +int gAppAlive = 1; + +static HINSTANCE sInstance; + +static const _TCHAR sAppName[] = + _T("San Angeles Observation OpenGL ES version example (Win32)"); +static HWND sWnd; +static int sWindowWidth = WINDOW_DEFAULT_WIDTH; +static int sWindowHeight = WINDOW_DEFAULT_HEIGHT; +static EGLDisplay sEglDisplay = EGL_NO_DISPLAY; +static EGLConfig sEglConfig; +static EGLContext sEglContext = EGL_NO_CONTEXT; +static EGLSurface sEglSurface = EGL_NO_SURFACE; + + +static void checkGLErrors() +{ + GLenum error = glGetError(); + if (error != GL_NO_ERROR) + { + _TCHAR errorString[32]; + _stprintf(errorString, _T("0x%04x"), error); + MessageBox(NULL, errorString, _T("GL Error"), MB_OK); + } +} + + +static void checkEGLErrors() +{ + EGLint error = eglGetError(); + if (error != EGL_SUCCESS) + { + _TCHAR errorString[32]; + _stprintf(errorString, _T("0x%04x"), error); + MessageBox(NULL, errorString, _T("EGL Initialization Error"), MB_OK); + } +} + + +static BOOL initEGL(HWND wnd) +{ + static const EGLint configAttribs[] = + { +#if (WINDOW_BPP == 16) + EGL_RED_SIZE, 5, + EGL_GREEN_SIZE, 5, + EGL_BLUE_SIZE, 5, +#elif (WINDOW_BPP == 32) + EGL_RED_SIZE, 8, + EGL_GREEN_SIZE, 8, + EGL_BLUE_SIZE, 8, +#else +#error WINDOW_BPP must be 16 or 32 +#endif + EGL_DEPTH_SIZE, 16, + EGL_ALPHA_SIZE, EGL_DONT_CARE, + EGL_STENCIL_SIZE, EGL_DONT_CARE, + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_NONE + }; + EGLBoolean success; + EGLint numConfigs; + EGLint majorVersion; + EGLint minorVersion; +#ifdef PVRSDK + HDC dc; +#endif // PVRSDK + +#ifndef DISABLE_IMPORTGL + int importGLResult; + importGLResult = importGLInit(); + if (!importGLResult) + return FALSE; +#endif // !DISABLE_IMPORTGL + +#ifdef PVRSDK + dc = GetDC(sWnd); + sEglDisplay = eglGetDisplay(dc); +#else + sEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); +#endif // !PVRSDK + success = eglInitialize(sEglDisplay, &majorVersion, &minorVersion); + if (success != EGL_FALSE) + success = eglGetConfigs(sEglDisplay, NULL, 0, &numConfigs); + if (success != EGL_FALSE) + success = eglChooseConfig(sEglDisplay, configAttribs, + &sEglConfig, 1, &numConfigs); + if (success != EGL_FALSE) + { + sEglSurface = eglCreateWindowSurface(sEglDisplay, sEglConfig, + wnd, NULL); + if (sEglSurface == EGL_NO_SURFACE) + success = EGL_FALSE; + } + if (success != EGL_FALSE) + { + sEglContext = eglCreateContext(sEglDisplay, sEglConfig, NULL, NULL); + if (sEglContext == EGL_NO_CONTEXT) + success = EGL_FALSE; + } + if (success != EGL_FALSE) + success = eglMakeCurrent(sEglDisplay, sEglSurface, + sEglSurface, sEglContext); + + if (success == EGL_FALSE) + checkEGLErrors(); + + return success; +} + + +static void deinitEGL() +{ + eglMakeCurrent(sEglDisplay, NULL, NULL, NULL); + eglDestroyContext(sEglDisplay, sEglContext); + eglDestroySurface(sEglDisplay, sEglSurface); + eglTerminate(sEglDisplay); +#ifndef DISABLE_IMPORTGL + importGLDeinit(); +#endif // !DISABLE_IMPORTGL +} + + +static LRESULT CALLBACK wndProc(HWND wnd, UINT message, + WPARAM wParam, LPARAM lParam) +{ + RECT rc; + int useDefWindowProc = 0; + + switch (message) + { + case WM_CLOSE: + DestroyWindow(wnd); + gAppAlive = 0; + break; + + case WM_DESTROY: + PostQuitMessage(0); + gAppAlive = 0; + break; + + case WM_KEYDOWN: + if (wParam == VK_ESCAPE || wParam == VK_RETURN) + gAppAlive = 0; + useDefWindowProc = 1; + break; + + case WM_KEYUP: + useDefWindowProc = 1; + break; + + case WM_SIZE: + GetClientRect(sWnd, &rc); + sWindowWidth = rc.right; + sWindowHeight = rc.bottom; + break; + + default: + useDefWindowProc = 1; + } + + if (useDefWindowProc) + return DefWindowProc(wnd, message, wParam, lParam); + return 0; +} + + +int WINAPI WinMain(HINSTANCE instance, HINSTANCE prevInstance, + LPTSTR cmdLine, int cmdShow) +{ + MSG msg; + WNDCLASS wc; + DWORD windowStyle; + int windowX, windowY; + + // not referenced: + prevInstance = prevInstance; + cmdLine = cmdLine; + + + sInstance = instance; + + // register class + wc.style = CS_HREDRAW | CS_VREDRAW; + wc.lpfnWndProc = (WNDPROC)wndProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = sInstance; + wc.hIcon = NULL; + wc.hCursor = 0; + wc.hbrBackground = GetStockObject(BLACK_BRUSH); + wc.lpszMenuName = NULL; + wc.lpszClassName = sAppName; + if (!RegisterClass(&wc)) + return FALSE; + + // init instance + windowStyle = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE; +#ifdef UNDER_CE + sWindowWidth = GetSystemMetrics(SM_CXSCREEN); + sWindowHeight = GetSystemMetrics(SM_CYSCREEN); + windowX = windowY = 0; +#else + windowStyle |= WS_OVERLAPPEDWINDOW; + windowX = CW_USEDEFAULT; + windowY = 0; +#endif + sWnd = CreateWindow(sAppName, sAppName, windowStyle, + windowX, windowY, + sWindowWidth, sWindowHeight, + NULL, NULL, instance, NULL); + if (!sWnd) + return FALSE; + + ShowWindow(sWnd, cmdShow); + +#ifdef UNDER_CE + SHFullScreen(sWnd, + SHFS_HIDETASKBAR | SHFS_HIDESIPBUTTON | SHFS_HIDESTARTICON); + MoveWindow(sWnd, 0, 0, sWindowWidth, sWindowHeight, TRUE); +#endif + + UpdateWindow(sWnd); + + if (!initEGL(sWnd)) + return FALSE; + + appInit(sWindowWidth, sWindowHeight); + + while (gAppAlive) + { + while (PeekMessage(&msg, sWnd, 0, 0, PM_NOREMOVE)) + { + if (GetMessage(&msg, sWnd, 0, 0)) + { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + else + gAppAlive = 0; + } + + if (gAppAlive) + { + appRender(GetTickCount(), sWindowWidth, sWindowHeight); + checkGLErrors(); + eglSwapBuffers(sEglDisplay, sEglSurface); + checkEGLErrors(); + } + } + + appDeinit(); + deinitEGL(); + + return 0; +} diff --git a/tests/ndkSanAngeles/src/main/AndroidManifest.xml b/tests/ndkSanAngeles/src/main/AndroidManifest.xml new file mode 100644 index 0000000..5ae6a8e --- /dev/null +++ b/tests/ndkSanAngeles/src/main/AndroidManifest.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="utf-8"?> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.example.SanAngeles" + android:versionCode="1" + android:versionName="1.0"> + <application android:label="@string/app_name"> + <activity android:name=".DemoActivity" + android:label="@string/app_name"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity> + </application> + <uses-sdk android:minSdkVersion="4" /> +</manifest> diff --git a/tests/ndkSanAngeles/src/main/java/com/example/SanAngeles/DemoActivity.java b/tests/ndkSanAngeles/src/main/java/com/example/SanAngeles/DemoActivity.java new file mode 100644 index 0000000..076b8a7 --- /dev/null +++ b/tests/ndkSanAngeles/src/main/java/com/example/SanAngeles/DemoActivity.java @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2009 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. + * + * This is a small port of the "San Angeles Observation" demo + * program for OpenGL ES 1.x. For more details, see: + * + * http://jet.ro/visuals/san-angeles-observation/ + * + * This program demonstrates how to use a GLSurfaceView from Java + * along with native OpenGL calls to perform frame rendering. + * + * Touching the screen will start/stop the animation. + * + * Note that the demo runs much faster on the emulator than on + * real devices, this is mainly due to the following facts: + * + * - the demo sends bazillions of polygons to OpenGL without + * even trying to do culling. Most of them are clearly out + * of view. + * + * - on a real device, the GPU bus is the real bottleneck + * that prevent the demo from getting acceptable performance. + * + * - the software OpenGL engine used in the emulator uses + * the system bus instead, and its code rocks :-) + * + * Fixing the program to send less polygons to the GPU is left + * as an exercise to the reader. As always, patches welcomed :-) + */ +package com.example.SanAngeles; + +import javax.microedition.khronos.egl.EGLConfig; +import javax.microedition.khronos.opengles.GL10; + +import android.app.Activity; +import android.content.Context; +import android.opengl.GLSurfaceView; +import android.os.Bundle; +import android.view.MotionEvent; + +public class DemoActivity extends Activity { + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + mGLView = new DemoGLSurfaceView(this); + setContentView(mGLView); + } + + @Override + protected void onPause() { + super.onPause(); + mGLView.onPause(); + } + + @Override + protected void onResume() { + super.onResume(); + mGLView.onResume(); + } + + private GLSurfaceView mGLView; + + static { + System.loadLibrary("sanangeles"); + } +} + +class DemoGLSurfaceView extends GLSurfaceView { + public DemoGLSurfaceView(Context context) { + super(context); + mRenderer = new DemoRenderer(); + setRenderer(mRenderer); + } + + public boolean onTouchEvent(final MotionEvent event) { + if (event.getAction() == MotionEvent.ACTION_DOWN) { + nativeTogglePauseResume(); + } + return true; + } + + @Override + public void onPause() { + super.onPause(); + nativePause(); + } + + @Override + public void onResume() { + super.onResume(); + nativeResume(); + } + + + DemoRenderer mRenderer; + + private static native void nativePause(); + private static native void nativeResume(); + private static native void nativeTogglePauseResume(); +} + +class DemoRenderer implements GLSurfaceView.Renderer { + public void onSurfaceCreated(GL10 gl, EGLConfig config) { + nativeInit(); + } + + public void onSurfaceChanged(GL10 gl, int w, int h) { + //gl.glViewport(0, 0, w, h); + nativeResize(w, h); + } + + public void onDrawFrame(GL10 gl) { + nativeRender(); + } + + private static native void nativeInit(); + private static native void nativeResize(int w, int h); + private static native void nativeRender(); + private static native void nativeDone(); +} diff --git a/tests/ndkSanAngeles/src/main/jni/app-android.c b/tests/ndkSanAngeles/src/main/jni/app-android.c new file mode 100644 index 0000000..399d896 --- /dev/null +++ b/tests/ndkSanAngeles/src/main/jni/app-android.c @@ -0,0 +1,137 @@ +/* San Angeles Observation OpenGL ES version example + * Copyright 2009 The Android Open Source Project + * All rights reserved. + * + * This source is free software; you can redistribute it and/or + * modify it under the terms of EITHER: + * (1) The GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at + * your option) any later version. The text of the GNU Lesser + * General Public License is included with this source in the + * file LICENSE-LGPL.txt. + * (2) The BSD-style license that is included with this source in + * the file LICENSE-BSD.txt. + * + * This source is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files + * LICENSE-LGPL.txt and LICENSE-BSD.txt for more details. + */ +#include <jni.h> +#include <sys/time.h> +#include <time.h> +#include <android/log.h> +#include <stdint.h> +#include "importgl.h" +#include "app.h" + +int gAppAlive = 1; + +static int sWindowWidth = 320; +static int sWindowHeight = 480; +static int sDemoStopped = 0; +static long sTimeOffset = 0; +static int sTimeOffsetInit = 0; +static long sTimeStopped = 0; + +static long +_getTime(void) +{ + struct timeval now; + + gettimeofday(&now, NULL); + return (long)(now.tv_sec*1000 + now.tv_usec/1000); +} + +/* Call to initialize the graphics state */ +void +Java_com_example_SanAngeles_DemoRenderer_nativeInit( JNIEnv* env ) +{ + importGLInit(); + appInit(); + gAppAlive = 1; +} + +void +Java_com_example_SanAngeles_DemoRenderer_nativeResize( JNIEnv* env, jobject thiz, jint w, jint h ) +{ + sWindowWidth = w; + sWindowHeight = h; + __android_log_print(ANDROID_LOG_INFO, "SanAngeles", "resize w=%d h=%d", w, h); +} + +/* Call to finalize the graphics state */ +void +Java_com_example_SanAngeles_DemoRenderer_nativeDone( JNIEnv* env ) +{ + appDeinit(); + importGLDeinit(); +} + +/* This is called to indicate to the render loop that it should + * stop as soon as possible. + */ + +void _pause() +{ + /* we paused the animation, so store the current + * time in sTimeStopped for future nativeRender calls */ + sDemoStopped = 1; + sTimeStopped = _getTime(); +} + +void _resume() +{ + /* we resumed the animation, so adjust the time offset + * to take care of the pause interval. */ + sDemoStopped = 0; + sTimeOffset -= _getTime() - sTimeStopped; +} + + +void +Java_com_example_SanAngeles_DemoGLSurfaceView_nativeTogglePauseResume( JNIEnv* env ) +{ + sDemoStopped = !sDemoStopped; + if (sDemoStopped) + _pause(); + else + _resume(); +} + +void +Java_com_example_SanAngeles_DemoGLSurfaceView_nativePause( JNIEnv* env ) +{ + _pause(); +} + +void +Java_com_example_SanAngeles_DemoGLSurfaceView_nativeResume( JNIEnv* env ) +{ + _resume(); +} + +/* Call to render the next GL frame */ +void +Java_com_example_SanAngeles_DemoRenderer_nativeRender( JNIEnv* env ) +{ + long curTime; + + /* NOTE: if sDemoStopped is TRUE, then we re-render the same frame + * on each iteration. + */ + if (sDemoStopped) { + curTime = sTimeStopped + sTimeOffset; + } else { + curTime = _getTime() + sTimeOffset; + if (sTimeOffsetInit == 0) { + sTimeOffsetInit = 1; + sTimeOffset = -curTime; + curTime = 0; + } + } + + //__android_log_print(ANDROID_LOG_INFO, "SanAngeles", "curTime=%ld", curTime); + + appRender(curTime, sWindowWidth, sWindowHeight); +} diff --git a/tests/ndkSanAngeles/src/main/jni/app.h b/tests/ndkSanAngeles/src/main/jni/app.h new file mode 100644 index 0000000..70ebd35 --- /dev/null +++ b/tests/ndkSanAngeles/src/main/jni/app.h @@ -0,0 +1,56 @@ +/* San Angeles Observation OpenGL ES version example + * Copyright 2004-2005 Jetro Lauha + * All rights reserved. + * Web: http://iki.fi/jetro/ + * + * This source is free software; you can redistribute it and/or + * modify it under the terms of EITHER: + * (1) The GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at + * your option) any later version. The text of the GNU Lesser + * General Public License is included with this source in the + * file LICENSE-LGPL.txt. + * (2) The BSD-style license that is included with this source in + * the file LICENSE-BSD.txt. + * + * This source is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files + * LICENSE-LGPL.txt and LICENSE-BSD.txt for more details. + * + * $Id: app.h,v 1.14 2005/02/06 21:13:54 tonic Exp $ + * $Revision: 1.14 $ + */ + +#ifndef APP_H_INCLUDED +#define APP_H_INCLUDED + + +#ifdef __cplusplus +extern "C" { +#endif + + +#define WINDOW_DEFAULT_WIDTH 640 +#define WINDOW_DEFAULT_HEIGHT 480 + +#define WINDOW_BPP 16 + + +// The simple framework expects the application code to define these functions. +extern void appInit(); +extern void appDeinit(); +extern void appRender(long tick, int width, int height); + +/* Value is non-zero when application is alive, and 0 when it is closing. + * Defined by the application framework. + */ +extern int gAppAlive; + + +#ifdef __cplusplus +} +#endif + + +#endif // !APP_H_INCLUDED diff --git a/tests/ndkSanAngeles/src/main/jni/cams.h b/tests/ndkSanAngeles/src/main/jni/cams.h new file mode 100644 index 0000000..2b1acb3 --- /dev/null +++ b/tests/ndkSanAngeles/src/main/jni/cams.h @@ -0,0 +1,65 @@ +/* San Angeles Observation OpenGL ES version example + * Copyright 2004-2005 Jetro Lauha + * All rights reserved. + * Web: http://iki.fi/jetro/ + * + * This source is free software; you can redistribute it and/or + * modify it under the terms of EITHER: + * (1) The GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at + * your option) any later version. The text of the GNU Lesser + * General Public License is included with this source in the + * file LICENSE-LGPL.txt. + * (2) The BSD-style license that is included with this source in + * the file LICENSE-BSD.txt. + * + * This source is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files + * LICENSE-LGPL.txt and LICENSE-BSD.txt for more details. + * + * $Id: cams.h,v 1.7 2005/01/31 22:15:15 tonic Exp $ + * $Revision: 1.7 $ + */ + +#ifndef CAMS_H_INCLUDED +#define CAMS_H_INCLUDED + + +/* Length in milliseconds of one camera track base unit. + * The value originates from the music synchronization. + */ +#define CAMTRACK_LEN 5442 + + +// Camera track definition for one camera trucking shot. +typedef struct +{ + /* Five parameters of src[5] and dest[5]: + * eyeX, eyeY, eyeZ, viewAngle, viewHeightOffs + */ + short src[5], dest[5]; + unsigned char dist; // if >0, cam rotates around eye xy on dist * 0.1 + unsigned char len; // length multiplier +} CAMTRACK; + +static CAMTRACK sCamTracks[] = +{ + { { 4500, 2700, 100, 70, -30 }, { 50, 50, -90, -100, 0 }, 20, 1 }, + { { -1448, 4294, 25, 363, 0 }, { -136, 202, 125, -98, 100 }, 0, 1 }, + { { 1437, 4930, 200, -275, -20 }, { 1684, 0, 0, 9, 0 }, 0, 1 }, + { { 1800, 3609, 200, 0, 675 }, { 0, 0, 0, 300, 0 }, 0, 1 }, + { { 923, 996, 50, 2336, -80 }, { 0, -20, -50, 0, 170 }, 0, 1 }, + { { -1663, -43, 600, 2170, 0 }, { 20, 0, -600, 0, 100 }, 0, 1 }, + { { 1049, -1420, 175, 2111, -17 }, { 0, 0, 0, -334, 0 }, 0, 2 }, + { { 0, 0, 50, 300, 25 }, { 0, 0, 0, 300, 0 }, 70, 2 }, + { { -473, -953, 3500, -353, -350 }, { 0, 0, -2800, 0, 0 }, 0, 2 }, + { { 191, 1938, 35, 1139, -17 }, { 1205, -2909, 0, 0, 0 }, 0, 2 }, + { { -1449, -2700, 150, 0, 0 }, { 0, 2000, 0, 0, 0 }, 0, 2 }, + { { 5273, 4992, 650, 373, -50 }, { -4598, -3072, 0, 0, 0 }, 0, 2 }, + { { 3223, -3282, 1075, -393, -25 }, { 1649, -1649, 0, 0, 0 }, 0, 2 } +}; +#define CAMTRACK_COUNT (sizeof(camTracks) / sizeof(camTracks[0])) + + +#endif // !CAMS_H_INCLUDED diff --git a/tests/ndkSanAngeles/src/main/jni/demo.c b/tests/ndkSanAngeles/src/main/jni/demo.c new file mode 100644 index 0000000..9cb73d1 --- /dev/null +++ b/tests/ndkSanAngeles/src/main/jni/demo.c @@ -0,0 +1,792 @@ +/* San Angeles Observation OpenGL ES version example + * Copyright 2004-2005 Jetro Lauha + * All rights reserved. + * Web: http://iki.fi/jetro/ + * + * This source is free software; you can redistribute it and/or + * modify it under the terms of EITHER: + * (1) The GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at + * your option) any later version. The text of the GNU Lesser + * General Public License is included with this source in the + * file LICENSE-LGPL.txt. + * (2) The BSD-style license that is included with this source in + * the file LICENSE-BSD.txt. + * + * This source is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files + * LICENSE-LGPL.txt and LICENSE-BSD.txt for more details. + * + * $Id: demo.c,v 1.10 2005/02/08 20:54:39 tonic Exp $ + * $Revision: 1.10 $ + */ + +#include <stdlib.h> +#include <math.h> +#include <float.h> +#include <assert.h> + +#include "importgl.h" + +#include "app.h" +#include "shapes.h" +#include "cams.h" + + +// Total run length is 20 * camera track base unit length (see cams.h). +#define RUN_LENGTH (20 * CAMTRACK_LEN) +#undef PI +#define PI 3.1415926535897932f +#define RANDOM_UINT_MAX 65535 + + +static unsigned long sRandomSeed = 0; + +static void seedRandom(unsigned long seed) +{ + sRandomSeed = seed; +} + +static unsigned long randomUInt() +{ + sRandomSeed = sRandomSeed * 0x343fd + 0x269ec3; + return sRandomSeed >> 16; +} + + +// Capped conversion from float to fixed. +static long floatToFixed(float value) +{ + if (value < -32768) value = -32768; + if (value > 32767) value = 32767; + return (long)(value * 65536); +} + +#define FIXED(value) floatToFixed(value) + + +// Definition of one GL object in this demo. +typedef struct { + /* Vertex array and color array are enabled for all objects, so their + * pointers must always be valid and non-NULL. Normal array is not + * used by the ground plane, so when its pointer is NULL then normal + * array usage is disabled. + * + * Vertex array is supposed to use GL_FIXED datatype and stride 0 + * (i.e. tightly packed array). Color array is supposed to have 4 + * components per color with GL_UNSIGNED_BYTE datatype and stride 0. + * Normal array is supposed to use GL_FIXED datatype and stride 0. + */ + GLfixed *vertexArray; + GLubyte *colorArray; + GLfixed *normalArray; + GLint vertexComponents; + GLsizei count; +} GLOBJECT; + + +static long sStartTick = 0; +static long sTick = 0; + +static int sCurrentCamTrack = 0; +static long sCurrentCamTrackStartTick = 0; +static long sNextCamTrackStartTick = 0x7fffffff; + +static GLOBJECT *sSuperShapeObjects[SUPERSHAPE_COUNT] = { NULL }; +static GLOBJECT *sGroundPlane = NULL; + + +typedef struct { + float x, y, z; +} VECTOR3; + + +static void freeGLObject(GLOBJECT *object) +{ + if (object == NULL) + return; + free(object->normalArray); + free(object->colorArray); + free(object->vertexArray); + free(object); +} + + +static GLOBJECT * newGLObject(long vertices, int vertexComponents, + int useNormalArray) +{ + GLOBJECT *result; + result = (GLOBJECT *)malloc(sizeof(GLOBJECT)); + if (result == NULL) + return NULL; + result->count = vertices; + result->vertexComponents = vertexComponents; + result->vertexArray = (GLfixed *)malloc(vertices * vertexComponents * + sizeof(GLfixed)); + result->colorArray = (GLubyte *)malloc(vertices * 4 * sizeof(GLubyte)); + if (useNormalArray) + { + result->normalArray = (GLfixed *)malloc(vertices * 3 * + sizeof(GLfixed)); + } + else + result->normalArray = NULL; + if (result->vertexArray == NULL || + result->colorArray == NULL || + (useNormalArray && result->normalArray == NULL)) + { + freeGLObject(result); + return NULL; + } + return result; +} + + +static void drawGLObject(GLOBJECT *object) +{ + assert(object != NULL); + + glVertexPointer(object->vertexComponents, GL_FIXED, + 0, object->vertexArray); + glColorPointer(4, GL_UNSIGNED_BYTE, 0, object->colorArray); + + // Already done in initialization: + //glEnableClientState(GL_VERTEX_ARRAY); + //glEnableClientState(GL_COLOR_ARRAY); + + if (object->normalArray) + { + glNormalPointer(GL_FIXED, 0, object->normalArray); + glEnableClientState(GL_NORMAL_ARRAY); + } + else + glDisableClientState(GL_NORMAL_ARRAY); + glDrawArrays(GL_TRIANGLES, 0, object->count); +} + + +static void vector3Sub(VECTOR3 *dest, VECTOR3 *v1, VECTOR3 *v2) +{ + dest->x = v1->x - v2->x; + dest->y = v1->y - v2->y; + dest->z = v1->z - v2->z; +} + + +static void superShapeMap(VECTOR3 *point, float r1, float r2, float t, float p) +{ + // sphere-mapping of supershape parameters + point->x = (float)(cos(t) * cos(p) / r1 / r2); + point->y = (float)(sin(t) * cos(p) / r1 / r2); + point->z = (float)(sin(p) / r2); +} + + +static float ssFunc(const float t, const float *p) +{ + return (float)(pow(pow(fabs(cos(p[0] * t / 4)) / p[1], p[4]) + + pow(fabs(sin(p[0] * t / 4)) / p[2], p[5]), 1 / p[3])); +} + + +// Creates and returns a supershape object. +// Based on Paul Bourke's POV-Ray implementation. +// http://astronomy.swin.edu.au/~pbourke/povray/supershape/ +static GLOBJECT * createSuperShape(const float *params) +{ + const int resol1 = (int)params[SUPERSHAPE_PARAMS - 3]; + const int resol2 = (int)params[SUPERSHAPE_PARAMS - 2]; + // latitude 0 to pi/2 for no mirrored bottom + // (latitudeBegin==0 for -pi/2 to pi/2 originally) + const int latitudeBegin = resol2 / 4; + const int latitudeEnd = resol2 / 2; // non-inclusive + const int longitudeCount = resol1; + const int latitudeCount = latitudeEnd - latitudeBegin; + const long triangleCount = longitudeCount * latitudeCount * 2; + const long vertices = triangleCount * 3; + GLOBJECT *result; + float baseColor[3]; + int a, longitude, latitude; + long currentVertex, currentQuad; + + result = newGLObject(vertices, 3, 1); + if (result == NULL) + return NULL; + + for (a = 0; a < 3; ++a) + baseColor[a] = ((randomUInt() % 155) + 100) / 255.f; + + currentQuad = 0; + currentVertex = 0; + + // longitude -pi to pi + for (longitude = 0; longitude < longitudeCount; ++longitude) + { + + // latitude 0 to pi/2 + for (latitude = latitudeBegin; latitude < latitudeEnd; ++latitude) + { + float t1 = -PI + longitude * 2 * PI / resol1; + float t2 = -PI + (longitude + 1) * 2 * PI / resol1; + float p1 = -PI / 2 + latitude * 2 * PI / resol2; + float p2 = -PI / 2 + (latitude + 1) * 2 * PI / resol2; + float r0, r1, r2, r3; + + r0 = ssFunc(t1, params); + r1 = ssFunc(p1, ¶ms[6]); + r2 = ssFunc(t2, params); + r3 = ssFunc(p2, ¶ms[6]); + + if (r0 != 0 && r1 != 0 && r2 != 0 && r3 != 0) + { + VECTOR3 pa, pb, pc, pd; + VECTOR3 v1, v2, n; + float ca; + int i; + //float lenSq, invLenSq; + + superShapeMap(&pa, r0, r1, t1, p1); + superShapeMap(&pb, r2, r1, t2, p1); + superShapeMap(&pc, r2, r3, t2, p2); + superShapeMap(&pd, r0, r3, t1, p2); + + // kludge to set lower edge of the object to fixed level + if (latitude == latitudeBegin + 1) + pa.z = pb.z = 0; + + vector3Sub(&v1, &pb, &pa); + vector3Sub(&v2, &pd, &pa); + + // Calculate normal with cross product. + /* i j k i j + * v1.x v1.y v1.z | v1.x v1.y + * v2.x v2.y v2.z | v2.x v2.y + */ + + n.x = v1.y * v2.z - v1.z * v2.y; + n.y = v1.z * v2.x - v1.x * v2.z; + n.z = v1.x * v2.y - v1.y * v2.x; + + /* Pre-normalization of the normals is disabled here because + * they will be normalized anyway later due to automatic + * normalization (GL_NORMALIZE). It is enabled because the + * objects are scaled with glScale. + */ + /* + lenSq = n.x * n.x + n.y * n.y + n.z * n.z; + invLenSq = (float)(1 / sqrt(lenSq)); + n.x *= invLenSq; + n.y *= invLenSq; + n.z *= invLenSq; + */ + + ca = pa.z + 0.5f; + + for (i = currentVertex * 3; + i < (currentVertex + 6) * 3; + i += 3) + { + result->normalArray[i] = FIXED(n.x); + result->normalArray[i + 1] = FIXED(n.y); + result->normalArray[i + 2] = FIXED(n.z); + } + for (i = currentVertex * 4; + i < (currentVertex + 6) * 4; + i += 4) + { + int a, color[3]; + for (a = 0; a < 3; ++a) + { + color[a] = (int)(ca * baseColor[a] * 255); + if (color[a] > 255) color[a] = 255; + } + result->colorArray[i] = (GLubyte)color[0]; + result->colorArray[i + 1] = (GLubyte)color[1]; + result->colorArray[i + 2] = (GLubyte)color[2]; + result->colorArray[i + 3] = 0; + } + result->vertexArray[currentVertex * 3] = FIXED(pa.x); + result->vertexArray[currentVertex * 3 + 1] = FIXED(pa.y); + result->vertexArray[currentVertex * 3 + 2] = FIXED(pa.z); + ++currentVertex; + result->vertexArray[currentVertex * 3] = FIXED(pb.x); + result->vertexArray[currentVertex * 3 + 1] = FIXED(pb.y); + result->vertexArray[currentVertex * 3 + 2] = FIXED(pb.z); + ++currentVertex; + result->vertexArray[currentVertex * 3] = FIXED(pd.x); + result->vertexArray[currentVertex * 3 + 1] = FIXED(pd.y); + result->vertexArray[currentVertex * 3 + 2] = FIXED(pd.z); + ++currentVertex; + result->vertexArray[currentVertex * 3] = FIXED(pb.x); + result->vertexArray[currentVertex * 3 + 1] = FIXED(pb.y); + result->vertexArray[currentVertex * 3 + 2] = FIXED(pb.z); + ++currentVertex; + result->vertexArray[currentVertex * 3] = FIXED(pc.x); + result->vertexArray[currentVertex * 3 + 1] = FIXED(pc.y); + result->vertexArray[currentVertex * 3 + 2] = FIXED(pc.z); + ++currentVertex; + result->vertexArray[currentVertex * 3] = FIXED(pd.x); + result->vertexArray[currentVertex * 3 + 1] = FIXED(pd.y); + result->vertexArray[currentVertex * 3 + 2] = FIXED(pd.z); + ++currentVertex; + } // r0 && r1 && r2 && r3 + ++currentQuad; + } // latitude + } // longitude + + // Set number of vertices in object to the actual amount created. + result->count = currentVertex; + + return result; +} + + +static GLOBJECT * createGroundPlane() +{ + const int scale = 4; + const int yBegin = -15, yEnd = 15; // ends are non-inclusive + const int xBegin = -15, xEnd = 15; + const long triangleCount = (yEnd - yBegin) * (xEnd - xBegin) * 2; + const long vertices = triangleCount * 3; + GLOBJECT *result; + int x, y; + long currentVertex, currentQuad; + + result = newGLObject(vertices, 2, 0); + if (result == NULL) + return NULL; + + currentQuad = 0; + currentVertex = 0; + + for (y = yBegin; y < yEnd; ++y) + { + for (x = xBegin; x < xEnd; ++x) + { + GLubyte color; + int i, a; + color = (GLubyte)((randomUInt() & 0x5f) + 81); // 101 1111 + for (i = currentVertex * 4; i < (currentVertex + 6) * 4; i += 4) + { + result->colorArray[i] = color; + result->colorArray[i + 1] = color; + result->colorArray[i + 2] = color; + result->colorArray[i + 3] = 0; + } + + // Axis bits for quad triangles: + // x: 011100 (0x1c), y: 110001 (0x31) (clockwise) + // x: 001110 (0x0e), y: 100011 (0x23) (counter-clockwise) + for (a = 0; a < 6; ++a) + { + const int xm = x + ((0x1c >> a) & 1); + const int ym = y + ((0x31 >> a) & 1); + const float m = (float)(cos(xm * 2) * sin(ym * 4) * 0.75f); + result->vertexArray[currentVertex * 2] = + FIXED(xm * scale + m); + result->vertexArray[currentVertex * 2 + 1] = + FIXED(ym * scale + m); + ++currentVertex; + } + ++currentQuad; + } + } + return result; +} + + +static void drawGroundPlane() +{ + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glEnable(GL_BLEND); + glBlendFunc(GL_ZERO, GL_SRC_COLOR); + glDisable(GL_LIGHTING); + + drawGLObject(sGroundPlane); + + glEnable(GL_LIGHTING); + glDisable(GL_BLEND); + glEnable(GL_DEPTH_TEST); +} + + +static void drawFadeQuad() +{ + static const GLfixed quadVertices[] = { + -0x10000, -0x10000, + 0x10000, -0x10000, + -0x10000, 0x10000, + 0x10000, -0x10000, + 0x10000, 0x10000, + -0x10000, 0x10000 + }; + + const int beginFade = sTick - sCurrentCamTrackStartTick; + const int endFade = sNextCamTrackStartTick - sTick; + const int minFade = beginFade < endFade ? beginFade : endFade; + + if (minFade < 1024) + { + const GLfixed fadeColor = minFade << 6; + glColor4x(fadeColor, fadeColor, fadeColor, 0); + + glDisable(GL_DEPTH_TEST); + glEnable(GL_BLEND); + glBlendFunc(GL_ZERO, GL_SRC_COLOR); + glDisable(GL_LIGHTING); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + + glDisableClientState(GL_COLOR_ARRAY); + glDisableClientState(GL_NORMAL_ARRAY); + glVertexPointer(2, GL_FIXED, 0, quadVertices); + glDrawArrays(GL_TRIANGLES, 0, 6); + + glEnableClientState(GL_COLOR_ARRAY); + + glMatrixMode(GL_MODELVIEW); + + glEnable(GL_LIGHTING); + glDisable(GL_BLEND); + glEnable(GL_DEPTH_TEST); + } +} + + +// Called from the app framework. +void appInit() +{ + int a; + + glEnable(GL_NORMALIZE); + glEnable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glShadeModel(GL_FLAT); + + glEnable(GL_LIGHTING); + glEnable(GL_LIGHT0); + glEnable(GL_LIGHT1); + glEnable(GL_LIGHT2); + + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_COLOR_ARRAY); + + seedRandom(15); + + for (a = 0; a < SUPERSHAPE_COUNT; ++a) + { + sSuperShapeObjects[a] = createSuperShape(sSuperShapeParams[a]); + assert(sSuperShapeObjects[a] != NULL); + } + sGroundPlane = createGroundPlane(); + assert(sGroundPlane != NULL); +} + + +// Called from the app framework. +void appDeinit() +{ + int a; + for (a = 0; a < SUPERSHAPE_COUNT; ++a) + freeGLObject(sSuperShapeObjects[a]); + freeGLObject(sGroundPlane); +} + + +static void gluPerspective(GLfloat fovy, GLfloat aspect, + GLfloat zNear, GLfloat zFar) +{ + GLfloat xmin, xmax, ymin, ymax; + + ymax = zNear * (GLfloat)tan(fovy * PI / 360); + ymin = -ymax; + xmin = ymin * aspect; + xmax = ymax * aspect; + + glFrustumx((GLfixed)(xmin * 65536), (GLfixed)(xmax * 65536), + (GLfixed)(ymin * 65536), (GLfixed)(ymax * 65536), + (GLfixed)(zNear * 65536), (GLfixed)(zFar * 65536)); +} + + +static void prepareFrame(int width, int height) +{ + glViewport(0, 0, width, height); + + glClearColorx((GLfixed)(0.1f * 65536), + (GLfixed)(0.2f * 65536), + (GLfixed)(0.3f * 65536), 0x10000); + glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); + + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + gluPerspective(45, (float)width / height, 0.5f, 150); + + glMatrixMode(GL_MODELVIEW); + + glLoadIdentity(); +} + + +static void configureLightAndMaterial() +{ + static GLfixed light0Position[] = { -0x40000, 0x10000, 0x10000, 0 }; + static GLfixed light0Diffuse[] = { 0x10000, 0x6666, 0, 0x10000 }; + static GLfixed light1Position[] = { 0x10000, -0x20000, -0x10000, 0 }; + static GLfixed light1Diffuse[] = { 0x11eb, 0x23d7, 0x5999, 0x10000 }; + static GLfixed light2Position[] = { -0x10000, 0, -0x40000, 0 }; + static GLfixed light2Diffuse[] = { 0x11eb, 0x2b85, 0x23d7, 0x10000 }; + static GLfixed materialSpecular[] = { 0x10000, 0x10000, 0x10000, 0x10000 }; + + glLightxv(GL_LIGHT0, GL_POSITION, light0Position); + glLightxv(GL_LIGHT0, GL_DIFFUSE, light0Diffuse); + glLightxv(GL_LIGHT1, GL_POSITION, light1Position); + glLightxv(GL_LIGHT1, GL_DIFFUSE, light1Diffuse); + glLightxv(GL_LIGHT2, GL_POSITION, light2Position); + glLightxv(GL_LIGHT2, GL_DIFFUSE, light2Diffuse); + glMaterialxv(GL_FRONT_AND_BACK, GL_SPECULAR, materialSpecular); + + glMaterialx(GL_FRONT_AND_BACK, GL_SHININESS, 60 << 16); + glEnable(GL_COLOR_MATERIAL); +} + + +static void drawModels(float zScale) +{ + const int translationScale = 9; + int x, y; + + seedRandom(9); + + glScalex(1 << 16, 1 << 16, (GLfixed)(zScale * 65536)); + + for (y = -5; y <= 5; ++y) + { + for (x = -5; x <= 5; ++x) + { + float buildingScale; + GLfixed fixedScale; + + int curShape = randomUInt() % SUPERSHAPE_COUNT; + buildingScale = sSuperShapeParams[curShape][SUPERSHAPE_PARAMS - 1]; + fixedScale = (GLfixed)(buildingScale * 65536); + + glPushMatrix(); + glTranslatex((x * translationScale) * 65536, + (y * translationScale) * 65536, + 0); + glRotatex((GLfixed)((randomUInt() % 360) << 16), 0, 0, 1 << 16); + glScalex(fixedScale, fixedScale, fixedScale); + + drawGLObject(sSuperShapeObjects[curShape]); + glPopMatrix(); + } + } + + for (x = -2; x <= 2; ++x) + { + const int shipScale100 = translationScale * 500; + const int offs100 = x * shipScale100 + (sTick % shipScale100); + float offs = offs100 * 0.01f; + GLfixed fixedOffs = (GLfixed)(offs * 65536); + glPushMatrix(); + glTranslatex(fixedOffs, -4 * 65536, 2 << 16); + drawGLObject(sSuperShapeObjects[SUPERSHAPE_COUNT - 1]); + glPopMatrix(); + glPushMatrix(); + glTranslatex(-4 * 65536, fixedOffs, 4 << 16); + glRotatex(90 << 16, 0, 0, 1 << 16); + drawGLObject(sSuperShapeObjects[SUPERSHAPE_COUNT - 1]); + glPopMatrix(); + } +} + + +/* Following gluLookAt implementation is adapted from the + * Mesa 3D Graphics library. http://www.mesa3d.org + */ +static void gluLookAt(GLfloat eyex, GLfloat eyey, GLfloat eyez, + GLfloat centerx, GLfloat centery, GLfloat centerz, + GLfloat upx, GLfloat upy, GLfloat upz) +{ + GLfloat m[16]; + GLfloat x[3], y[3], z[3]; + GLfloat mag; + + /* Make rotation matrix */ + + /* Z vector */ + z[0] = eyex - centerx; + z[1] = eyey - centery; + z[2] = eyez - centerz; + mag = (float)sqrt(z[0] * z[0] + z[1] * z[1] + z[2] * z[2]); + if (mag) { /* mpichler, 19950515 */ + z[0] /= mag; + z[1] /= mag; + z[2] /= mag; + } + + /* Y vector */ + y[0] = upx; + y[1] = upy; + y[2] = upz; + + /* X vector = Y cross Z */ + x[0] = y[1] * z[2] - y[2] * z[1]; + x[1] = -y[0] * z[2] + y[2] * z[0]; + x[2] = y[0] * z[1] - y[1] * z[0]; + + /* Recompute Y = Z cross X */ + y[0] = z[1] * x[2] - z[2] * x[1]; + y[1] = -z[0] * x[2] + z[2] * x[0]; + y[2] = z[0] * x[1] - z[1] * x[0]; + + /* mpichler, 19950515 */ + /* cross product gives area of parallelogram, which is < 1.0 for + * non-perpendicular unit-length vectors; so normalize x, y here + */ + + mag = (float)sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]); + if (mag) { + x[0] /= mag; + x[1] /= mag; + x[2] /= mag; + } + + mag = (float)sqrt(y[0] * y[0] + y[1] * y[1] + y[2] * y[2]); + if (mag) { + y[0] /= mag; + y[1] /= mag; + y[2] /= mag; + } + +#define M(row,col) m[col*4+row] + M(0, 0) = x[0]; + M(0, 1) = x[1]; + M(0, 2) = x[2]; + M(0, 3) = 0.0; + M(1, 0) = y[0]; + M(1, 1) = y[1]; + M(1, 2) = y[2]; + M(1, 3) = 0.0; + M(2, 0) = z[0]; + M(2, 1) = z[1]; + M(2, 2) = z[2]; + M(2, 3) = 0.0; + M(3, 0) = 0.0; + M(3, 1) = 0.0; + M(3, 2) = 0.0; + M(3, 3) = 1.0; +#undef M + { + int a; + GLfixed fixedM[16]; + for (a = 0; a < 16; ++a) + fixedM[a] = (GLfixed)(m[a] * 65536); + glMultMatrixx(fixedM); + } + + /* Translate Eye to Origin */ + glTranslatex((GLfixed)(-eyex * 65536), + (GLfixed)(-eyey * 65536), + (GLfixed)(-eyez * 65536)); +} + + +static void camTrack() +{ + float lerp[5]; + float eX, eY, eZ, cX, cY, cZ; + float trackPos; + CAMTRACK *cam; + long currentCamTick; + int a; + + if (sNextCamTrackStartTick <= sTick) + { + ++sCurrentCamTrack; + sCurrentCamTrackStartTick = sNextCamTrackStartTick; + } + sNextCamTrackStartTick = sCurrentCamTrackStartTick + + sCamTracks[sCurrentCamTrack].len * CAMTRACK_LEN; + + cam = &sCamTracks[sCurrentCamTrack]; + currentCamTick = sTick - sCurrentCamTrackStartTick; + trackPos = (float)currentCamTick / (CAMTRACK_LEN * cam->len); + + for (a = 0; a < 5; ++a) + lerp[a] = (cam->src[a] + cam->dest[a] * trackPos) * 0.01f; + + if (cam->dist) + { + float dist = cam->dist * 0.1f; + cX = lerp[0]; + cY = lerp[1]; + cZ = lerp[2]; + eX = cX - (float)cos(lerp[3]) * dist; + eY = cY - (float)sin(lerp[3]) * dist; + eZ = cZ - lerp[4]; + } + else + { + eX = lerp[0]; + eY = lerp[1]; + eZ = lerp[2]; + cX = eX + (float)cos(lerp[3]); + cY = eY + (float)sin(lerp[3]); + cZ = eZ + lerp[4]; + } + gluLookAt(eX, eY, eZ, cX, cY, cZ, 0, 0, 1); +} + + +// Called from the app framework. +/* The tick is current time in milliseconds, width and height + * are the image dimensions to be rendered. + */ +void appRender(long tick, int width, int height) +{ + if (sStartTick == 0) + sStartTick = tick; + if (!gAppAlive) + return; + + // Actual tick value is "blurred" a little bit. + sTick = (sTick + tick - sStartTick) >> 1; + + // Terminate application after running through the demonstration once. + if (sTick >= RUN_LENGTH) + { + gAppAlive = 0; + return; + } + + // Prepare OpenGL ES for rendering of the frame. + prepareFrame(width, height); + + // Update the camera position and set the lookat. + camTrack(); + + // Configure environment. + configureLightAndMaterial(); + + // Draw the reflection by drawing models with negated Z-axis. + glPushMatrix(); + drawModels(-1); + glPopMatrix(); + + // Blend the ground plane to the window. + drawGroundPlane(); + + // Draw all the models normally. + drawModels(1); + + // Draw fade quad over whole window (when changing cameras). + drawFadeQuad(); +} diff --git a/tests/ndkSanAngeles/src/main/jni/importgl.c b/tests/ndkSanAngeles/src/main/jni/importgl.c new file mode 100644 index 0000000..f501636 --- /dev/null +++ b/tests/ndkSanAngeles/src/main/jni/importgl.c @@ -0,0 +1,168 @@ +/* San Angeles Observation OpenGL ES version example + * Copyright 2004-2005 Jetro Lauha + * All rights reserved. + * Web: http://iki.fi/jetro/ + * + * This source is free software; you can redistribute it and/or + * modify it under the terms of EITHER: + * (1) The GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at + * your option) any later version. The text of the GNU Lesser + * General Public License is included with this source in the + * file LICENSE-LGPL.txt. + * (2) The BSD-style license that is included with this source in + * the file LICENSE-BSD.txt. + * + * This source is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files + * LICENSE-LGPL.txt and LICENSE-BSD.txt for more details. + * + * $Id: importgl.c,v 1.4 2005/02/08 18:42:55 tonic Exp $ + * $Revision: 1.4 $ + */ + +#undef WIN32 +#undef LINUX +#ifdef _MSC_VER +// Desktop or mobile Win32 environment: +#define WIN32 +#else +// Linux environment: +#define LINUX +#endif + +#ifndef DISABLE_IMPORTGL + +#if defined(WIN32) +#define WIN32_LEAN_AND_MEAN +#include <windows.h> +#include <tchar.h> +static HMODULE sGLESDLL = NULL; +#endif // WIN32 + +#ifdef LINUX +#include <stdlib.h> +#include <dlfcn.h> +static void *sGLESSO = NULL; +#endif // LINUX + +#endif /* DISABLE_IMPORTGL */ + +#define IMPORTGL_NO_FNPTR_DEFS +#define IMPORTGL_API +#define IMPORTGL_FNPTRINIT = NULL +#include "importgl.h" + + +/* Imports function pointers to selected function calls in OpenGL ES Common + * or Common Lite profile DLL or shared object. The function pointers are + * stored as global symbols with equivalent function name but prefixed with + * "funcPtr_". Standard gl/egl calls are redirected to the function pointers + * with preprocessor macros (see importgl.h). + */ +int importGLInit() +{ + int result = 1; + +#ifndef DISABLE_IMPORTGL + +#undef IMPORT_FUNC + +#ifdef WIN32 + sGLESDLL = LoadLibrary(_T("libGLES_CM.dll")); + if (sGLESDLL == NULL) + sGLESDLL = LoadLibrary(_T("libGLES_CL.dll")); + if (sGLESDLL == NULL) + return 0; // Cannot find OpenGL ES Common or Common Lite DLL. + + /* The following fetches address to each egl & gl function call + * and stores it to the related function pointer. Casting through + * void * results in warnings with VC warning level 4, which + * could be fixed by casting to the true type for each fetch. + */ +#define IMPORT_FUNC(funcName) do { \ + void *procAddress = (void *)GetProcAddress(sGLESDLL, _T(#funcName)); \ + if (procAddress == NULL) result = 0; \ + *((void **)&FNPTR(funcName)) = procAddress; } while (0) +#endif // WIN32 + +#ifdef LINUX +#ifdef ANDROID_NDK + sGLESSO = dlopen("libGLESv1_CM.so", RTLD_NOW); +#else /* !ANDROID_NDK */ + sGLESSO = dlopen("libGLES_CM.so", RTLD_NOW); + if (sGLESSO == NULL) + sGLESSO = dlopen("libGLES_CL.so", RTLD_NOW); +#endif /* !ANDROID_NDK */ + if (sGLESSO == NULL) + return 0; // Cannot find OpenGL ES Common or Common Lite SO. + +#define IMPORT_FUNC(funcName) do { \ + void *procAddress = (void *)dlsym(sGLESSO, #funcName); \ + if (procAddress == NULL) result = 0; \ + *((void **)&FNPTR(funcName)) = procAddress; } while (0) +#endif // LINUX + +#ifndef ANDROID_NDK + IMPORT_FUNC(eglChooseConfig); + IMPORT_FUNC(eglCreateContext); + IMPORT_FUNC(eglCreateWindowSurface); + IMPORT_FUNC(eglDestroyContext); + IMPORT_FUNC(eglDestroySurface); + IMPORT_FUNC(eglGetConfigAttrib); + IMPORT_FUNC(eglGetConfigs); + IMPORT_FUNC(eglGetDisplay); + IMPORT_FUNC(eglGetError); + IMPORT_FUNC(eglInitialize); + IMPORT_FUNC(eglMakeCurrent); + IMPORT_FUNC(eglSwapBuffers); + IMPORT_FUNC(eglTerminate); +#endif /* !ANDROID_NDK */ + + IMPORT_FUNC(glBlendFunc); + IMPORT_FUNC(glClear); + IMPORT_FUNC(glClearColorx); + IMPORT_FUNC(glColor4x); + IMPORT_FUNC(glColorPointer); + IMPORT_FUNC(glDisable); + IMPORT_FUNC(glDisableClientState); + IMPORT_FUNC(glDrawArrays); + IMPORT_FUNC(glEnable); + IMPORT_FUNC(glEnableClientState); + IMPORT_FUNC(glFrustumx); + IMPORT_FUNC(glGetError); + IMPORT_FUNC(glLightxv); + IMPORT_FUNC(glLoadIdentity); + IMPORT_FUNC(glMaterialx); + IMPORT_FUNC(glMaterialxv); + IMPORT_FUNC(glMatrixMode); + IMPORT_FUNC(glMultMatrixx); + IMPORT_FUNC(glNormalPointer); + IMPORT_FUNC(glPopMatrix); + IMPORT_FUNC(glPushMatrix); + IMPORT_FUNC(glRotatex); + IMPORT_FUNC(glScalex); + IMPORT_FUNC(glShadeModel); + IMPORT_FUNC(glTranslatex); + IMPORT_FUNC(glVertexPointer); + IMPORT_FUNC(glViewport); + +#endif /* DISABLE_IMPORTGL */ + + return result; +} + + +void importGLDeinit() +{ +#ifndef DISABLE_IMPORTGL +#ifdef WIN32 + FreeLibrary(sGLESDLL); +#endif + +#ifdef LINUX + dlclose(sGLESSO); +#endif +#endif /* DISABLE_IMPORTGL */ +} diff --git a/tests/ndkSanAngeles/src/main/jni/importgl.h b/tests/ndkSanAngeles/src/main/jni/importgl.h new file mode 100644 index 0000000..a19a3a7 --- /dev/null +++ b/tests/ndkSanAngeles/src/main/jni/importgl.h @@ -0,0 +1,171 @@ +/* San Angeles Observation OpenGL ES version example + * Copyright 2004-2005 Jetro Lauha + * All rights reserved. + * Web: http://iki.fi/jetro/ + * + * This source is free software; you can redistribute it and/or + * modify it under the terms of EITHER: + * (1) The GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at + * your option) any later version. The text of the GNU Lesser + * General Public License is included with this source in the + * file LICENSE-LGPL.txt. + * (2) The BSD-style license that is included with this source in + * the file LICENSE-BSD.txt. + * + * This source is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files + * LICENSE-LGPL.txt and LICENSE-BSD.txt for more details. + * + * $Id: importgl.h,v 1.4 2005/02/24 20:29:33 tonic Exp $ + * $Revision: 1.4 $ + */ + +#ifndef IMPORTGL_H_INCLUDED +#define IMPORTGL_H_INCLUDED + + +#ifdef __cplusplus +extern "C" { +#endif + + +#include <GLES/gl.h> +#ifndef ANDROID_NDK +#include <GLES/egl.h> +#endif /* !ANDROID_NDK */ + +/* Dynamically fetches pointers to the egl & gl functions. + * Should be called once on application initialization. + * Returns non-zero on success and 0 on failure. + */ +extern int importGLInit(); + +/* Frees the handle to egl & gl functions library. + */ +extern void importGLDeinit(); + +/* Use DISABLE_IMPORTGL if you want to link the OpenGL ES at + * compile/link time and not import it dynamically runtime. + */ +#ifndef DISABLE_IMPORTGL + + +#ifndef IMPORTGL_API +#define IMPORTGL_API extern +#endif +#ifndef IMPORTGL_FNPTRINIT +#define IMPORTGL_FNPTRINIT +#endif + +#define FNDEF(retType, funcName, args) IMPORTGL_API retType (*funcPtr_##funcName) args IMPORTGL_FNPTRINIT + +#ifndef ANDROID_NDK +FNDEF(EGLBoolean, eglChooseConfig, (EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config)); +FNDEF(EGLContext, eglCreateContext, (EGLDisplay dpy, EGLConfig config, EGLContext share_list, const EGLint *attrib_list)); +FNDEF(EGLSurface, eglCreateWindowSurface, (EGLDisplay dpy, EGLConfig config, NativeWindowType window, const EGLint *attrib_list)); +FNDEF(EGLBoolean, eglDestroyContext, (EGLDisplay dpy, EGLContext ctx)); +FNDEF(EGLBoolean, eglDestroySurface, (EGLDisplay dpy, EGLSurface surface)); +FNDEF(EGLBoolean, eglGetConfigAttrib, (EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value)); +FNDEF(EGLBoolean, eglGetConfigs, (EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config)); +FNDEF(EGLDisplay, eglGetDisplay, (NativeDisplayType display)); +FNDEF(EGLint, eglGetError, (void)); +FNDEF(EGLBoolean, eglInitialize, (EGLDisplay dpy, EGLint *major, EGLint *minor)); +FNDEF(EGLBoolean, eglMakeCurrent, (EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx)); +FNDEF(EGLBoolean, eglSwapBuffers, (EGLDisplay dpy, EGLSurface draw)); +FNDEF(EGLBoolean, eglTerminate, (EGLDisplay dpy)); +#endif /* !ANDROID_NDK */ + +FNDEF(void, glBlendFunc, (GLenum sfactor, GLenum dfactor)); +FNDEF(void, glClear, (GLbitfield mask)); +FNDEF(void, glClearColorx, (GLclampx red, GLclampx green, GLclampx blue, GLclampx alpha)); +FNDEF(void, glColor4x, (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha)); +FNDEF(void, glColorPointer, (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)); +FNDEF(void, glDisable, (GLenum cap)); +FNDEF(void, glDisableClientState, (GLenum array)); +FNDEF(void, glDrawArrays, (GLenum mode, GLint first, GLsizei count)); +FNDEF(void, glEnable, (GLenum cap)); +FNDEF(void, glEnableClientState, (GLenum array)); +FNDEF(void, glFrustumx, (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar)); +FNDEF(GLenum, glGetError, (void)); +FNDEF(void, glLightxv, (GLenum light, GLenum pname, const GLfixed *params)); +FNDEF(void, glLoadIdentity, (void)); +FNDEF(void, glMaterialx, (GLenum face, GLenum pname, GLfixed param)); +FNDEF(void, glMaterialxv, (GLenum face, GLenum pname, const GLfixed *params)); +FNDEF(void, glMatrixMode, (GLenum mode)); +FNDEF(void, glMultMatrixx, (const GLfixed *m)); +FNDEF(void, glNormalPointer, (GLenum type, GLsizei stride, const GLvoid *pointer)); +FNDEF(void, glPopMatrix, (void)); +FNDEF(void, glPushMatrix, (void)); +FNDEF(void, glRotatex, (GLfixed angle, GLfixed x, GLfixed y, GLfixed z)); +FNDEF(void, glScalex, (GLfixed x, GLfixed y, GLfixed z)); +FNDEF(void, glShadeModel, (GLenum mode)); +FNDEF(void, glTranslatex, (GLfixed x, GLfixed y, GLfixed z)); +FNDEF(void, glVertexPointer, (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)); +FNDEF(void, glViewport, (GLint x, GLint y, GLsizei width, GLsizei height)); + + +#undef FN +#define FNPTR(name) funcPtr_##name + +#ifndef IMPORTGL_NO_FNPTR_DEFS + +// Redirect egl* and gl* function calls to funcPtr_egl* and funcPtr_gl*. + +#ifndef ANDROID_NDK +#define eglChooseConfig FNPTR(eglChooseConfig) +#define eglCreateContext FNPTR(eglCreateContext) +#define eglCreateWindowSurface FNPTR(eglCreateWindowSurface) +#define eglDestroyContext FNPTR(eglDestroyContext) +#define eglDestroySurface FNPTR(eglDestroySurface) +#define eglGetConfigAttrib FNPTR(eglGetConfigAttrib) +#define eglGetConfigs FNPTR(eglGetConfigs) +#define eglGetDisplay FNPTR(eglGetDisplay) +#define eglGetError FNPTR(eglGetError) +#define eglInitialize FNPTR(eglInitialize) +#define eglMakeCurrent FNPTR(eglMakeCurrent) +#define eglSwapBuffers FNPTR(eglSwapBuffers) +#define eglTerminate FNPTR(eglTerminate) +#endif /* !ANDROID_NDK */ + +#define glBlendFunc FNPTR(glBlendFunc) +#define glClear FNPTR(glClear) +#define glClearColorx FNPTR(glClearColorx) +#define glColor4x FNPTR(glColor4x) +#define glColorPointer FNPTR(glColorPointer) +#define glDisable FNPTR(glDisable) +#define glDisableClientState FNPTR(glDisableClientState) +#define glDrawArrays FNPTR(glDrawArrays) +#define glEnable FNPTR(glEnable) +#define glEnableClientState FNPTR(glEnableClientState) +#define glFrustumx FNPTR(glFrustumx) +#define glGetError FNPTR(glGetError) +#define glLightxv FNPTR(glLightxv) +#define glLoadIdentity FNPTR(glLoadIdentity) +#define glMaterialx FNPTR(glMaterialx) +#define glMaterialxv FNPTR(glMaterialxv) +#define glMatrixMode FNPTR(glMatrixMode) +#define glMultMatrixx FNPTR(glMultMatrixx) +#define glNormalPointer FNPTR(glNormalPointer) +#define glPopMatrix FNPTR(glPopMatrix) +#define glPushMatrix FNPTR(glPushMatrix) +#define glRotatex FNPTR(glRotatex) +#define glScalex FNPTR(glScalex) +#define glShadeModel FNPTR(glShadeModel) +#define glTranslatex FNPTR(glTranslatex) +#define glVertexPointer FNPTR(glVertexPointer) +#define glViewport FNPTR(glViewport) + +#endif // !IMPORTGL_NO_FNPTR_DEFS + + +#endif // !DISABLE_IMPORTGL + + +#ifdef __cplusplus +} +#endif + + +#endif // !IMPORTGL_H_INCLUDED diff --git a/tests/ndkSanAngeles/src/main/jni/shapes.h b/tests/ndkSanAngeles/src/main/jni/shapes.h new file mode 100644 index 0000000..25ffae8 --- /dev/null +++ b/tests/ndkSanAngeles/src/main/jni/shapes.h @@ -0,0 +1,59 @@ +/* San Angeles Observation OpenGL ES version example + * Copyright 2004-2005 Jetro Lauha + * All rights reserved. + * Web: http://iki.fi/jetro/ + * + * This source is free software; you can redistribute it and/or + * modify it under the terms of EITHER: + * (1) The GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at + * your option) any later version. The text of the GNU Lesser + * General Public License is included with this source in the + * file LICENSE-LGPL.txt. + * (2) The BSD-style license that is included with this source in + * the file LICENSE-BSD.txt. + * + * This source is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files + * LICENSE-LGPL.txt and LICENSE-BSD.txt for more details. + * + * $Id: shapes.h,v 1.6 2005/01/31 22:15:30 tonic Exp $ + * $Revision: 1.6 $ + */ + +#ifndef SHAPES_H_INCLUDED +#define SHAPES_H_INCLUDED + + +#define SUPERSHAPE_PARAMS 15 + +static const float sSuperShapeParams[][SUPERSHAPE_PARAMS] = +{ + // m a b n1 n2 n3 m a b n1 n2 n3 res1 res2 scale (org.res1,res2) + { 10, 1, 2, 90, 1, -45, 8, 1, 1, -1, 1, -0.4f, 20, 30, 2 }, // 40, 60 + { 10, 1, 2, 90, 1, -45, 4, 1, 1, 10, 1, -0.4f, 20, 20, 4 }, // 40, 40 + { 10, 1, 2, 60, 1, -10, 4, 1, 1, -1, -2, -0.4f, 41, 41, 1 }, // 82, 82 + { 6, 1, 1, 60, 1, -70, 8, 1, 1, 0.4f, 3, 0.25f, 20, 20, 1 }, // 40, 40 + { 4, 1, 1, 30, 1, 20, 12, 1, 1, 0.4f, 3, 0.25f, 10, 30, 1 }, // 20, 60 + { 8, 1, 1, 30, 1, -4, 8, 2, 1, -1, 5, 0.5f, 25, 26, 1 }, // 60, 60 + { 13, 1, 1, 30, 1, -4, 13, 1, 1, 1, 5, 1, 30, 30, 6 }, // 60, 60 + { 10, 1, 1.1f, -0.5f, 0.1f, 70, 60, 1, 1, -90, 0, -0.25f, 20, 60, 8 }, // 60, 180 + { 7, 1, 1, 20, -0.3f, -3.5f, 6, 1, 1, -1, 4.5f, 0.5f, 10, 20, 4 }, // 60, 80 + { 4, 1, 1, 10, 10, 10, 4, 1, 1, 10, 10, 10, 10, 20, 1 }, // 20, 40 + { 4, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 10, 10, 2 }, // 10, 10 + { 1, 1, 1, 38, -0.25f, 19, 4, 1, 1, 10, 10, 10, 10, 15, 2 }, // 20, 40 + { 2, 1, 1, 0.7f, 0.3f, 0.2f, 3, 1, 1, 100, 100, 100, 10, 25, 2 }, // 20, 50 + { 6, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 30, 30, 2 }, // 60, 60 + { 3, 1, 1, 1, 1, 1, 6, 1, 1, 2, 1, 1, 10, 20, 2 }, // 20, 40 + { 6, 1, 1, 6, 5.5f, 100, 6, 1, 1, 25, 10, 10, 30, 20, 2 }, // 60, 40 + { 3, 1, 1, 0.5f, 1.7f, 1.7f, 2, 1, 1, 10, 10, 10, 20, 20, 2 }, // 40, 40 + { 5, 1, 1, 0.1f, 1.7f, 1.7f, 1, 1, 1, 0.3f, 0.5f, 0.5f, 20, 20, 4 }, // 40, 40 + { 2, 1, 1, 6, 5.5f, 100, 6, 1, 1, 4, 10, 10, 10, 22, 1 }, // 40, 40 + { 6, 1, 1, -1, 70, 0.1f, 9, 1, 0.5f, -98, 0.05f, -45, 20, 30, 4 }, // 60, 91 + { 6, 1, 1, -1, 90, -0.1f, 7, 1, 1, 90, 1.3f, 34, 13, 16, 1 }, // 32, 60 +}; +#define SUPERSHAPE_COUNT (sizeof(sSuperShapeParams) / sizeof(sSuperShapeParams[0])) + + +#endif // !SHAPES_H_INCLUDED diff --git a/tests/ndkSanAngeles/src/main/res/layout/main.xml b/tests/ndkSanAngeles/src/main/res/layout/main.xml new file mode 100644 index 0000000..3e76662 --- /dev/null +++ b/tests/ndkSanAngeles/src/main/res/layout/main.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="vertical" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + > +<TextView + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:text="Hello World, DemoActivity" + /> +</LinearLayout> + diff --git a/tests/ndkSanAngeles/src/main/res/values/strings.xml b/tests/ndkSanAngeles/src/main/res/values/strings.xml new file mode 100644 index 0000000..574c333 --- /dev/null +++ b/tests/ndkSanAngeles/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <string name="app_name">SanAngeles</string> +</resources> |