ARCore使用

一. 配置您項(xiàng)目的 build.gradle 文件,相關(guān)AR項(xiàng)目引用

官網(wǎng)地址
官網(wǎng)demo地址

1.確保您項(xiàng)目的 build.gradle 包括 Google 的 Maven 代碼庫:
allprojects {
    repositories {
        google()
        jcenter()
    }
}
2.更新您應(yīng)用的 build.gradle 以添加最新的 ARCore 和 Sceneform 用戶體驗(yàn)依賴項(xiàng),確保您的項(xiàng)目設(shè)置與兩個庫都兼容。
android {
    …
    defaultConfig {
        // Sceneform requires minSdkVersion >= 24.
        minSdkVersion 24
        …
    }
    // Sceneform libraries use language constructs from Java 8.
    // Add these compile options if targeting minSdkVersion < 26.
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    …
    // Provides ARCore Session and related resources.
    implementation 'com.google.ar:core:1.5.0'

    // Provides ArFragment, and other UX resources.
    implementation 'com.google.ar.sceneform.ux:sceneform-ux:1.5.0'

    // Alternatively, use ArSceneView without the UX dependency.
    implementation 'com.google.ar.sceneform:core:1.5.0'
}
3.更新您的 AndroidManifest.xml

修改您的 AndroidManifest.xml 來指示您的應(yīng)用使用(AR 可選)或需要(AR 必備)ARCore 和攝像頭訪問權(quán)限:

<!-- Both "AR Optional" and "AR Required" apps require CAMERA permission. -->
<uses-permission android:name="android.permission.CAMERA" />

<!-- Indicates that app requires ARCore ("AR Required"). Ensures app is only
     visible in the Google Play Store on devices that support ARCore.
     For "AR Optional" apps remove this line. -->
<uses-feature android:name="android.hardware.camera.ar" />

<application>
    …
    <!-- Indicates that app requires ARCore ("AR Required"). Causes Google
         Play Store to download and install ARCore along with the app.
         For an "AR Optional" app, specify "optional" instead of "required".
    -->
    <meta-data android:name="com.google.ar.core" android:value="required" />
</application>

二. Android Studio中預(yù)覽3D模型文件 官網(wǎng)說明

1.安裝 Google Sceneform Tools (Beta) 插件

在 Android Studio 中,打開 Plugins 設(shè)置:

Windows:File > Settings > Plugins > Browse Repositories
macOS:Android Studio > Preferences > Plugins
然后點(diǎn)擊 Browse repositories 并安裝 Google Sceneform Tools (Beta)。


image.png
2.導(dǎo)入3D asset, 添加Sampledata文件(已經(jīng)有,可以不再新建)
image.png
3.copy模型文件到sampledata中,如果沒有模型文件, 可下載官網(wǎng)demo官網(wǎng)demo地址
4.選擇.obj文件導(dǎo)入模型在Android studio中查看
image.png

image.png

更新您的應(yīng)用的 build.gradle 文件,為新導(dǎo)入的 asset 添加一個 apply plugin 行和一個 sceneform.asset() 條目:

apply plugin: 'com.google.ar.sceneform.plugin'
//導(dǎo)入成功后,下面代碼會自動生成
sceneform.asset('sampledata/models/andy.obj', // 'Source Asset Path' specified during import.
        'default',                            // 'Material Path' specified during import.
        'sampledata/models/andy.sfa',         // '.sfa Output Path' specified during import.
        'src/main/res/raw/andy')              // '.sfb Output Path' specified during import.
