using UnityEngine; using UnityEngine.Networking; using System.Collections; using System.IO; using UnityEditor; using System.Linq; using Raumgleiter.BaseRGDK.JSON; using System.Collections.Generic; //using System; namespace Raumgleiter.RGDKDevLab { public class MtexDownloadFunctions : MonoBehaviour { //Singleton Pattern private static MtexDownloadFunctions _inst; public static MtexDownloadFunctions Instance { get { if (!_inst) _inst = UnityEngine.Object.FindObjectOfType(); if (!_inst) _inst = new GameObject(typeof(MtexDownloadFunctions).ToString()).AddComponent(); return _inst; } } public static bool GetHasInstance() { return _inst != null; } //------------------------------------------------------------------------------------------------------------------ //Connections //[Header("Connections")] //Resources //[Header("Resources")] //Attributes //[Header("Attributes")] //Attributes | web related public static string mtexturUrl = "https://www.mtextur.com/api/v1/"; // private string mtexturUrlStaging = "https://staging.mtextur.ch/api/v1/"; //Stats //[Header("Stats")] //protected bool IsSetUp = false; //Getter //Delegates //------------------------------------------------------------------------------------------------------------------ //awake //------------------------------------------------------------------------------------------------------------------ //start //------------------------------------------------------------------------------------------------------------------ //setup //public void SetUp() //{ // IsSetUp = true; //} //------------------------------------------------------------------------------------------------------------------ //destroy //*********************************************************************************************************************** //update //*********************************************************************************************************************** //refresh //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //*********************************************************************************************************************** //events //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //*********************************************************************************************************************** //private //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //*********************************************************************************************************************** //protected //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //*********************************************************************************************************************** //internal //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //*********************************************************************************************************************** //public //------------------------------------------------------------------------------------------------------------------ public static IEnumerator GetJsonLikeString(string someUrl, System.Action result) { using (UnityWebRequest webRequest = UnityWebRequest.Get(someUrl)) { Debug.Log(":MtexDownloadFunctions::GetJsonLikeString: getting json string from: " + someUrl); //Add Headers webRequest.SetRequestHeader("X-Api-Key", mtexApiKeys.mtexturApiKey); yield return webRequest.SendWebRequest(); if (webRequest.isNetworkError) { Debug.Log(":MtexDownloadFunctions::GetJsonLikeString: Error: " + webRequest.error); } else { Debug.Log(":MtexDownloadFunctions::GetJsonLikeString: " + webRequest.downloadHandler.text); } result(webRequest.downloadHandler.text); } } //------------------------------------------------------------------------------------------------------------------ public static IEnumerator GetTotalEntries(string someUrl, System.Action result) { using (UnityWebRequest webRequest = UnityWebRequest.Get(someUrl)) { Debug.Log(":MtexDownloadFunctions::GetTotalEntries: " + someUrl); //Add Headers webRequest.SetRequestHeader("X-Api-Key", mtexApiKeys.mtexturApiKey); yield return webRequest.SendWebRequest(); if (webRequest.isNetworkError) { Debug.Log(":MtexDownloadFunctions::GetTotalEntries: Error: " + webRequest.error); } else { Debug.Log(":MtexDownloadFunctions::GetTotalEntries: " + webRequest.downloadHandler.text); } result(webRequest.GetResponseHeaders()["Total"]); } } //------------------------------------------------------------------------------------------------------------------ public static IEnumerator DownloadTexture(string url, System.Action result) { UnityWebRequest www = UnityWebRequestTexture.GetTexture(url); yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); Debug.Log(":MtexDownloadFunctions::GetTotalEntries: no texture at: " + url); result(new Texture()); // clear last texture } else { Debug.Log(":MtexDownloadFunctions::GetTotalEntries: added" + url); result(((DownloadHandlerTexture)www.downloadHandler).texture); } } //------------------------------------------------------------------------------------------------------------------ public static string BuildUrl2(Dictionary> urlVariabels) { string materialsUrl = mtexturUrl + "materials/?"; foreach (var kvp in urlVariabels) { foreach (var item in kvp.Value) { if (item != 999999) { materialsUrl = materialsUrl + kvp.Key + "=" + item + "&"; } } } Debug.Log(materialsUrl); return materialsUrl; } //------------------------------------------------------------------------------------------------------------------ public static string BuildUrl(Dictionary urlVariabels) { string materialsUrl = mtexturUrl + "materials/?"; foreach (var kvp in urlVariabels) { if (kvp.Value != 999999) { materialsUrl = materialsUrl + kvp.Key + "=" + kvp.Value + "&"; } } Debug.Log(materialsUrl); return materialsUrl; } //------------------------------------------------------------------------------------------------------------------ public static Material CreateMaterial(Texture2D mainTexture, Texture2D normalTexture, string materialName) { { // create new material Material newMaterial = new Material(Shader.Find("Standard")); newMaterial.name = materialName; newMaterial.mainTexture = (mainTexture); // check if there is a normal texture and assign it if (normalTexture != null) { newMaterial.EnableKeyword("_NORMALMAP"); newMaterial.SetTexture("_BumpMap", normalTexture); } // get aspect ratio of main texture and apply it to material float ratio = mainTexture.width / (float)mainTexture.height; newMaterial.mainTextureScale = new Vector2(ratio, 1f); return newMaterial; } } //------------------------------------------------------------------------------------------------------------------ public static void SaveMaterial(Material newMaterial, string materialName, Texture2D mainTexture, Texture2D normTexture) { //remove invalid characters from material name var invalidChars = System.IO.Path.GetInvalidFileNameChars(); materialName = new string(materialName.Where(x => !invalidChars.Contains(x)).ToArray()); string textureName = materialName + "_tex"; string normName = materialName + "_norm"; // create new asset if there is no such if (!(Directory.Exists("Assets/Materials/" + materialName))) { Directory.CreateDirectory("Assets/Materials/" + materialName); Debug.Log("MtexDownloadFunctions::SaveMaterial: Path: Assets/Materials/" + materialName); //write bump file if there is one if (normTexture != null) { AssetDatabase.CreateAsset(normTexture, "Assets/Materials/" + materialName + "/" + normName + ".renderTexture"); Debug.Log("MtexDownloadFunctions::SaveMaterial: saved normal texture."); } else { Debug.Log("no norm tex"); } //write rest of files AssetDatabase.CreateAsset(mainTexture, "Assets/Materials/" + materialName + "/" + textureName + ".renderTexture"); AssetDatabase.CreateAsset(newMaterial, "Assets/Materials/" + materialName + "/" + textureName + ".mat"); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); Debug.Log("MtexDownloadFunctions::SaveMaterial: created material: " + materialName); } else { Debug.Log("MtexDownloadFunctions::SaveMaterial: no new material, already exists: " + materialName); } } //------------------------------------------------------------------------------------------------------------------ public static List GetTextureSizes(JSONNode json) { var textureSizes = new List(); foreach (var key in json["image"]["urls"].Keys) { textureSizes.Add(key); } return (textureSizes); } //------------------------------------------------------------------------------------------------------------------ public IEnumerator GetTypes(System.Action> result) { var jsonLikeString = ""; var Filter = "types"; yield return GetByEndpoint(Filter, value => jsonLikeString = value); var TypeClassList = MtexType.JsonTypeToClass(jsonLikeString); result(TypeClassList); } //------------------------------------------------------------------------------------------------------------------ public IEnumerator GetManufacturers(System.Action> result) { var jsonLikeString = ""; var Filter = "manufacturers"; yield return GetByEndpoint(Filter, value => jsonLikeString = value); //create list of class elements from downloaded json var ManClassList = MtexManufacturer.JsonManToClass(jsonLikeString); result(ManClassList); } //------------------------------------------------------------------------------------------------------------------ public IEnumerator GetColors(System.Action> result) { var jsonLikeString = ""; var Filter = "colors"; yield return GetByEndpoint(Filter, value => jsonLikeString = value); var ColorClassList = MtexColor.JsonTypeToClass(jsonLikeString); result(ColorClassList); } //------------------------------------------------------------------------------------------------------------------ private IEnumerator GetByEndpoint(string Filter, System.Action result) { string thisUrl = mtexturUrl + Filter + "/"; // get number of materials from request header string totalEntries = ""; yield return GetTotalEntries(thisUrl, value => totalEntries = value); Debug.Log("MtexDownloadFunctions::GetByFilter: totalEntries: " + Filter + totalEntries); // change pagination of request to total number of materials and get json string jsonLikeString = ""; yield return GetJsonLikeString(thisUrl + "?per_page=" + totalEntries, value => jsonLikeString = value); result(jsonLikeString); } //------------------------------------------------------------------------------------------------------------------ public IEnumerator GetMaterials(string materialsUrl, System.Action> result) { // get number of materials from request header // string totalEntries = ""; // yield return GetTotalEntries(materialsUrl, value => totalEntries = value); // Debug.Log("MtexDownloadFunctions::GetMaterials: totalEntries: " + totalEntries); // change pagination of request to total number of materials and get json // yield return GetJsonLikeString(materialsUrl + "per_page=" + totalEntries, value => jsonLikeString = value); string jsonLikeString = ""; yield return GetJsonLikeString(materialsUrl, value => jsonLikeString = value); Debug.Log("MtexDownloadFunctions::GetMaterials: string: /n" + jsonLikeString); // create list of class elements from downloaded json // should be part of materialsBasic class var json = JSONNode.Parse(jsonLikeString); var materialsBasic = new List(); for (int i = 0; i < (json.Count); i++) { materialsBasic.Add(new MtexMaterialBasic { id = json[i]["id"], name = json[i]["name"], }); } var MatClassList = materialsBasic; result(MatClassList); } //------------------------------------------------------------------------------------------------------------------ public IEnumerator GetMaterial(int matId, System.Action result) { //get selected material json string jsonLikeString = ""; string materialUrl = mtexturUrl + "materials/" + matId; yield return GetJsonLikeString(materialUrl, value => jsonLikeString = value); var json = JSONNode.Parse(jsonLikeString); result(json); } //------------------------------------------------------------------------------------------------------------------ public IEnumerator GetMainTexture(JSONNode json, System.Action result, string texturesize = "small") { Texture texture = new Texture(); string imageUrl = "https://www.mtextur.com" + json["image"]["urls"][texturesize]; imageUrl = imageUrl.Split('?')[0]; // remove querry yield return DownloadTexture(imageUrl, value => texture = value); result(texture); } //------------------------------------------------------------------------------------------------------------------ public IEnumerator GetBumpTexture(JSONNode json, System.Action result, string texturesize = "small") { if (CheckForTexture(json, "image_map_bump")) { Texture texture = new Texture(); string bumpUrl = "https://www.mtextur.com" + json["image_map_bump"]["urls"][texturesize]; bumpUrl = bumpUrl.Split('?')[0]; // remove querry yield return DownloadTexture(bumpUrl, value => texture = value); result(texture); } else { result(null); } } //------------------------------------------------------------------------------------------------------------------ public bool CheckForTexture(JSONNode json, string type) { string baseUrl = "https://www.mtextur.com"; string checkUrl = baseUrl + json[type]["urls"]["small"]; checkUrl = checkUrl.Split('?')[0]; if (checkUrl != baseUrl) { Debug.Log(":MtexDownload::CheckForTexture: bump Url :" + checkUrl); return true; } else { Debug.Log(":MtexDownload::CheckForTexture: no bump map"); return false; } } //------------------------------------------------------------------------------------------------------------------ public string MaterialDescription(JSONNode json, Texture texture) { string materialDescription = "manufacturer: " + json["manufacturer"]["name"] + "\n" + "id: " + json["id"] + "\n" + "name: " + json["name"] + "\n" + "type: " + json["type"]["name"] + "\n" + "type_id: " + json["type"]["id"] + "\n" + "color: " + json["color"]["name"] + "\n" + "texture width:" + texture.width + "\n" + "texture height:" + texture.height + "\n"; return materialDescription; } //------------------------------------------------------------------------------------------------------------------ public Vector2 MaterialTiling(Texture texture, float scaleFactor = 1f) { var scaleFactorVector = new Vector2(scaleFactor, scaleFactor); float ratio = texture.width / (float)texture.height; var materialTiling = Vector2.Scale(new Vector2(ratio, 1f), scaleFactorVector); return materialTiling; } //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //*********************************************************************************************************************** //public static //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //*********************************************************************************************************************** //getter, setter //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ } }