Vuforia官網(wǎng)
XAMPP官網(wǎng)
SharpZipLib
截止目前蜻韭,Vuforia SDK版本為8.1.7肖方,已內置與Unity引擎內。
? ?經常會遇到項目需要動態(tài)的增刪改識別圖舷胜,使用云識別上成本又比較高烹骨,在識別圖體量還不是特別多的情況沮焕,利用動態(tài)的加載Dataset可以很好的實現(xiàn)識別圖的熱更新拉宗。
1.下載數(shù)據(jù)包,部署于本地服務器
??本次示例通過壓縮包形式魁巩,在下載數(shù)據(jù)包是選擇下圖選項谷遂,得到壓縮格式的數(shù)據(jù)包卖鲤,直接將壓縮包部署本地或服務器,省去了下載unitypackge形式還得導入引擎內取出數(shù)據(jù)包的過程集晚。
??這里應用了集成服務器環(huán)境XAMPP蒋院,一鍵式安裝条摸,開箱即用钉蒲,局域網(wǎng)直接訪問顷啼,比lamp server好用不要太多钙蒙。安裝完畢后開啟Apache服務间驮,并等待啟動成功竞帽,隨后可自行訪問本機的內網(wǎng)IP進行測試,正常情況下你會看到這個XAMPP的默認頁面疙渣。
??進入XAMPP的安裝目錄進入htdocs文件夾內的dashboard妄荔,將數(shù)據(jù)包放入啦租。并在瀏覽器內輸入路徑 內網(wǎng)ip/dashboard/數(shù)據(jù)包名.zip 如http://192.168.0.108/dashboard/Test.zip 確認數(shù)據(jù)包URL訪問正常篷角。這里需要注意的是Android平臺9.0以上的系統(tǒng)内地,也就是Andorid P會報出Cleartext HTTP traffic to xxx not permitted。會出現(xiàn)無法請求HTTP的資源非凌,HTTPS請求則不會受影響荆针。這里比較簡單的解決辦法是在Player Settings內設置Target API level版本在API Level28以下,比如Level27 Android 8.1航背。
2.引用第三方解壓庫SharpZipLib
??在Github內選擇releases內下載最新版本箕肃,通過壓縮文件打開找到其Dll文件今魔,選擇并導入合適.NET版本的到Unity內,使用時直接引入命名空間ICSharpCode.SharpZipLib.Zip吟宦,并封裝對應的解壓到指定目錄的方法殃姓。
3.下載數(shù)據(jù)包蜗侈,進行解壓并加載
??填入數(shù)據(jù)包的URL地址進行下載宛篇,下載完成后解壓到沙盒路徑內叫倍,通過激活數(shù)據(jù)包來完成識別圖的動態(tài)加載吆倦。代碼如下
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO;
public class FileDecompression {
/// <summary>
/// 解壓功能(下載后直接解壓壓縮文件到指定目錄)
/// </summary>
/// <param name="path">解壓目標路徑</param>
/// <param name="ZipByte">原始數(shù)據(jù)</param>
/// <param name="password">解壓密碼</param>
/// <returns></returns>
public static string SaveZip(string path,byte[] ZipByte,string password = null) {
string result = null;
FileStream fs = null;
ZipInputStream zipStream = null;
ZipEntry ent = null;
string fileName;
if(!Directory.Exists(path)) {
Directory.CreateDirectory(path);
}
try {
//直接使用 將byte轉換為Stream坐求,省去先保存到本地在解壓的過程
Stream stream = new MemoryStream(ZipByte);
zipStream = new ZipInputStream(stream);
if(!string.IsNullOrEmpty(password)) {
zipStream.Password = password;
}
while((ent = zipStream.GetNextEntry()) != null) {
if(!string.IsNullOrEmpty(ent.Name)) {
fileName = Path.Combine(path,ent.Name);
#region Android
fileName = fileName.Replace('\\','/');
if(fileName.EndsWith("/")) {
Directory.CreateDirectory(fileName);
continue;
}
#endregion
fs = File.Create(fileName);
int size = 2048;
byte[] data = new byte[size];
while(true) {
size = zipStream.Read(data,0,data.Length);
if(size > 0) {
//fs.Write(data, 0, data.Length);
fs.Write(data,0,size);//解決讀取不完整情況
}
else
break;
}
}
}
}
catch(Exception e) {
result = e.Message;
}
finally {
if(fs != null) {
fs.Close();
fs.Dispose();
}
if(zipStream != null) {
zipStream.Close();
zipStream.Dispose();
}
if(ent != null) {
ent = null;
}
GC.Collect();
GC.Collect(1);
}
return result;
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class DownloadUtlitile {
public static IEnumerator DownloadDataset(string url,Action<byte[]> succeedAction,Action<string> failedAction) {
UnityWebRequest unityWebRequest = UnityWebRequest.Get(url);
yield return unityWebRequest.SendWebRequest();
if(unityWebRequest.isDone && string.IsNullOrEmpty(unityWebRequest.error)) {
succeedAction.Invoke(unityWebRequest.downloadHandler.data);
}
else {
failedAction.Invoke(unityWebRequest.error);
}
}
}
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using Vuforia;
public class LoadDataset:MonoBehaviour {
public string url;
public Material material;
// Start is called before the first frame update
void Start() {
VuforiaARController.Instance.RegisterVuforiaStartedCallback(()=> {
LoadDataSetForUrl(url);
});
}
private void LoadDataSetForUrl(string url) {
int startIndex = url.LastIndexOf("/") + 1;
int conut = url.LastIndexOf(".") - startIndex;
string zipName = url.Substring(startIndex,conut);
string filePath = string.Format("{0}/{1}/{2}",Application.persistentDataPath,"dataset",zipName);
string xmlPath = string.Format("{0}/{1}.xml",filePath,zipName);
print(filePath);
if(Directory.Exists(filePath)) {
LoadDataSet(xmlPath);
}
else {
StartCoroutine(DownloadUtlitile.DownloadDataset(url,a => {
print("下載成功");
if(string.IsNullOrEmpty(FileDecompression.SaveZip(filePath,a))) {
print("解壓成功");
LoadDataSet(xmlPath);
}
else {
print("解壓失敗");
}
},a => {
print("下載異常:" + a);
}));
}
}
private void LoadDataSet(string path) {
ObjectTracker tracker = TrackerManager.Instance.GetTracker<ObjectTracker>();
DataSet dataSet = tracker.CreateDataSet();
if(dataSet.Load(path,VuforiaUnity.StorageType.STORAGE_ABSOLUTE)) {
tracker.Stop();
if(!tracker.ActivateDataSet(dataSet)) {
Debug.Log("<color=yellow>Failed to Activate DataSet: " + path + "</color>");
}
if(!tracker.Start()) {
Debug.Log("<color=yellow>Tracker Failed to Start.</color>");
}
IEnumerable<TrackableBehaviour> trackableBehaviours = TrackerManager.Instance.GetStateManager().GetTrackableBehaviours();
foreach(TrackableBehaviour trackableBehaviour in trackableBehaviours) {
trackableBehaviour.gameObject.name = trackableBehaviour.TrackableName;
trackableBehaviour.gameObject.AddComponent<DefaultTrackableEventHandler>();
trackableBehaviour.gameObject.AddComponent<TurnOffBehaviour>();
GameObject gameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
gameObject.GetComponent<MeshRenderer>().material = material;
gameObject.transform.parent = trackableBehaviour.gameObject.transform;
gameObject.transform.localPosition = Vector3.zero;
gameObject.transform.localRotation = Quaternion.identity;
gameObject.transform.localScale = Vector3.one * 0.5f;
}
}
else {
Debug.LogError("<color=yellow>Failed to load dataset: '" + path + "'</color>");
}
}
}