Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Copyright 2018 Google LLC.
- *
- * 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 hicnet.andrea.mumtaksf
- import android.Manifest
- import android.annotation.SuppressLint
- import android.app.Activity
- import android.bluetooth.BluetoothClass
- import android.content.Context
- import android.content.Intent
- import android.content.pm.PackageManager
- import android.location.Location
- import android.location.LocationManager
- import android.os.AsyncTask
- import android.os.Bundle
- import android.os.Debug
- import android.provider.AlarmClock.EXTRA_MESSAGE
- import android.provider.Settings
- import android.support.design.widget.Snackbar
- import android.support.v4.app.ActivityCompat
- import android.support.v4.content.ContextCompat
- import android.support.v4.view.GestureDetectorCompat
- import android.support.v7.app.AppCompatActivity
- import android.util.Log
- import android.view.GestureDetector
- import android.view.MotionEvent
- import android.view.View
- import android.view.WindowManager
- import android.widget.ImageView
- import android.widget.TextView
- import android.widget.Toast
- import com.github.pwittchen.swipe.library.rx2.Swipe
- import com.github.pwittchen.swipe.library.rx2.SwipeListener
- import com.google.android.gms.common.ConnectionResult
- import com.google.android.gms.common.api.GoogleApiClient
- import com.google.android.gms.common.api.Result
- import com.google.ar.core.Frame
- import com.google.ar.core.Plane
- import com.google.ar.core.Session
- import com.google.ar.core.TrackingState
- import com.google.ar.core.exceptions.CameraNotAvailableException
- import com.google.ar.core.exceptions.UnavailableException
- import com.google.ar.sceneform.ArSceneView
- import com.google.ar.sceneform.Node
- import com.google.ar.sceneform.rendering.ModelRenderable
- import com.google.ar.sceneform.rendering.ViewRenderable
- import fr.quentinklein.slt.LocationTracker
- import hicnet.andrea.mumtaksf.stuff.Categories
- import hicnet.andrea.mumtaksf.stuff.Tak
- import java.util.concurrent.CompletableFuture
- import java.util.concurrent.ExecutionException
- import hicnet.andrea.mumtaksf.stuff.LocationScene
- import hicnet.andrea.mumtaksf.stuff.LocationUtil.LocationHelper
- import hicnet.andrea.mumtaksf.stuff.rendering.LocationNode
- import hicnet.andrea.mumtaksf.stuff.rendering.LocationNodeRender
- import hicnet.andrea.mumtaksf.stuff.sensor.DeviceLocation
- import hicnet.andrea.mumtaksf.stuff.utils.ARLocationPermissionHelper
- import java.io.Serializable
- import khttp.post
- import org.jetbrains.anko.custom.async
- import org.jetbrains.anko.doAsync
- import org.jetbrains.anko.doAsyncResult
- import org.json.JSONArray
- import org.json.JSONObject
- import uk.co.appoly.arcorelocation.LocationMarker
- class LocationActivity : AppCompatActivity(), Serializable {
- private var swipe: Swipe? = null
- var lastLoc: Location? = null
- private var installRequested: Boolean = false
- private var hasFinishedLoading = false
- private var loadingMessageSnackbar: Snackbar? = null
- private var arSceneView: ArSceneView? = null
- // Renderables for this example
- private var andyRenderable: ModelRenderable? = null
- private var exampleLayoutRenderable: ViewRenderable? = null
- // Our ARCore-Location scene
- private var locationScene: LocationScene? = null
- var PERMISSION_REQUEST_LOCATION: Int = 0
- var completableFutureArray:Array<CompletableFuture<ViewRenderable>>? = null
- var completableFutureHashMap:HashMap<String,CompletableFuture<ViewRenderable>>? = null
- // Add listeners etc here
- val exampleView: Node
- get() {
- val base = Node()
- base.renderable = exampleLayoutRenderable
- val eView = exampleLayoutRenderable!!.view
- eView.setOnTouchListener(object : View.OnTouchListener {
- override fun onTouch(v: View?, event: MotionEvent?): Boolean {
- Toast.makeText(this@LocationActivity, "Location marker touched.", Toast.LENGTH_LONG).show()
- //onTakTouched()
- return false
- }
- })
- return base
- }
- var takList: ArrayList<Tak>? = null
- @SuppressLint("MissingPermission")
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_sceneform)
- // if (ContextCompat.checkSelfPermission(this@LocationActivity, Manifest.permission.ACCESS_FINE_LOCATION)
- // != PackageManager.PERMISSION_GRANTED) {
- // ActivityCompat.requestPermissions(this@LocationActivity,
- // arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
- // PERMISSION_REQUEST_LOCATION)
- //
- // }
- var tempTakList:JSONArray? = null
- doAsync {
- tempTakList = khttp.get("http://ar-demo.hicnet.it/api/locations").jsonArray
- }
- while(tempTakList == null){
- //Log.e("DIOCANE", "INIZIO PAUSA 10 s")
- Thread.sleep(1000)
- }
- Log.e("DIOCANE", ""+ tempTakList!!.length())
- takList = ArrayList()
- for(i in tempTakList!!.length()-1 downTo 0 step 1 ){
- var jsonObj = tempTakList!!.getJSONObject(i)
- //String name, double latitude, double longitude, double altitude, String desc, String cat, int duration, Node node
- takList?.add(Tak(jsonObj.getString("name"),jsonObj.getString("latitude").toDouble(),
- jsonObj.getString("longitude").toDouble(),0.0,
- "","",0,null))
- //Log.e("EAJASDIADJAI ", "gg "+takList?.get(0)?.name)
- }
- //takList?.forEachIndexed { index, i -> Log.e("EAJASDIADJAI ","index $index " +"Name" +takList!![index].name +" Lat "+takList!![index].latitude+ "long" + takList!![index].longitude ) }
- var size:Int = takList?.size!!
- completableFutureHashMap = HashMap()
- completableFutureArray = Array<CompletableFuture<ViewRenderable>>(size, {
- i ->
- var locationSource = takList!!.get(i)
- val completableFuture = ViewRenderable.builder().setView(this, R.layout.example_layout).build()
- completableFutureHashMap!!.put(locationSource.name, completableFuture)
- completableFuture
- }
- )
- if (ContextCompat.checkSelfPermission(this.applicationContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this.applicationContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- //MANCANO I PERMESSI!!!
- } else {
- val tracker = object : LocationTracker(this.applicationContext) {
- override fun onTimeout() {}
- override fun onLocationFound(location: Location) {
- lastLoc = location
- findViewById<TextView>(R.id.currentPos).text = location.latitude.toString() + " " + location.longitude + "\nACC: " + location.accuracy+"Tak:"+ takList?.size
- }
- }
- tracker.startListening()
- }
- swipe = Swipe()
- swipe!!.setListener(object : SwipeListener {
- override fun onSwipedUp(event: MotionEvent?): Boolean {
- //if(lastLoc!=null){
- val intent = Intent(this@LocationActivity, TakInputActivity::class.java)
- intent.putExtra("Latitude", lastLoc!!.latitude)
- intent.putExtra("Longitude", lastLoc!!.longitude)
- intent.putExtra("Altitude", lastLoc!!.altitude)
- startActivityForResult(intent, 0)
- //}else{
- // Toast.makeText(this@LocationActivity, "Segnale GPS troppo debole per inserire tak!", Toast.LENGTH_SHORT).show()
- // }
- return true
- }
- override fun onSwipedDown(event: MotionEvent?): Boolean {
- return false
- }
- override fun onSwipingUp(event: MotionEvent?) {}
- override fun onSwipedRight(event: MotionEvent?): Boolean {
- return false
- }
- override fun onSwipingLeft(event: MotionEvent?) {}
- override fun onSwipingRight(event: MotionEvent?) {}
- override fun onSwipingDown(event: MotionEvent?) {}
- override fun onSwipedLeft(event: MotionEvent?): Boolean {
- return false
- }
- })
- arSceneView = findViewById(R.id.ar_scene_view)
- // Build a renderable from a 2D View.
- val exampleLayout = ViewRenderable.builder()
- .setView(this, R.layout.example_layout)
- .build()
- // When you build a Renderable, Sceneform loads its resources in the background while returning
- // a CompletableFuture. Call thenAccept(), handle(), or check isDone() before calling get().
- val andy = ModelRenderable.builder()
- .setSource(this, R.raw.andy)
- .build()
- CompletableFuture.allOf(
- *completableFutureArray!!)
- .handle<Any> CompletableFuture@{ notUsed, throwable ->
- // When you build a Renderable, Sceneform loads its resources in the background while
- // returning a CompletableFuture. Call handle(), thenAccept(), or check isDone()
- // before calling get().
- if (throwable != null) {
- DemoUtils.displayError(this, "Unable to load renderables", throwable)
- return@CompletableFuture null
- }
- hasFinishedLoading = true;
- null
- }
- // Set an update listener on the Scene that will hide the loading message once a Plane is
- // detected.
- arSceneView!!
- .scene
- .setOnUpdateListener { frameTime ->
- if (!hasFinishedLoading) {
- return@setOnUpdateListener
- }
- if (locationScene == null) {
- locationScene = LocationScene(this, this, arSceneView!!)
- // val layoutLocationMarker = Tak("Bar da Chao", 39.4841303, -0.3657801, 18.0,
- // "Descrizione", Categories.eating.bar.toString(), 0, exampleView)
- //
- // // An example "onRender" event, called every frame
- // // Updates the layout with the markers distance
- // layoutLocationMarker.setRenderEvent(object : LocationNodeRender {
- // override fun render(node: LocationNode) {
- // val eView = exampleLayoutRenderable!!.view
- // eView.findViewById<TextView>(R.id.takName).setText(layoutLocationMarker.name)
- // eView.findViewById<TextView>(R.id.takPos).setText(node.getDistance().toString() + "m")
- // }
- // })
- // // Adding the marker
- // locationScene!!.mLocationMarkers.add(layoutLocationMarker)
- for(tak in takList!!){
- //String name, double latitude, double longitude, double altitude, String desc, String cat, int duration, Node node
- var marker = Tak(tak.name,tak.latitude,tak.longitude,tak.altitude,tak.desc,"PERMA",0,Node())
- var completableFuture = completableFutureHashMap!!.get(tak.name)
- Log.w("DIOCANE", ""+tak.name)
- try {
- var viewRenderable = completableFuture!!.get()
- marker.node.setRenderable(viewRenderable)
- //Toast.makeText(this@LocationActivity, tak.name +" - distance "+marker.anchorNode.getDistance() + " meters", Toast.LENGTH_LONG).show()
- marker.node.setOnTapListener { v, event -> Toast.makeText(this@LocationActivity, tak.name + " - distance " + marker.anchorNode.distance + " meters", Toast.LENGTH_LONG).show() }
- marker.setOnlyRenderWhenWithin(1000)
- val nameTextView = viewRenderable.view.findViewById<TextView>(R.id.takName)
- nameTextView.setText(tak.name)
- marker.setRenderEvent { n ->
- val distanceTextView = viewRenderable.view.findViewById<TextView>(R.id.takPos)
- distanceTextView.setText(""+n.distance + " Meters")
- }
- locationScene!!.mLocationMarkers.add(marker);
- }
- catch (ex: Exception) {
- DemoUtils.displayError(this, "Unable to load renderables", ex);
- }
- }
- }
- /*|||||||||||||||||||||||*/
- /* UPDATE FUNCTION */
- /*|||||||||||||||||||||||*/
- val frame = arSceneView!!.arFrame
- if (frame == null) {
- return@setOnUpdateListener
- }
- if (frame!!.camera.trackingState != TrackingState.TRACKING) {
- return@setOnUpdateListener
- }
- if (locationScene != null) {
- locationScene!!.processFrame(frame)
- }
- if (loadingMessageSnackbar != null) {
- for (plane in frame.getUpdatedTrackables(Plane::class.java)) {
- if (plane.trackingState == TrackingState.TRACKING) {
- hideLoadingMessage()
- }
- }
- }
- }
- ARLocationPermissionHelper.requestPermission(this)
- }
- fun placeTak(newTak: Tak) {
- newTak.node = exampleView
- var t = doAsync {
- var r = khttp.post("http://ar-demo.hicnet.it/api/locations/new",
- data = mapOf("name" to newTak.name, "latitude" to newTak.latitude,
- "longitude" to newTak.longitude, "altitude" to newTak.altitude,
- "duration" to newTak.duration))
- }
- newTak.setRenderEvent(object : LocationNodeRender {
- override fun render(node: LocationNode) {
- val eView = exampleLayoutRenderable!!.view
- eView.findViewById<TextView>(R.id.takName).setText(newTak.name)
- if (newTak.type == Tak.types.TEMP) {
- eView.findViewById<ImageView>(R.id.takIcon).setImageResource(R.drawable.app_icon)
- }
- eView.findViewById<TextView>(R.id.takPos).setText(newTak.latitude.toString() + "," + newTak.longitude)
- }
- })
- locationScene!!.mLocationMarkers.add(newTak)
- Toast.makeText(this, "Tak creato con successo!", Toast.LENGTH_SHORT).show()
- }
- //LISTENER SWIPE E GESTURE
- override fun dispatchTouchEvent(event: MotionEvent): Boolean {
- swipe!!.dispatchTouchEvent(event)
- return super.dispatchTouchEvent(event)
- }
- override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
- if (requestCode == 0) {
- if (resultCode == Activity.RESULT_OK) {
- var result = data!!.getSerializableExtra("NewTak") as Tak
- placeTak(result)
- }
- }
- }
- //FUNZIONI PREDEFINITE
- override fun onResume() {
- super.onResume()
- if (locationScene != null) {
- locationScene!!.resume()
- }
- if (arSceneView!!.session == null) {
- // If the session wasn't created yet, don't resume rendering.
- // This can happen if ARCore needs to be updated or permissions are not granted yet.
- try {
- val session = DemoUtils.createArSession(this, installRequested)
- if (session == null) {
- installRequested = ARLocationPermissionHelper.hasPermission(this)
- return
- } else {
- arSceneView!!.setupSession(session)
- }
- } catch (e: UnavailableException) {
- DemoUtils.handleSessionException(this, e)
- }
- }
- try {
- arSceneView!!.resume()
- } catch (ex: CameraNotAvailableException) {
- DemoUtils.displayError(this, "Unable to get camera", ex)
- finish()
- return
- }
- if (arSceneView!!.session != null) {
- showLoadingMessage()
- }
- }
- public override fun onPause() {
- super.onPause()
- if (locationScene != null) {
- locationScene!!.pause()
- }
- arSceneView!!.pause()
- }
- public override fun onDestroy() {
- super.onDestroy()
- arSceneView!!.destroy()
- }
- override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, results: IntArray) {
- if (!ARLocationPermissionHelper.hasPermission(this)) {
- if (!ARLocationPermissionHelper.shouldShowRequestPermissionRationale(this)) {
- // Permission denied with checking "Do not ask again".
- ARLocationPermissionHelper.launchPermissionSettings(this)
- } else {
- Toast.makeText(
- this, "Camera permission is needed to run this application", Toast.LENGTH_LONG)
- .show()
- }
- finish()
- }
- }
- override fun onWindowFocusChanged(hasFocus: Boolean) {
- super.onWindowFocusChanged(hasFocus)
- if (hasFocus) {
- // Standard Android full-screen functionality.
- window
- .decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
- or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
- or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
- or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
- or View.SYSTEM_UI_FLAG_FULLSCREEN
- or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
- window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
- }
- }
- private fun showLoadingMessage() {
- if (loadingMessageSnackbar != null && loadingMessageSnackbar!!.isShownOrQueued) {
- return
- }
- loadingMessageSnackbar = Snackbar.make(
- this@LocationActivity.findViewById<View>(android.R.id.content),
- "Searching for planes...",
- Snackbar.LENGTH_INDEFINITE)
- loadingMessageSnackbar!!.view.setBackgroundColor(-0x40cdcdce)
- loadingMessageSnackbar!!.show()
- }
- private fun hideLoadingMessage() {
- if (loadingMessageSnackbar == null) {
- return
- }
- loadingMessageSnackbar!!.dismiss()
- loadingMessageSnackbar = null
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement