Exemple #1
0
        public static async Task DownloadAndExecute(this ChakraHost host, string url)
        {
            var script = await CoreTools.DownloadStringAsync(url);

            host.RunScript(script);
        }
Exemple #2
0
        private IEnumerator GenerateAvatarFunc(byte[] selectedImageBytes, PipelineType pipelineType, AsyncRequest <AvatarData> request)
        {
            UpdateAvatarState(WebglAvatarState.UPLOADING, pipelineType);

            var defaultResourcesRequest = avatarProvider.ResourceManager.GetResourcesAsync(AvatarResourcesSubset.DEFAULT, pipelineType);

            yield return(Await(defaultResourcesRequest, pipelineType));

            // Generate all haircuts and default blendshapes to play animations
            var allResourcesRequest = avatarProvider.ResourceManager.GetResourcesAsync(AvatarResourcesSubset.ALL, pipelineType);

            yield return(Await(allResourcesRequest, pipelineType));

            if (defaultResourcesRequest.IsError || allResourcesRequest.IsError)
            {
                string msg = "Unable to get resources list";
                Debug.LogError(msg);
                UpdateAvatarState(WebglAvatarState.FAILED, pipelineType);
                request.SetError(msg);
                yield break;
            }
            AvatarResources resources = allResourcesRequest.Result;

            resources.blendshapes = defaultResourcesRequest.Result.blendshapes;

            var createAvatar = connection.CreateAvatarWithPhotoAsync("test_avatar", "test_description", selectedImageBytes, false, pipelineType, resources);

            yield return(Await(createAvatar, pipelineType));

            if (createAvatar.IsError)
            {
                Debug.LogError(createAvatar.ErrorMessage);
                UpdateAvatarState(WebglAvatarState.FAILED, pipelineType);
                request.SetError(createAvatar.ErrorMessage);
                yield break;
            }

            var avatar    = createAvatar.Result;
            var savePhoto = CoreTools.SaveAvatarFileAsync(selectedImageBytes, avatar.code, AvatarFile.PHOTO);

            yield return(savePhoto);

            var savePipeline = CoreTools.SaveAvatarFileAsync(Encoding.ASCII.GetBytes(pipelineType.GetPipelineTypeName()), avatar.code, AvatarFile.PIPELINE_INFO);

            yield return(savePipeline);

            if (savePhoto.IsError)
            {
                Debug.LogError(savePhoto.ErrorMessage);
                UpdateAvatarState(WebglAvatarState.FAILED, pipelineType);
                request.SetError(savePhoto.ErrorMessage);
                yield break;
            }

            UpdateAvatarState(WebglAvatarState.CALCULATING_IN_CLOUD, pipelineType);

            var awaitCalculations = connection.AwaitAvatarCalculationsAsync(avatar);

            yield return(Await(awaitCalculations, pipelineType));

            if (awaitCalculations.IsError)
            {
                Debug.LogError(awaitCalculations.ErrorMessage);
                UpdateAvatarState(WebglAvatarState.FAILED, pipelineType);
                request.SetError(awaitCalculations.ErrorMessage);
                yield break;
            }

            AvatarData avatarData = awaitCalculations.Result;

            UpdateAvatarState(WebglAvatarState.DOWNLOADING, pipelineType);
            var downloadRequest = DownloadAvatarAsync(avatarData, pipelineType);

            yield return(downloadRequest);

            if (downloadRequest.IsError)
            {
                Debug.LogError(downloadRequest.ErrorMessage);
                UpdateAvatarState(WebglAvatarState.FAILED, pipelineType);
                request.SetError(downloadRequest.ErrorMessage);
                yield break;
            }

            UpdateAvatarState(WebglAvatarState.FINISHED, pipelineType);
            request.Result = avatarData;
            request.IsDone = true;
        }
        /// <summary>
        /// GenerateAndSaveAvatarAsync implementation.
        /// </summary>
        private static IEnumerator GenerateAndSaveAvatarFunc(
            Connection connection,
            string name,
            string description,
            byte[] photoBytes,
            bool withHaircutPointClouds,
            bool withBlendshapes,
            bool forcePowerOfTwoTexture,
            AsyncRequest <AvatarData> request
            )
        {
            // uploading photo and registering new avatar on the server
            var createAvatar = connection.CreateAvatarWithPhotoAsync(name, description, photoBytes, forcePowerOfTwoTexture);

            // Wait until async request is completed (without blocking the main thread).
            // Instead of using AwaitSubrequest we could just use `yield return createAvatar;`
            // AwaitSubrequest is a helper function that allows to track progress on composite
            // requests automatically. It also provides info for the caller about current subrequest
            // (and it's progress) and propagetes error from subrequest to the parent request.
            // finalProgress is a value between 0 and 1, a desired progress of parent request when given
            // subrequest is completed.
            yield return(request.AwaitSubrequest(createAvatar, finalProgress: 0.19f));

            // must check whether request was successful before proceeding
            if (request.IsError)
            {
                yield break;
            }

            // Result field contains, well, result of the request. In this case it's an AvatarData object.
            AvatarData avatar = createAvatar.Result;

            // save photo for later use
            var savePhoto = CoreTools.SaveAvatarFileAsync(photoBytes, avatar.code, AvatarFile.PHOTO);

            yield return(request.AwaitSubrequest(savePhoto, finalProgress: 0.2f));

            // again, must check for the error, there's no point in proceeding otherwise
            if (request.IsError)
            {
                yield break;
            }

            // Server starts calculating 3D shape and texture after photo has been uploaded.
            // Now we must wait until calculations finish.
            var awaitCalculations = connection.AwaitAvatarCalculationsAsync(avatar);

            yield return(request.AwaitSubrequest(awaitCalculations, finalProgress: 0.95f));

            if (request.IsError)
            {
                yield break;
            }

            // calculations finished, update avatar info from the latest result
            avatar = awaitCalculations.Result;

            // download, save and unzip all files
            var downloadAndSave = DownloadAndSaveAvatarModelAsync(connection, avatar, withHaircutPointClouds, withBlendshapes);

            yield return(request.AwaitSubrequest(downloadAndSave, finalProgress: 1));

            if (request.IsError)
            {
                yield break;
            }

            // At this point we have all avatar files stored in the filesystem ready for being loaded and displayed.
            // Our job is considered done here.
            request.Result = avatar;
            request.IsDone = true;
        }
Exemple #4
0
        public static async Task ReadAndExecute(this ChakraHost host, string filename, string folder)
        {
            var script = await CoreTools.GetPackagedFileContentAsync(folder, filename);

            host.RunScript(script);
        }
Exemple #5
0
        public void ProcessTask(Options commandLineOptions)
        {
            String        inputFile  = commandLineOptions.Items[0];
            var           splitTools = new CoreTools();
            List <String> splitPages;

            switch (commandLineOptions.allPages)
            {
            case (true):
                // Splitting out every single page,
                // so there has to be any entry for
                // every page in the List object
                Dictionary <String, String> pdfInfo = splitTools.RetrieveBasicProperties(inputFile);
                int pageCount = Convert.ToInt32(pdfInfo["Page Count"]);
                splitPages = new List <string>();
                for (int loop = 2; loop <= pageCount; loop++)
                {
                    splitPages.Add(loop.ToString());
                }
                break;

            default:
                splitPages = commandLineOptions.SplitPages.Distinct().ToList <String>();
                splitPages.Sort();
                break;
            }
            String outputFilePrefix;

            if (!String.IsNullOrWhiteSpace(commandLineOptions.OutputFilePrefix))
            {
                outputFilePrefix = commandLineOptions.OutputFilePrefix;
            }
            else
            {
                if (!String.IsNullOrEmpty(Path.GetDirectoryName(commandLineOptions.Items[0])))
                {
                    outputFilePrefix = Path.Combine(Path.GetDirectoryName(commandLineOptions.Items[0]), Path.GetFileNameWithoutExtension(commandLineOptions.Items[0]));
                }
                else
                {
                    outputFilePrefix = Path.GetFileNameWithoutExtension(commandLineOptions.Items[0]);
                }
            }
            outputFilePrefix += "{0:" + new String('0', splitPages.Count.ToString().Length) + "}.PDF";
            var splitStartPages = new SortedList <int, String>();

            for (int loop = 0; loop < splitPages.Count; loop++)
            {
                splitStartPages.Add(Convert.ToInt32(splitPages[loop]), String.Format(outputFilePrefix, loop + 2));
            }
            if (!splitStartPages.ContainsKey(1))
            {
                splitStartPages.Add(1, String.Format(outputFilePrefix, 1));                                  // Add page 1 if not specified by user (it usually isn't)
            }
            try
            {
                splitTools.SplitPDF(inputFile, splitStartPages);
            }
            catch (ArgumentOutOfRangeException outOfRangeException)
            {
                // Page 0 or page number greater than # of pages in PDF specified
                String consoleMessage = outOfRangeException.Message.Remove(outOfRangeException.Message.LastIndexOf("Parameter name:", StringComparison.CurrentCultureIgnoreCase));
                System.Console.Error.WriteLine(Environment.NewLine + consoleMessage);
            }
            catch (ArgumentException argException)
            {
                // Output file prefix (-p) contains illegal characters.
                if (argException.Message.Contains("Illegal characters in path"))
                {
                    System.Console.Error.WriteLine(Environment.NewLine + argException.Message);
                }
            }
            catch (UnauthorizedAccessException)
            {
                System.Console.Error.WriteLine(Environment.NewLine + "Access denied.");
            }
            catch (System.IO.FileNotFoundException)
            {
                System.Console.Error.WriteLine(Environment.NewLine + "File not found.");
            }
            catch (System.IO.DirectoryNotFoundException)
            {
                System.Console.Error.WriteLine(Environment.NewLine + "Directory not found.");
            }
            catch (IOException ioException)
            {
                // PDF file is not valid, or was not found
                if (ioException.Message.Contains("PDF"))
                {
                    System.Console.Error.WriteLine(Environment.NewLine + "Input file is not a valid PDF.");
                }
                else if (ioException.Message.Contains("not found as file or resource"))
                {
                    System.Console.Error.WriteLine(Environment.NewLine + ioException.Message);
                }
                else
                {
                    throw;
                }
            }
        }
        /// <summary>
        /// DownloadAndSaveAvatarModelAsync implementation.
        /// </summary>
        private static IEnumerator DownloadAndSaveAvatarModel(
            Connection connection,
            AvatarData avatar,
            bool withHaircutPointClouds,
            bool withBlendshapes,
            AsyncRequest <AvatarData> request
            )
        {
            // By initializing multiple requests at the same time (without yield between them) we're
            // starting them in parallel. In this particular case we're downloading multiple files at the same time,
            // which is usually a bit faster than sequential download.
            var meshZip        = connection.DownloadMeshZipAsync(avatar);
            var textureRequest = connection.DownloadTextureBytesAsync(avatar);

            var download = new List <AsyncRequest> {
                meshZip, textureRequest
            };
            AsyncWebRequest <byte[]> allHaircutPointCloudsZip = null, blendshapesZip = null;

                        #if BLENDSHAPES_IN_PLY_OR_FBX
            // just a sample of how to get blendshapes in a different format

            AsyncWebRequest <byte[]> blendshapesZipFbx = null, blendshapesZipPly = null;
                        #endif

            if (withHaircutPointClouds)
            {
                allHaircutPointCloudsZip = connection.DownloadAllHaircutPointCloudsZipAsync(avatar);
                download.Add(allHaircutPointCloudsZip);
            }

            if (withBlendshapes)
            {
                blendshapesZip = connection.DownloadBlendshapesZipAsync(avatar);
                download.Add(blendshapesZip);

                                #if BLENDSHAPES_IN_PLY_OR_FBX
                // just a sample of how to get blendshapes in a different format

                blendshapesZipFbx = connection.DownloadBlendshapesZipAsync(avatar, BlendshapesFormat.FBX);
                download.Add(blendshapesZipFbx);

                blendshapesZipPly = connection.DownloadBlendshapesZipAsync(avatar, BlendshapesFormat.PLY);
                download.Add(blendshapesZipPly);
                                #endif
            }

            // continue execution when all requests finish
            yield return(request.AwaitSubrequests(0.9f, download.ToArray()));

            // return if any of the requests failed
            if (request.IsError)
            {
                yield break;
            }

            // save all the results to disk, also in parallel
            var saveMeshZip = CoreTools.SaveAvatarFileAsync(meshZip.Result, avatar.code, AvatarFile.MESH_ZIP);
            var saveTexture = CoreTools.SaveAvatarFileAsync(textureRequest.Result, avatar.code, AvatarFile.TEXTURE);

            var save = new List <AsyncRequest> ()
            {
                saveMeshZip, saveTexture
            };
            AsyncRequest <string> saveHaircutPointsZip = null, saveBlendshapesZip = null;
            if (allHaircutPointCloudsZip != null)
            {
                saveHaircutPointsZip = CoreTools.SaveAvatarFileAsync(allHaircutPointCloudsZip.Result, avatar.code, AvatarFile.ALL_HAIRCUT_POINTS_ZIP);
                save.Add(saveHaircutPointsZip);
            }

            if (blendshapesZip != null)
            {
                saveBlendshapesZip = CoreTools.SaveAvatarFileAsync(blendshapesZip.Result, avatar.code, AvatarFile.BLENDSHAPES_ZIP);
                save.Add(saveBlendshapesZip);
            }

                        #if BLENDSHAPES_IN_PLY_OR_FBX
            // just a sample of how to get blendshapes in a different format

            if (blendshapesZipFbx != null)
            {
                var saveBlendshapesZipFbx = CoreTools.SaveAvatarFileAsync(blendshapesZipFbx.Result, avatar.code, AvatarFile.BLENDSHAPES_FBX_ZIP);
                save.Add(saveBlendshapesZipFbx);
            }

            if (blendshapesZipPly != null)
            {
                var saveBlendshapesZipPly = CoreTools.SaveAvatarFileAsync(blendshapesZipPly.Result, avatar.code, AvatarFile.BLENDSHAPES_PLY_ZIP);
                save.Add(saveBlendshapesZipPly);
            }
                        #endif

            yield return(request.AwaitSubrequests(0.95f, save.ToArray()));

            if (request.IsError)
            {
                yield break;
            }

            var unzipMesh = CoreTools.UnzipFileAsync(saveMeshZip.Result);

            var unzip = new List <AsyncRequest> ()
            {
                unzipMesh
            };
            AsyncRequest <string> unzipHaircutPoints = null, unzipBlendshapes = null;
            if (saveHaircutPointsZip != null)
            {
                unzipHaircutPoints = CoreTools.UnzipFileAsync(saveHaircutPointsZip.Result);
                unzip.Add(unzipHaircutPoints);
            }
            if (saveBlendshapesZip != null)
            {
                unzipBlendshapes = UnzipBlendshapes(saveBlendshapesZip.Result, avatar.code);
                unzip.Add(unzipBlendshapes);
            }

            yield return(request.AwaitSubrequests(0.99f, unzip.ToArray()));

            if (request.IsError)
            {
                yield break;
            }

            // delete all .zip files we don't need anymore
            try {
                foreach (var fileToDelete in new AvatarFile[] { AvatarFile.MESH_ZIP, AvatarFile.ALL_HAIRCUT_POINTS_ZIP, AvatarFile.BLENDSHAPES_ZIP })
                {
                    CoreTools.DeleteAvatarFile(avatar.code, fileToDelete);
                }
            } catch (Exception ex) {
                // error here is not critical, we can just ignore it
                Debug.LogException(ex);
            }

            request.Result = avatar;
            request.IsDone = true;
        }
        /// <summary>
        /// Process blendshapes slightly differently compared to other zips (for compatibility reasons).
        /// Blendshapes are unzipped not just in avatar directory, but in their own personal folder.
        /// </summary>
        /// <param name="blendshapesZip">Full path to blendshapes zip archive.</param>
        /// <param name="avatarCode">Avatar identifier to determine the correct unzip location.</param>
        public AsyncRequest <string> UnzipBlendshapesAsync(string blendshapesZip, string avatarCode)
        {
            var blendshapesDir = AvatarSdkMgr.Storage().GetAvatarSubdirectory(avatarCode, AvatarSubdirectory.BLENDSHAPES);

            return(CoreTools.UnzipFileAsync(blendshapesZip, blendshapesDir));
        }
        /// <summary>
        /// GetHeadMeshAsync implementation
        /// </summary>
        private IEnumerator GetHeadMeshFunc(string avatarCode, bool withBlendshapes, int detailsLevel, AsyncRequest <TexturedMesh> request)
        {
            // Need to verify if this avatar supports Level Of Details
            if (detailsLevel > 0)
            {
                var avatarRequest = GetAvatarAsync(avatarCode);
                yield return(avatarRequest);

                if (avatarRequest.IsError)
                {
                    yield break;
                }
                if (string.Compare(avatarRequest.Result.pipeline, PipelineType.FACE.GetPipelineTypeName()) != 0)
                {
                    Debug.LogWarningFormat("Avatar created by {0} doesn't support Level Of Details. Will be used LOD 0.", avatarRequest.Result.pipeline);
                    detailsLevel = 0;
                }
            }

            string meshFilename    = AvatarSdkMgr.Storage().GetAvatarFilename(avatarCode, AvatarFile.MESH_PLY);
            string textureFilename = AvatarSdkMgr.Storage().GetAvatarFilename(avatarCode, AvatarFile.TEXTURE);

            //If there are no required files, will download them.
            if (!File.Exists(meshFilename) || !File.Exists(textureFilename))
            {
                var avatarRequest = connection.GetAvatarAsync(avatarCode);
                yield return(avatarRequest);

                if (avatarRequest.IsError)
                {
                    yield break;
                }

                var downloadRequest = DownloadAndSaveAvatarModelAsync(avatarRequest.Result, false, withBlendshapes);
                yield return(request.AwaitSubrequest(downloadRequest, 0.5f));

                if (request.IsError)
                {
                    yield break;
                }
            }

            //if there are no blendshapes, will download them
            var  blendshapesDir   = AvatarSdkMgr.Storage().GetAvatarSubdirectory(avatarCode, AvatarSubdirectory.BLENDSHAPES);
            bool blendshapesExist = Directory.GetFiles(blendshapesDir).Length > 0;

            if (withBlendshapes && !blendshapesExist)
            {
                var avatarRequest = connection.GetAvatarAsync(avatarCode);
                yield return(avatarRequest);

                if (avatarRequest.IsError)
                {
                    yield break;
                }

                var downloadBlendshapes = connection.DownloadBlendshapesZipAsync(avatarRequest.Result, BlendshapesFormat.BIN, detailsLevel);
                yield return(request.AwaitSubrequest(downloadBlendshapes, 0.8f));

                if (request.IsError)
                {
                    yield break;
                }

                byte[] blendshapesZipBytes = downloadBlendshapes.Result;
                if (blendshapesZipBytes != null && blendshapesZipBytes.Length > 0)
                {
                    var saveBlendshapesZip = CoreTools.SaveAvatarFileAsync(downloadBlendshapes.Result, avatarCode, AvatarFile.BLENDSHAPES_ZIP);
                    yield return(request.AwaitSubrequest(saveBlendshapesZip, 0.9f));

                    if (request.IsError)
                    {
                        yield break;
                    }

                    var unzipBlendshapes = UnzipBlendshapesAsync(saveBlendshapesZip.Result, avatarCode);
                    yield return(request.AwaitSubrequest(unzipBlendshapes, 0.95f));

                    if (request.IsError)
                    {
                        yield break;
                    }

                    CoreTools.DeleteAvatarFile(avatarCode, AvatarFile.BLENDSHAPES_ZIP);
                }
            }

            // At this point all avatar files are already saved to disk. Let's load the files to Unity.
            var loadAvatarHeadRequest = CoreTools.LoadAvatarHeadFromDiskAsync(avatarCode, withBlendshapes, detailsLevel);

            yield return(request.AwaitSubrequest(loadAvatarHeadRequest, 1.0f));

            if (request.IsError)
            {
                yield break;
            }

            request.Result = loadAvatarHeadRequest.Result;
            request.IsDone = true;
        }
Exemple #9
0
        async Task ReadAndExecute(string filename)
        {
            var script = await CoreTools.GetPackagedFileContentAsync("refs", filename);

            host.RunScript(script);
        }
 public void Init()
 {
     gameManager      = CoreTools.GetManager <GameManager>();
     changeButtonText = ChangeInput.GetComponentInChildren <Text>();
     ScoreText.text   = "";
 }
Exemple #11
0
        public void ProcessTask(Options commandLineOptions)
        {
            String inputFile = commandLineOptions.Items[0];
            var    infoTools = new CoreTools();
            Dictionary <String, String> pdfInfo = new Dictionary <String, String>();

            try
            {
                if (commandLineOptions.showAll || commandLineOptions.showInfo)
                {
                    foreach (KeyValuePair <String, String> pdfInfoPair in infoTools.RetrieveBasicProperties(inputFile))
                    {
                        pdfInfo.Add(pdfInfoPair.Key, pdfInfoPair.Value);
                    }
                    foreach (KeyValuePair <String, String> pdfInfoPair in infoTools.RetrieveInfo(inputFile))
                    {
                        pdfInfo.Add(pdfInfoPair.Key, pdfInfoPair.Value);
                    }
                }
                if (commandLineOptions.showAll || commandLineOptions.showFields)
                {
                    foreach (KeyValuePair <String, String> pdfInfoPair in infoTools.RetrieveAcroFieldsData(inputFile))
                    {
                        pdfInfo.Add(pdfInfoPair.Key, pdfInfoPair.Value);
                    }
                }
                WriteResults(commandLineOptions.csvOutput, pdfInfo);
            }
            catch (ArgumentException argException)
            {
                // Output file prefix (-p) contains illegal characters.
                if (argException.Message.Contains("Illegal characters in path"))
                {
                    System.Console.Error.WriteLine(Environment.NewLine + argException.Message);
                }
            }
            catch (UnauthorizedAccessException)
            {
                System.Console.Error.WriteLine(Environment.NewLine + "Access denied.");
            }
            catch (System.IO.FileNotFoundException)
            {
                System.Console.Error.WriteLine(Environment.NewLine + "File not found.");
            }
            catch (IOException ioException)
            {
                // PDF file is not valid, or was not found
                if (ioException.Message.Contains("PDF"))
                {
                    System.Console.Error.WriteLine(Environment.NewLine + "Input file is not a valid PDF.");
                }
                else if (ioException.Message.Contains("not found as file or resource"))
                {
                    System.Console.Error.WriteLine(Environment.NewLine + ioException.Message);
                }
                else
                {
                    throw;
                }
            }
        }