4.檢查是否支持ARCore,并且檢查權(quán)限
//檢查是否支持ARCore
 /**
   * Returns false and displays an error message if Sceneform can not run, true if Sceneform can run
   * on this device.
   *
   * <p>Sceneform requires Android N on the device as well as OpenGL 3.0 capabilities.
   *
   * <p>Finishes the activity if Sceneform can not run
   */
  public static boolean checkIsSupportedDeviceOrFinish(final Activity activity) {
    if (Build.VERSION.SDK_INT < VERSION_CODES.N) {
      Log.e(TAG, "this APP requires Android N or later");
      Toast.makeText(activity, "this APP Android N or later", Toast.LENGTH_LONG).show();
      activity.finish();
      return false;
    }
    String openGlVersionString =
        ((ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE))
            .getDeviceConfigurationInfo()
            .getGlEsVersion();
    if (Double.parseDouble(openGlVersionString) < MIN_OPENGL_VERSION) {
      Log.e(TAG, "Sceneform requires OpenGL ES 3.0 later");
      Toast.makeText(activity, "Sceneform requires OpenGL ES 3.0 or later", Toast.LENGTH_LONG)
          .show();
      activity.finish();
      return false;
    }
    return true;
  }

//檢查申請權(quán)限
 public static final int PERMISSION_REQUESTCODE = 0;
    public static void checkPermissions(final Activity activity) {
        List<String> needRequestPermissionList = findDeniedPermissions(activity,needPermissions);
        if (needRequestPermissionList != null
                && needRequestPermissionList.size() > 0) {
            String[] array = needRequestPermissionList.toArray(new String[needRequestPermissionList.size()]);
            activity.requestPermissions(array, PERMISSION_REQUESTCODE);
        }
    }

    public static List<String> findDeniedPermissions(final Activity activity,String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<String>();
        try {
            for (String perm : permissions) {
                Method checkSelfMethod = activity.getClass().getMethod("checkSelfPermission", String.class);
                Method shouldShowRequestPermissionRationaleMethod = activity.getClass().getMethod("shouldShowRequestPermissionRationale",
                        String.class);
                if ((Integer)checkSelfMethod.invoke(activity, perm) != PackageManager.PERMISSION_GRANTED
                        || (Boolean)shouldShowRequestPermissionRationaleMethod.invoke(activity, perm)) {
                    needRequestPermissionList.add(perm);
                }
            }
        } catch (Throwable e) {

        }
        return needRequestPermissionList;
    }

三. 代碼部分

1.xml文件部分
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.PlaneModelActvity">

   <fragment android:name="com.google.ar.sceneform.ux.ArFragment"
       android:id="@+id/ux_fragment"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />

</FrameLayout>
2.java代碼部分
private ArFragment fragment;
private ModelRenderable andyRenderable;

fragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.ux_fragment);

//初始化模型文件
ModelRenderable.builder()
                .setSource(this, Uri.parse("andy.sfb"))  //加載模型資源
                .build()
                .thenAccept(renderable -> andyRenderable = renderable)
                .exceptionally(
                        throwable -> {
                            Toast toast =
                                    Toast.makeText(this, "Unable to load andy renderable", Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                            return null;
                        });

        fragment.setOnTapArPlaneListener(
                (HitResult hitResult, Plane plane, MotionEvent motionEvent) -> {
                    if (andyRenderable == null) {
                        return;
                    }

                    // Create the Anchor. 創(chuàng)建定位點(diǎn)
                    Anchor anchor = hitResult.createAnchor();
                    AnchorNode anchorNode = new AnchorNode(anchor);
                    anchorNode.setParent(fragment.getArSceneView().getScene());

                    // Create the transformable andy and add it to the anchor.
                    TransformableNode andy = new TransformableNode(fragment.getTransformationSystem());
                    andy.setParent(anchorNode);
                    andy.setRenderable(andyRenderable);
                    andy.select();
                });

常見問題

1. 如果點(diǎn)擊 Sample Data Directory并沒有新建出sampledata文件夾, 可以手動創(chuàng)建, 并將模型文件Copy進(jìn)去, 再進(jìn)行 Import Sceneform Asset 操作。

2.點(diǎn)擊obj/fbx文件,發(fā)現(xiàn)并沒有Import Sceneform Asset 選項(xiàng)
解決方案:
2.1 回到文章上端查看安裝 Google Sceneform Tools (Beta) 插件, 不安裝肯定是找不到Import Sceneform Asset選項(xiàng)的

image.png

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容