กำหนดค่าเซสชัน ARCore เพื่อสร้างประสบการณ์ AR สำหรับแอป
เซสชันคืออะไร
กระบวนการของ AR ทั้งหมด เช่น การติดตามการเคลื่อนไหว ความเข้าใจด้านสิ่งแวดล้อม และการประมาณแสง เกิดขึ้นในเซสชัน ARCore ArSession
คือจุดแรกเข้าของ ARCore API โดยจะจัดการสถานะระบบ AR และจัดการวงจรเซสชัน ซึ่งจะช่วยให้แอปสร้าง กำหนดค่า เริ่ม หรือหยุดเซสชันได้ สิ่งสำคัญที่สุดคือ ช่วยให้แอปรับเฟรมที่อนุญาตการเข้าถึงรูปภาพกล้องและท่าทางของอุปกรณ์
เซสชันสามารถใช้เพื่อกำหนดค่าฟีเจอร์ต่อไปนี้ได้
- การประมาณแสงสว่าง
- แท็ก Anchor
- รูปภาพเสริม
- Augmented Faces
- Depth API
- ตำแหน่งทันใจ
- ARCore Geospatial API
ยืนยันว่าติดตั้ง ARCore และเป็นเวอร์ชันล่าสุดแล้ว
ก่อนสร้าง ArSession
โปรดยืนยันว่ามีการติดตั้ง ARCore และเป็นเวอร์ชันล่าสุดแล้ว
หากไม่ได้ติดตั้ง ARCore การสร้างเซสชันจะไม่สำเร็จและการติดตั้งหรืออัปเกรด ARCore ที่ตามมาต้องรีสตาร์ทแอป
/* * Check if ARCore is currently usable, i.e. whether ARCore is supported and * up to date. */ int32_t is_arcore_supported_and_up_to_date(void* env, void* context) { ArAvailability availability; ArCoreApk_checkAvailability(env, context, &availability); switch (availability) { case AR_AVAILABILITY_SUPPORTED_INSTALLED: return true; case AR_AVAILABILITY_SUPPORTED_APK_TOO_OLD: case AR_AVAILABILITY_SUPPORTED_NOT_INSTALLED: { ArInstallStatus install_status; // ArCoreApk_requestInstall is processed asynchronously. CHECK(ArCoreApk_requestInstall(env, context, true, &install_status) == AR_SUCCESS); return false; } case AR_AVAILABILITY_UNSUPPORTED_DEVICE_NOT_CAPABLE: // This device is not supported for AR. return false; case AR_AVAILABILITY_UNKNOWN_CHECKING: // ARCore is checking the availability with a remote query. // This function should be called again after waiting 200 ms // to determine the query result. handle_check_later(); return false; case AR_AVAILABILITY_UNKNOWN_ERROR: case AR_AVAILABILITY_UNKNOWN_TIMED_OUT: // There was an error checking for AR availability. // This may be due to the device being offline. // Handle the error appropriately. handle_unknown_error(); return false; default: // All enum cases have been handled. return false; } }
สร้างเซสชัน
สร้างและกำหนดค่าเซสชันใน ARCore
// Create a new ARCore session. ArSession* ar_session = NULL; CHECK(ArSession_create(env, context, &ar_session) == AR_SUCCESS); // Create a session config. ArConfig* ar_config = NULL; ArConfig_create(ar_session, &ar_config); // Do feature-specific operations here, such as enabling depth or turning on // support for Augmented Faces. // Configure the session. CHECK(ArSession_configure(ar_session, ar_config) == AR_SUCCESS);
ปิดเซสชัน
ArSession
เป็นเจ้าของหน่วยความจำฮีพดั้งเดิมในปริมาณมาก หากไม่ปิดเซสชันอย่างชัดแจ้ง หน่วยความจำในเครื่องอาจเต็มและเกิดข้อขัดข้อง เมื่อไม่จำเป็นต้องใช้เซสชัน AR อีกต่อไป ให้เรียกใช้ ArSession_destroy()
เพื่อปล่อยทรัพยากร
// Release memory used by the AR session. ArSession_destroy(session);