Exemple #12
0
        /// <summary>
        /// Upload photo and create avatar instance on the server. Calculations will start right away after the photo is uploaded.
        /// </summary>
        public virtual AsyncWebRequest <AvatarData> CreateAvatarWithPhotoAsync(
            string name, string description, byte[] photoBytes, bool forcePowerOfTwoTexture = false,
            PipelineType pipeline = PipelineType.FACE, AvatarResources resources = null
            )
        {
            var request = new AsyncWebRequest <AvatarData> (AvatarSdkMgr.Str(Strings.UploadingPhoto), TrackProgress.UPLOAD);

#if UNITY_2017_1_OR_NEWER
            Func <UnityWebRequest> webRequestFactory = () =>
            {
                List <IMultipartFormSection> formData = new List <IMultipartFormSection>();
                formData.Add(new MultipartFormDataSection("name", name));
                if (!string.IsNullOrEmpty(description))
                {
                    formData.Add(new MultipartFormDataSection("description", description));
                }
                formData.Add(new MultipartFormFileSection("photo", photoBytes, "photo.jpg", "application/octet-stream"));
                formData.Add(new MultipartFormDataSection("preserve_original_texture", (!forcePowerOfTwoTexture).ToString()));
                formData.Add(new MultipartFormDataSection("pipeline", pipeline.GetPipelineTypeName()));

                if (resources != null)
                {
                    formData.Add(new MultipartFormDataSection("pipeline_subtype", pipeline_subtype));
                    formData.Add(new MultipartFormDataSection("resources", CoreTools.GetAvatarCalculationParamsJson(resources)));
                }

                var webRequest = UnityWebRequest.Post(GetUrl("avatars"), formData);
                webRequest.chunkedTransfer = false;
                SetAuthHeaders(webRequest);
                return(webRequest);
            };

            Debug.LogFormat("Uploading photo...");
            AvatarSdkMgr.SpawnCoroutine(AwaitJsonWebRequest(webRequestFactory, request));
            return(request);
#else
            // Unity 5.5.0 (and probably earlier versions) have a weird bug in default multipart form data
            // implementation, which causes incorrect boundaries between data fields. To work around this bug the
            // multipart request body is constructed manually, see below.
            byte[] requestBodyData = null;
            using (var requestBody = new MultipartBody()) {
                requestBody.WriteTextField("name", name);
                requestBody.WriteTextField("description", description);
                requestBody.WriteFileField("photo", "photo.jpg", photoBytes);
                requestBody.WriteTextField("preserve_original_texture", (!forcePowerOfTwoTexture).ToString());
                requestBody.WriteTextField("pipeline", pipeline.GetPipelineTypeName());

                if (resources != null)
                {
                    requestBody.WriteTextField("pipeline_subtype", pipeline_subtype);
                    requestBody.WriteTextField("resources", CoreTools.GetAvatarCalculationParamsJson(resources));
                }

                requestBody.WriteFooter();
                requestBodyData = requestBody.GetRequestBodyData();

                Func <UnityWebRequest> webRequestFactory = () => {
                    var webRequest = UnityWebRequest.Post(GetUrl("avatars"), " ");
                    webRequest.uploadHandler = new UploadHandlerRaw(requestBodyData);
                    webRequest.SetRequestHeader(
                        "Content-Type", string.Format("multipart/form-data; boundary=\"{0}\"", requestBody.Boundary)
                        );
                    webRequest.chunkedTransfer = false;
                    SetAuthHeaders(webRequest);
                    return(webRequest);
                };

                Debug.LogFormat("Uploading photo...");
                AvatarSdkMgr.SpawnCoroutine(AwaitJsonWebRequest(webRequestFactory, request));
                return(request);
            }
#endif
        }
Exemple #13
0
        private IEnumerator ShowAvatarByCode(string avatarCode)
        {
            // with known avatar code we can get TexturedMesh for head in order to show it further
            var avatarHeadRequest = avatarProvider.GetHeadMeshAsync(avatarCode, true);

            yield return(AwaitRoutine(avatarHeadRequest));

            TexturedMesh headTexturedMesh = avatarHeadRequest.Result;

            TexturedMesh haircutTexturedMesh = null;
            // get identities of all haircuts available for the generated avatar
            var haircutsIdRequest = avatarProvider.GetHaircutsIdAsync(avatarCode);

            yield return(AwaitRoutine(haircutsIdRequest));

            ModelInfo modelInfo = CoreTools.GetAvatarModelInfo(avatarCode);

            // select predicted haircut
            var haircuts   = haircutsIdRequest.Result.ToList();
            var haircutIdx = 0;

            if (haircuts != null && haircuts.Count > 0 && !string.IsNullOrEmpty(modelInfo.haircut_name))
            {
                haircutIdx = haircuts.FindIndex(h => h.Contains(modelInfo.haircut_name));

                if (haircutIdx >= 0)
                {
                    // load TexturedMesh for the chosen haircut
                    var haircutRequest = avatarProvider.GetHaircutMeshAsync(avatarCode, haircuts[haircutIdx]);
                    yield return(AwaitRoutine(haircutRequest));

                    haircutTexturedMesh = haircutRequest.Result;
                }
            }

            var avatarInfo = CreateHead(avatarCode, headTexturedMesh, haircutTexturedMesh, modelInfo);

            avatarInfo.code                    = avatarCode;
            avatarInfo.name                    = ReadAvatarNameByCode(avatarCode);
            avatarInfo.haircuts                = haircutsIdRequest.Result;
            avatarInfo.selectedHairstyle       = haircutIdx;
            avatarInfo.transform.position      = Vector3.zero;
            avatarInfo.transform.localRotation = Quaternion.identity;

            Selection.activeGameObject = avatarInfo.gameObject;

            SceneView sceneView = SceneView.lastActiveSceneView;

            if (sceneView == null)
            {
                Type GameViewType = System.Type.GetType("UnityEditor.GameView,UnityEditor");
                sceneView = EditorWindow.GetWindow <SceneView>(new Type[] { GameViewType });
            }

            if (sceneView != null)
            {
                Camera sceneCam = sceneView.camera;
                sceneView.pivot = Vector3.zero;
                sceneView.size  = cameraOffset;
                sceneView.LookAt(Vector3.zero, Quaternion.identity);
            }

            Tools.current = Tool.Rotate;
        }