-
-
Notifications
You must be signed in to change notification settings - Fork 147
/
MainFragment.kt
83 lines (73 loc) · 3.01 KB
/
MainFragment.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.google.ar.sceneform.samples.gltf
import android.net.Uri
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.google.ar.core.HitResult
import com.google.ar.core.Plane
import com.google.ar.sceneform.AnchorNode
import com.google.ar.sceneform.Node
import com.google.ar.sceneform.SceneView
import com.google.ar.sceneform.math.Vector3
import com.google.ar.sceneform.rendering.ModelRenderable
import com.google.ar.sceneform.rendering.Renderable
import com.google.ar.sceneform.rendering.ViewRenderable
import com.google.ar.sceneform.ux.ArFragment
import com.google.ar.sceneform.ux.TransformableNode
import com.gorisse.thomas.sceneform.scene.await
class MainFragment : Fragment(R.layout.fragment_main) {
private lateinit var arFragment: ArFragment
private val arSceneView get() = arFragment.arSceneView
private val scene get() = arSceneView.scene
private var model: Renderable? = null
private var modelView: ViewRenderable? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arFragment = (childFragmentManager.findFragmentById(R.id.arFragment) as ArFragment).apply {
setOnSessionConfigurationListener { session, config ->
// Modify the AR session configuration here
}
setOnViewCreatedListener { arSceneView ->
arSceneView.setFrameRateFactor(SceneView.FrameRate.FULL)
}
setOnTapArPlaneListener(::onTapPlane)
}
lifecycleScope.launchWhenCreated {
loadModels()
}
}
private suspend fun loadModels() {
model = ModelRenderable.builder()
.setSource(context, Uri.parse("models/halloween.glb"))
.setIsFilamentGltf(true)
.await()
modelView = ViewRenderable.builder()
.setView(context, R.layout.view_renderable_infos)
.await()
}
private fun onTapPlane(hitResult: HitResult, plane: Plane, motionEvent: MotionEvent) {
if (model == null || modelView == null) {
Toast.makeText(context, "Loading...", Toast.LENGTH_SHORT).show()
return
}
// Create the Anchor.
scene.addChild(AnchorNode(hitResult.createAnchor()).apply {
// Create the transformable model and add it to the anchor.
addChild(TransformableNode(arFragment.transformationSystem).apply {
renderable = model
renderableInstance.setCulling(false)
renderableInstance.animate(true).start()
// Add the View
addChild(Node().apply {
// Define the relative position
localPosition = Vector3(0.0f, 1f, 0.0f)
localScale = Vector3(0.7f, 0.7f, 0.7f)
renderable = modelView
})
})
})
}
}