Advertisement
Guest User

Untitled

a guest
Sep 15th, 2018
560
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 19.93 KB | None | 0 0
  1. /*
  2.  * Copyright 2018 Google LLC.
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *      http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16. package hicnet.andrea.mumtaksf
  17.  
  18. import android.Manifest
  19. import android.annotation.SuppressLint
  20. import android.app.Activity
  21. import android.bluetooth.BluetoothClass
  22. import android.content.Context
  23. import android.content.Intent
  24. import android.content.pm.PackageManager
  25. import android.location.Location
  26. import android.location.LocationManager
  27. import android.os.AsyncTask
  28. import android.os.Bundle
  29. import android.os.Debug
  30. import android.provider.AlarmClock.EXTRA_MESSAGE
  31. import android.provider.Settings
  32. import android.support.design.widget.Snackbar
  33. import android.support.v4.app.ActivityCompat
  34. import android.support.v4.content.ContextCompat
  35. import android.support.v4.view.GestureDetectorCompat
  36. import android.support.v7.app.AppCompatActivity
  37. import android.util.Log
  38. import android.view.GestureDetector
  39. import android.view.MotionEvent
  40. import android.view.View
  41. import android.view.WindowManager
  42. import android.widget.ImageView
  43. import android.widget.TextView
  44. import android.widget.Toast
  45. import com.github.pwittchen.swipe.library.rx2.Swipe
  46. import com.github.pwittchen.swipe.library.rx2.SwipeListener
  47. import com.google.android.gms.common.ConnectionResult
  48. import com.google.android.gms.common.api.GoogleApiClient
  49. import com.google.android.gms.common.api.Result
  50. import com.google.ar.core.Frame
  51. import com.google.ar.core.Plane
  52. import com.google.ar.core.Session
  53. import com.google.ar.core.TrackingState
  54. import com.google.ar.core.exceptions.CameraNotAvailableException
  55. import com.google.ar.core.exceptions.UnavailableException
  56. import com.google.ar.sceneform.ArSceneView
  57. import com.google.ar.sceneform.Node
  58. import com.google.ar.sceneform.rendering.ModelRenderable
  59. import com.google.ar.sceneform.rendering.ViewRenderable
  60. import fr.quentinklein.slt.LocationTracker
  61. import hicnet.andrea.mumtaksf.stuff.Categories
  62. import hicnet.andrea.mumtaksf.stuff.Tak
  63. import java.util.concurrent.CompletableFuture
  64. import java.util.concurrent.ExecutionException
  65. import hicnet.andrea.mumtaksf.stuff.LocationScene
  66. import hicnet.andrea.mumtaksf.stuff.LocationUtil.LocationHelper
  67. import hicnet.andrea.mumtaksf.stuff.rendering.LocationNode
  68. import hicnet.andrea.mumtaksf.stuff.rendering.LocationNodeRender
  69. import hicnet.andrea.mumtaksf.stuff.sensor.DeviceLocation
  70. import hicnet.andrea.mumtaksf.stuff.utils.ARLocationPermissionHelper
  71. import java.io.Serializable
  72. import khttp.post
  73. import org.jetbrains.anko.custom.async
  74. import org.jetbrains.anko.doAsync
  75. import org.jetbrains.anko.doAsyncResult
  76. import org.json.JSONArray
  77. import org.json.JSONObject
  78. import uk.co.appoly.arcorelocation.LocationMarker
  79.  
  80. class LocationActivity : AppCompatActivity(), Serializable {
  81.     private var swipe: Swipe? = null
  82.  
  83.     var lastLoc: Location? = null
  84.     private var installRequested: Boolean = false
  85.     private var hasFinishedLoading = false
  86.     private var loadingMessageSnackbar: Snackbar? = null
  87.     private var arSceneView: ArSceneView? = null
  88.  
  89.     // Renderables for this example
  90.     private var andyRenderable: ModelRenderable? = null
  91.     private var exampleLayoutRenderable: ViewRenderable? = null
  92.  
  93.     // Our ARCore-Location scene
  94.     private var locationScene: LocationScene? = null
  95.     var PERMISSION_REQUEST_LOCATION: Int = 0
  96.  
  97.  
  98.     var completableFutureArray:Array<CompletableFuture<ViewRenderable>>? = null
  99.     var completableFutureHashMap:HashMap<String,CompletableFuture<ViewRenderable>>? = null
  100.  
  101.  
  102.  
  103.     // Add  listeners etc here
  104.     val exampleView: Node
  105.         get() {
  106.             val base = Node()
  107.             base.renderable = exampleLayoutRenderable
  108.             val eView = exampleLayoutRenderable!!.view
  109.             eView.setOnTouchListener(object : View.OnTouchListener {
  110.                 override fun onTouch(v: View?, event: MotionEvent?): Boolean {
  111.                     Toast.makeText(this@LocationActivity, "Location marker touched.", Toast.LENGTH_LONG).show()
  112.                     //onTakTouched()
  113.                     return false
  114.                 }
  115.             })
  116.             return base
  117.         }
  118.     var takList: ArrayList<Tak>? = null
  119.  
  120.     @SuppressLint("MissingPermission")
  121.     override fun onCreate(savedInstanceState: Bundle?) {
  122.         super.onCreate(savedInstanceState)
  123.         setContentView(R.layout.activity_sceneform)
  124.  
  125. //        if (ContextCompat.checkSelfPermission(this@LocationActivity, Manifest.permission.ACCESS_FINE_LOCATION)
  126. //                != PackageManager.PERMISSION_GRANTED) {
  127. //            ActivityCompat.requestPermissions(this@LocationActivity,
  128. //                    arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
  129. //                    PERMISSION_REQUEST_LOCATION)
  130. //
  131. //        }
  132.  
  133.         var tempTakList:JSONArray? = null
  134.         doAsync {
  135.            tempTakList = khttp.get("http://ar-demo.hicnet.it/api/locations").jsonArray
  136.         }
  137.         while(tempTakList == null){
  138.             //Log.e("DIOCANE", "INIZIO PAUSA 10 s")
  139.             Thread.sleep(1000)
  140.         }
  141.         Log.e("DIOCANE", ""+ tempTakList!!.length())
  142.         takList = ArrayList()
  143.         for(i in tempTakList!!.length()-1 downTo 0 step 1 ){
  144.             var jsonObj = tempTakList!!.getJSONObject(i)
  145.             //String name, double latitude, double longitude, double altitude, String desc, String cat, int duration, Node node
  146.             takList?.add(Tak(jsonObj.getString("name"),jsonObj.getString("latitude").toDouble(),
  147.                     jsonObj.getString("longitude").toDouble(),0.0,
  148.                     "","",0,null))
  149.             //Log.e("EAJASDIADJAI ", "gg  "+takList?.get(0)?.name)
  150.  
  151.         }
  152.  
  153.         //takList?.forEachIndexed { index, i -> Log.e("EAJASDIADJAI ","index $index " +"Name" +takList!![index].name +" Lat "+takList!![index].latitude+ "long" + takList!![index].longitude ) }
  154.         var size:Int = takList?.size!!
  155.  
  156.         completableFutureHashMap = HashMap()
  157.         completableFutureArray = Array<CompletableFuture<ViewRenderable>>(size, {
  158.                         i ->
  159.             var locationSource = takList!!.get(i)
  160.             val completableFuture = ViewRenderable.builder().setView(this, R.layout.example_layout).build()
  161.             completableFutureHashMap!!.put(locationSource.name, completableFuture)
  162.             completableFuture
  163.         }
  164.         )
  165.  
  166.         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) {
  167.             //MANCANO I PERMESSI!!!
  168.         } else {
  169.             val tracker = object : LocationTracker(this.applicationContext) {
  170.                 override fun onTimeout() {}
  171.                 override fun onLocationFound(location: Location) {
  172.                     lastLoc = location
  173.                     findViewById<TextView>(R.id.currentPos).text = location.latitude.toString() + " " + location.longitude + "\nACC: " + location.accuracy+"Tak:"+ takList?.size
  174.  
  175.                 }
  176.             }
  177.             tracker.startListening()
  178.         }
  179.  
  180.         swipe = Swipe()
  181.         swipe!!.setListener(object : SwipeListener {
  182.             override fun onSwipedUp(event: MotionEvent?): Boolean {
  183.                 //if(lastLoc!=null){
  184.                 val intent = Intent(this@LocationActivity, TakInputActivity::class.java)
  185.                 intent.putExtra("Latitude", lastLoc!!.latitude)
  186.                 intent.putExtra("Longitude", lastLoc!!.longitude)
  187.                 intent.putExtra("Altitude", lastLoc!!.altitude)
  188.                 startActivityForResult(intent, 0)
  189.                 //}else{
  190. //                    Toast.makeText(this@LocationActivity, "Segnale GPS troppo debole per inserire tak!", Toast.LENGTH_SHORT).show()
  191. //                }
  192.                 return true
  193.             }
  194.  
  195.             override fun onSwipedDown(event: MotionEvent?): Boolean {
  196.                 return false
  197.             }
  198.  
  199.             override fun onSwipingUp(event: MotionEvent?) {}
  200.             override fun onSwipedRight(event: MotionEvent?): Boolean {
  201.                 return false
  202.             }
  203.  
  204.             override fun onSwipingLeft(event: MotionEvent?) {}
  205.             override fun onSwipingRight(event: MotionEvent?) {}
  206.             override fun onSwipingDown(event: MotionEvent?) {}
  207.             override fun onSwipedLeft(event: MotionEvent?): Boolean {
  208.                 return false
  209.             }
  210.  
  211.         })
  212.  
  213.  
  214.         arSceneView = findViewById(R.id.ar_scene_view)
  215.         // Build a renderable from a 2D View.
  216.         val exampleLayout = ViewRenderable.builder()
  217.                 .setView(this, R.layout.example_layout)
  218.                 .build()
  219.  
  220.         // When you build a Renderable, Sceneform loads its resources in the background while returning
  221.         // a CompletableFuture. Call thenAccept(), handle(), or check isDone() before calling get().
  222.         val andy = ModelRenderable.builder()
  223.                 .setSource(this, R.raw.andy)
  224.                 .build()
  225.  
  226.  
  227.         CompletableFuture.allOf(
  228.                 *completableFutureArray!!)
  229.                 .handle<Any> CompletableFuture@{ notUsed, throwable ->
  230.                     // When you build a Renderable, Sceneform loads its resources in the background while
  231.                     // returning a CompletableFuture. Call handle(), thenAccept(), or check isDone()
  232.                     // before calling get().
  233.  
  234.                     if (throwable != null) {
  235.                         DemoUtils.displayError(this, "Unable to load renderables", throwable)
  236.                         return@CompletableFuture null
  237.                     }
  238.                     hasFinishedLoading = true;
  239.                     null
  240.                 }
  241.  
  242.         // Set an update listener on the Scene that will hide the loading message once a Plane is
  243.         // detected.
  244.  
  245.         arSceneView!!
  246.                 .scene
  247.                 .setOnUpdateListener { frameTime ->
  248.                     if (!hasFinishedLoading) {
  249.                         return@setOnUpdateListener
  250.                     }
  251.  
  252.                     if (locationScene == null) {
  253.  
  254.                         locationScene = LocationScene(this, this, arSceneView!!)
  255.  
  256. //                        val layoutLocationMarker = Tak("Bar da Chao", 39.4841303, -0.3657801, 18.0,
  257. //                                "Descrizione", Categories.eating.bar.toString(), 0, exampleView)
  258. //
  259. //                        // An example "onRender" event, called every frame
  260. //                        // Updates the layout with the markers distance
  261. //                        layoutLocationMarker.setRenderEvent(object : LocationNodeRender {
  262. //                            override fun render(node: LocationNode) {
  263. //                                val eView = exampleLayoutRenderable!!.view
  264. //                                eView.findViewById<TextView>(R.id.takName).setText(layoutLocationMarker.name)
  265. //                                eView.findViewById<TextView>(R.id.takPos).setText(node.getDistance().toString() + "m")
  266. //                            }
  267. //                        })
  268. //                        // Adding the marker
  269. //                        locationScene!!.mLocationMarkers.add(layoutLocationMarker)
  270.  
  271.                         for(tak in takList!!){
  272.                                         //String name, double latitude, double longitude, double altitude, String desc, String cat, int duration, Node node
  273.                                     var marker = Tak(tak.name,tak.latitude,tak.longitude,tak.altitude,tak.desc,"PERMA",0,Node())
  274.                                     var completableFuture = completableFutureHashMap!!.get(tak.name)
  275.                                     Log.w("DIOCANE", ""+tak.name)
  276.                                     try {
  277.                                         var viewRenderable = completableFuture!!.get()
  278.                                         marker.node.setRenderable(viewRenderable)
  279.  
  280.                                         //Toast.makeText(this@LocationActivity, tak.name +" - distance "+marker.anchorNode.getDistance() + " meters", Toast.LENGTH_LONG).show()
  281.  
  282.                                         marker.node.setOnTapListener { v, event -> Toast.makeText(this@LocationActivity, tak.name + " - distance " + marker.anchorNode.distance + " meters", Toast.LENGTH_LONG).show() }
  283.                                         marker.setOnlyRenderWhenWithin(1000)
  284.                                         val nameTextView = viewRenderable.view.findViewById<TextView>(R.id.takName)
  285.                                         nameTextView.setText(tak.name)
  286.  
  287.                                         marker.setRenderEvent { n ->
  288.                                             val distanceTextView = viewRenderable.view.findViewById<TextView>(R.id.takPos)
  289.                                             distanceTextView.setText(""+n.distance + " Meters")
  290.                                         }
  291.                                         locationScene!!.mLocationMarkers.add(marker);
  292.  
  293.  
  294.                                     }
  295.                                     catch (ex: Exception) {
  296.                                         DemoUtils.displayError(this, "Unable to load renderables", ex);
  297.                                     }
  298.                         }
  299.  
  300.  
  301.                     }
  302.                     /*|||||||||||||||||||||||*/
  303.                     /*    UPDATE FUNCTION    */
  304.  
  305.  
  306.                     /*|||||||||||||||||||||||*/
  307.                     val frame = arSceneView!!.arFrame
  308.                     if (frame == null) {
  309.                         return@setOnUpdateListener
  310.                     }
  311.  
  312.                     if (frame!!.camera.trackingState != TrackingState.TRACKING) {
  313.                         return@setOnUpdateListener
  314.                     }
  315.  
  316.                     if (locationScene != null) {
  317.                         locationScene!!.processFrame(frame)
  318.                     }
  319.  
  320.                     if (loadingMessageSnackbar != null) {
  321.                         for (plane in frame.getUpdatedTrackables(Plane::class.java)) {
  322.                             if (plane.trackingState == TrackingState.TRACKING) {
  323.                                 hideLoadingMessage()
  324.                             }
  325.                         }
  326.                     }
  327.                 }
  328.         ARLocationPermissionHelper.requestPermission(this)
  329.     }
  330.  
  331.     fun placeTak(newTak: Tak) {
  332.         newTak.node = exampleView
  333.         var t = doAsync {
  334.             var r = khttp.post("http://ar-demo.hicnet.it/api/locations/new",
  335.                     data = mapOf("name" to newTak.name, "latitude" to newTak.latitude,
  336.                             "longitude" to newTak.longitude, "altitude" to newTak.altitude,
  337.                             "duration" to newTak.duration))
  338.         }
  339.  
  340.         newTak.setRenderEvent(object : LocationNodeRender {
  341.             override fun render(node: LocationNode) {
  342.                 val eView = exampleLayoutRenderable!!.view
  343.                 eView.findViewById<TextView>(R.id.takName).setText(newTak.name)
  344.                 if (newTak.type == Tak.types.TEMP) {
  345.                     eView.findViewById<ImageView>(R.id.takIcon).setImageResource(R.drawable.app_icon)
  346.                 }
  347.                 eView.findViewById<TextView>(R.id.takPos).setText(newTak.latitude.toString() + "," + newTak.longitude)
  348.             }
  349.         })
  350.         locationScene!!.mLocationMarkers.add(newTak)
  351.         Toast.makeText(this, "Tak creato con successo!", Toast.LENGTH_SHORT).show()
  352.     }
  353.  
  354.     //LISTENER SWIPE E GESTURE
  355.     override fun dispatchTouchEvent(event: MotionEvent): Boolean {
  356.         swipe!!.dispatchTouchEvent(event)
  357.         return super.dispatchTouchEvent(event)
  358.     }
  359.  
  360.     override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
  361.         if (requestCode == 0) {
  362.             if (resultCode == Activity.RESULT_OK) {
  363.                 var result = data!!.getSerializableExtra("NewTak") as Tak
  364.                 placeTak(result)
  365.             }
  366.         }
  367.     }
  368.  
  369.     //FUNZIONI PREDEFINITE
  370.     override fun onResume() {
  371.         super.onResume()
  372.  
  373.         if (locationScene != null) {
  374.             locationScene!!.resume()
  375.         }
  376.  
  377.         if (arSceneView!!.session == null) {
  378.             // If the session wasn't created yet, don't resume rendering.
  379.             // This can happen if ARCore needs to be updated or permissions are not granted yet.
  380.             try {
  381.                 val session = DemoUtils.createArSession(this, installRequested)
  382.                 if (session == null) {
  383.                     installRequested = ARLocationPermissionHelper.hasPermission(this)
  384.                     return
  385.                 } else {
  386.                     arSceneView!!.setupSession(session)
  387.                 }
  388.             } catch (e: UnavailableException) {
  389.                 DemoUtils.handleSessionException(this, e)
  390.             }
  391.  
  392.         }
  393.  
  394.         try {
  395.             arSceneView!!.resume()
  396.         } catch (ex: CameraNotAvailableException) {
  397.             DemoUtils.displayError(this, "Unable to get camera", ex)
  398.             finish()
  399.             return
  400.         }
  401.  
  402.         if (arSceneView!!.session != null) {
  403.             showLoadingMessage()
  404.         }
  405.     }
  406.  
  407.     public override fun onPause() {
  408.         super.onPause()
  409.  
  410.         if (locationScene != null) {
  411.             locationScene!!.pause()
  412.         }
  413.  
  414.         arSceneView!!.pause()
  415.     }
  416.  
  417.     public override fun onDestroy() {
  418.         super.onDestroy()
  419.         arSceneView!!.destroy()
  420.     }
  421.  
  422.     override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, results: IntArray) {
  423.         if (!ARLocationPermissionHelper.hasPermission(this)) {
  424.             if (!ARLocationPermissionHelper.shouldShowRequestPermissionRationale(this)) {
  425.                 // Permission denied with checking "Do not ask again".
  426.                 ARLocationPermissionHelper.launchPermissionSettings(this)
  427.             } else {
  428.                 Toast.makeText(
  429.                         this, "Camera permission is needed to run this application", Toast.LENGTH_LONG)
  430.                         .show()
  431.             }
  432.             finish()
  433.         }
  434.     }
  435.  
  436.     override fun onWindowFocusChanged(hasFocus: Boolean) {
  437.         super.onWindowFocusChanged(hasFocus)
  438.         if (hasFocus) {
  439.             // Standard Android full-screen functionality.
  440.             window
  441.                     .decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
  442.                     or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
  443.                     or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
  444.                     or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
  445.                     or View.SYSTEM_UI_FLAG_FULLSCREEN
  446.                     or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
  447.             window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
  448.         }
  449.     }
  450.  
  451.     private fun showLoadingMessage() {
  452.         if (loadingMessageSnackbar != null && loadingMessageSnackbar!!.isShownOrQueued) {
  453.             return
  454.         }
  455.  
  456.         loadingMessageSnackbar = Snackbar.make(
  457.                 this@LocationActivity.findViewById<View>(android.R.id.content),
  458.                 "Searching for planes...",
  459.                 Snackbar.LENGTH_INDEFINITE)
  460.         loadingMessageSnackbar!!.view.setBackgroundColor(-0x40cdcdce)
  461.         loadingMessageSnackbar!!.show()
  462.     }
  463.  
  464.     private fun hideLoadingMessage() {
  465.         if (loadingMessageSnackbar == null) {
  466.             return
  467.         }
  468.  
  469.         loadingMessageSnackbar!!.dismiss()
  470.         loadingMessageSnackbar = null
  471.     }
  472.  
  473. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement