public int HandleStateTransition(string source, ref AnimatorStateTransition transition)
        {
            int        id             = controllerInfo.transitions.Count;
            JSONObject transitionJSON = new JSONObject(JSONObject.Type.OBJECT);

            controllerInfo.transitions.Add(transitionJSON);
            // transitionJSON.AddField("name", source + "->" + (transition.destinationState != null ? transition.destinationState.name : (transition.destinationStateMachine != null ? transition.destinationStateMachine.name : "exit")));
            JSONObject conditionsJSON = new JSONObject(JSONObject.Type.ARRAY);

            for (int i = 0; i < transition.conditions.Length; i++)
            {
                var        cd     = transition.conditions[i];
                JSONObject cdJSON = new JSONObject(JSONObject.Type.OBJECT);
                cdJSON.AddField("name", cd.parameter);
                cdJSON.AddField("operator", (int)cd.mode);
                if (cd.mode == AnimatorConditionMode.If || cd.mode == AnimatorConditionMode.IfNot)
                {
                    cdJSON.AddField("value", true);
                }
                else
                {
                    cdJSON.AddField("value", cd.threshold);
                }
                conditionsJSON.Add(cdJSON);
            }
            transitionJSON.AddField("conditions", conditionsJSON);

            transitionJSON.AddField("fixedDuration", transition.hasFixedDuration);
            transitionJSON.AddField("duration", transition.duration);
            transitionJSON.AddField("offset", transition.offset);
            transitionJSON.AddField("interruption", (int)transition.interruptionSource);
            transitionJSON.AddField("orderedInterruption", transition.orderedInterruption);
            transitionJSON.AddField("hasExitTime", transition.hasExitTime);
            transitionJSON.AddField("exitTime", transition.exitTime);
            if (transition.destinationState != null)
            {
                var        state     = transition.destinationState;
                JSONObject stateJSON = new JSONObject(JSONObject.Type.OBJECT);
                stateJSON.AddField("type", "State");
                stateJSON.AddField("id", HandleState(ref state));
                transitionJSON.AddField("destState", stateJSON);
            }
            else
            {
                if (transition.destinationStateMachine != null)
                {
                    var        stateMachine     = transition.destinationStateMachine;
                    JSONObject stateMachineJSON = new JSONObject(JSONObject.Type.OBJECT);
                    stateMachineJSON.AddField("type", "StateMachine");
                    bool stateMachineExist;
                    int  stateMachineId = controllerInfo.machines.AddObject(stateMachine, out stateMachineExist).Key;
                    if (!stateMachineExist)
                    {
                        TraverseStateMachine(ref stateMachine);
                    }
                    stateMachineJSON.AddField("id", stateMachineId);
                    transitionJSON.AddField("destSate", stateMachineJSON);
                }
                else
                {
                    transitionJSON.AddField("destSate", new JSONObject(JSONObject.Type.NULL));
                }
            }
            return(id);
        }
            private void writeResourceRecursive(string resourceDescriptionFilePath, ZipOutputStream zipStream)
            {
                // 如果已经转换过了
                if (packageGroupManifest_resourceDefinitions.HasField(resourceDescriptionFilePath))
                {
                    return;
                }
                // 先找到之前已经写入缓存表的资源。
                JSONObject resourceStorage = storage.GetField("assets").GetField(resourceDescriptionFilePath);

                if (resourceStorage == null)
                {
                    Debug.LogError("创建资源包时写入'" + resourceDescriptionFilePath + "'失败,没有找到该资源的转换记录");
                    return;
                }

                // 创建每一个资源definition的json对象
                JSONObject definitionObject = new JSONObject(JSONObject.Type.OBJECT);

                packageGroupManifest_resourceDefinitions.AddField(resourceDescriptionFilePath, definitionObject);

                // 写入字段
                definitionObject.AddField("dependencies", resourceStorage.GetField("dependencies"));
                definitionObject.AddField("type", resourceStorage.GetField("type"));
                definitionObject.AddField("descriptionFileID", resourceDescriptionFilePath);
                if (resourceStorage.GetField("importSetting") != null)
                {
                    definitionObject.AddField("importSetting", resourceStorage.GetField("importSetting"));
                }

                // 把记在缓存里的useFile拿出来,遍历,写入group.manifest.json的fileDescription字段
                // 并且排除掉resourceDescriptionFilePath之后放入resourceDefinition
                JSONObject outputUseFileArray = new JSONObject(JSONObject.Type.ARRAY);

                definitionObject.AddField("useFile", outputUseFileArray);

                // 放入文件
                foreach (string usingFile in WXUtility.ConvertJSONArrayToList(resourceStorage.GetField("useFile")))
                {
                    if (usingFile != resourceDescriptionFilePath)
                    {
                        outputUseFileArray.Add(usingFile);
                    }
                    if (packageGroupManifest_fileDescription.HasField(usingFile))
                    {
                        continue;
                    }
                    JSONObject fileStorage = storage.GetField("files").GetField(usingFile);

                    // add fileDescriptions
                    JSONObject fileDescription = new JSONObject(JSONObject.Type.OBJECT);
                    packageGroupManifest_fileDescription.AddField(usingFile, fileDescription);
                    fileDescription.AddField("path", usingFile);

                    // add files 555
                    JSONObject fileItem = new JSONObject(JSONObject.Type.OBJECT);
                    fileItem.AddField("path", usingFile);
                    fileItem.AddField("filetype", fileStorage.GetField("filetype"));
                    packageGroupManifest_files.Add(fileItem);

                    zipStream.PutNextEntry(new ZipEntry(usingFile));
                    var buffer = new byte[10240];
                    using (FileStream fsInput = File.OpenRead(Path.Combine(storagePath, Path.Combine(CONTENT_FOLDER, fileStorage.GetField("MD5").GetRawString()))))
                    {
                        StreamUtils.Copy(fsInput, zipStream, buffer);
                    }
                }

                // 递归转依赖
                foreach (string dependencyResource in WXUtility.ConvertJSONArrayToList(resourceStorage.GetField("dependencies")))
                {
                    writeResourceRecursive(dependencyResource, zipStream);
                }
            }
示例#3
0
        protected override JSONObject ExportResource(ExportPreset preset)
        {
            if (avatar.isHuman)
            {
                isHuman = GetHumanDescription(avatar, ref desc);
                if (isHuman)
                {
                    foreach (var pair in desc.human)
                    {
                        humanMap.Add(pair.humanName, pair.boneName);
                    }
                }
            }
            JSONObject avatarJSON = new JSONObject(JSONObject.Type.OBJECT);

            /*
             * {
             *  avatar:{
             *      path,
             *      linkSprites
             *  }
             * }
             */
            int id = -2;
            // GetAvatarNodeData(gameObject, rootNode, gameObject, ref id);
            bool       succ = false;
            JSONObject avatarRootNodeJSON = GetAvatarRootNodeJSON(gameObject, gameObject, ref id, ref succ);

            if (avatarRootNodeJSON == null)
            {
                return(null);
            }
            JSONObject    paths     = new JSONObject(JSONObject.Type.ARRAY);
            AssetImporter importer  = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(avatar.GetInstanceID()));
            ModelImporter mImporter = importer as ModelImporter;

            if (mImporter != null)
            {
                for (int k = 0; k < mImporter.extraExposedTransformPaths.Length; k++)
                {
                    paths.Add(mImporter.extraExposedTransformPaths[k]);
                }
            }
            avatarJSON.AddField("version", "1");
            avatarJSON.AddField("rootNode", avatarRootNodeJSON);
            avatarJSON.AddField("optimized", mImporter.optimizeGameObjects);
            string avatarPath = Path.GetFullPath(Directory.GetParent(Application.dataPath) + "/" + AssetDatabase.GetAssetPath(avatar.GetInstanceID()));
            float  scale      = (Path.GetExtension(avatarPath).ToLower() == ".fbx" && mImporter.useFileUnits) ? 0.01f : 1.0f;

            avatarJSON.AddField("scaleFactor", succ ? scale : 1.0f);
            avatarJSON.AddField("paths", paths);

            avatarJSON.AddField("version", 2);

            // 在importsetting里关联fbx文件
            if (Path.GetExtension(avatarPath).ToLower() == ".fbx")
            {
                importSetting = new JSONObject();
                WXRawResource fbx             = new WXRawResource(AssetDatabase.GetAssetPath(avatar.GetInstanceID()));
                string        fbxExportedPath = fbx.Export(preset);
                importSetting.AddField("associateFbx", fbxExportedPath);
                AddDependencies(fbxExportedPath);
            }
            return(avatarJSON);
        }
        private byte[] WriteMeshFile(ref JSONObject metadata)
        {
            MemoryStream fileStream = new MemoryStream();

            //ushort subMeshCount = (ushort)mesh.subMeshCount;
            string item = meshName;

            // 分析vertexLayout
            WXMeshVertexLayout vertexLayout = new WXMeshVertexLayout(mesh, true);

            List <Transform> bones = new List <Transform>();

            for (int j = 0; j < renderer.bones.Length; j++)
            {
                Transform item2 = renderer.bones[j];
                if (bones.IndexOf(item2) == -1)
                {
                    bones.Add(item2);
                }
            }

            //List<VertexData> vertexDatas = new List<VertexData>();
            //List<VertexData> boneGroupVertex = new List<VertexData>();
            //List<VertexData> vertexDataQueue = new List<VertexData>();
            //int[] positionInBoneGroup = new int[3];
            //List<int> indiceList = new List<int>();
            //List<int> allBoneIndexes = new List<int>();
            //List<int> vertexUsingBone = new List<int>();
            //VertexData vertexData;
            //for (int i = 0; i < subMeshCount; i++)
            //{
            //    int[] indices = mesh.GetIndices(i);
            //    for (int indiceIter = 0; indiceIter < indices.Length; indiceIter += 3)
            //    {
            //        // indice start
            //        for (int k = 0; k < 3; k++)
            //        {
            //            int indiceIndex = indiceIter + k;
            //            int vertexIndex = indices[indiceIndex];
            //            positionInBoneGroup[k] = -1;
            //            int ii = 0;
            //            while (ii < boneGroupVertex.Count)
            //            {
            //                if (boneGroupVertex[ii].index == vertexIndex)
            //                {
            //                    positionInBoneGroup[k] = ii;
            //                    break;
            //                }
            //                ii++;
            //                continue;
            //            }
            //            if (positionInBoneGroup[k] == -1)
            //            {
            //                vertexData = getVertexData(mesh, vertexIndex, vertexLayout);
            //                vertexDataQueue.Add(vertexData);
            //                // 每个点最多关联4根骨骼,所以遍历4下
            //                for (ii = 0; ii < 4; ii++)
            //                {
            //                    float bone = vertexData.boneIndex[ii];
            //                    if (allBoneIndexes.IndexOf((int)bone) == -1 && vertexUsingBone.IndexOf((int)bone) == -1)
            //                    {
            //                        vertexUsingBone.Add((int)bone);
            //                    }
            //                }
            //            }
            //        }
            //        // 没到达最大骨骼数 目前不知道这个24最大骨骼限制是干嘛用的
            //        if (allBoneIndexes.Count + vertexUsingBone.Count <= MaxBoneCount)
            //        {
            //            for (int l = 0; l < vertexUsingBone.Count; l++)
            //            {
            //                allBoneIndexes.Add(vertexUsingBone[l]);
            //            }
            //            int num8 = 1;
            //            for (int l = 0; l < 3; l++)
            //            {
            //                if (positionInBoneGroup[l] == -1)
            //                {
            //                    indiceList.Add(vertexDatas.Count + boneGroupVertex.Count - 1 + num8++);
            //                }
            //                else
            //                {
            //                    indiceList.Add(vertexDatas.Count + positionInBoneGroup[l]);
            //                }
            //            }
            //            for (int l = 0; l < vertexDataQueue.Count; l++)
            //            {
            //                boneGroupVertex.Add(vertexDataQueue[l]);
            //            }
            //        }
            //        else
            //        {
            //            for (int l = 0; l < boneGroupVertex.Count; l++)
            //            {
            //                vertexDatas.Add(boneGroupVertex[l]);
            //            }
            //            // 回退一位?
            //            indiceIter -= 3;
            //            boneGroupVertex = new List<VertexData>();
            //            allBoneIndexes = new List<int>();
            //        }

            //        // 最后一个face了
            //        if (indiceIter + 3 == indices.Length)
            //        {
            //            for (int l = 0; l < boneGroupVertex.Count; l++)
            //            {
            //                vertexDatas.Add(boneGroupVertex[l]);
            //            }
            //            boneGroupVertex = new List<VertexData>();
            //            allBoneIndexes = new List<int>();
            //        }
            //        vertexUsingBone = new List<int>();
            //        vertexDataQueue = new List<VertexData>();
            //        // indice end
            //    }
            //}
            long vertexStart     = 0L;
            long vertexLength    = 0L;
            long indiceStart     = 0L;
            long indiceLength    = 0L;
            long boneEndPosition = 0L;

            // 记录vertexBuffer在总buffer里的起始位置,一般是0
            vertexStart = fileStream.Position;
            // 用于算包围球,计算模型的重心(所有点的位置均值)
            Vector3 vertexPositionAddup = new Vector3(0, 0, 0);

            // 遍历mesh里的所有定点
            for (int j = 0; j < mesh.vertexCount; j++)
            {
                Vector3 vector = mesh.vertices[j];

                // 写入position
                wxFileUtil.WriteData(fileStream, vector.x * -1f, vector.y, vector.z);
                // 统计position,用于算包围盒
                vertexPositionAddup.Set(vertexPositionAddup.x + vector.x * -1f, vertexPositionAddup.y + vector.y, vertexPositionAddup.z + vector.z);

                // 如果vertexLayout有normal,写入normal
                if (vertexLayout.NORMAL)
                {
                    Vector3 vector2 = mesh.normals[j];
                    wxFileUtil.WriteData(fileStream, vector2.x * -1f, vector2.y, vector2.z);
                }
                // 如果vertexLayout有color,写入color
                if (vertexLayout.COLOR)
                {
                    Color color = mesh.colors[j];
                    wxFileUtil.WriteData(fileStream, color.r, color.g, color.b, color.a);
                }
                // 如果vertexLayout有uv,写入uv
                if (vertexLayout.UV)
                {
                    Vector2 vector3 = mesh.uv[j];
                    wxFileUtil.WriteData(fileStream, vector3.x, vector3.y * -1f + 1f);
                }
                // 如果vertexLayout有uv1,写入uv1
                if (vertexLayout.UV1)
                {
                    Vector2 vector4 = mesh.uv2[j];
                    wxFileUtil.WriteData(fileStream, vector4.x, vector4.y * -1f + 1f);
                }
                if (vertexLayout.BONE)
                {
                    BoneWeight boneWeight = mesh.boneWeights[j];
                    wxFileUtil.WriteData(
                        fileStream,
                        boneWeight.weight0,
                        boneWeight.weight1,
                        boneWeight.weight2,
                        boneWeight.weight3
                        );
                    wxFileUtil.WriteData(
                        fileStream,
                        (float)boneWeight.boneIndex0,
                        (float)boneWeight.boneIndex1,
                        (float)boneWeight.boneIndex2,
                        (float)boneWeight.boneIndex3
                        );
                }
                // 如果vertexLayout有tangent,写入tangent
                if (vertexLayout.TANGENT)
                {
                    Vector4 vector5 = mesh.tangents[j];
                    wxFileUtil.WriteData(fileStream, vector5.x * -1f, vector5.y, vector5.z, vector5.w);
                }
            }
            // 记录vertexBuffer在buffer里的结束位置
            vertexLength = fileStream.Position - vertexStart;

            // 记录indiceBuffer在buffer里的起始位置
            indiceStart = fileStream.Position;
            // indiceBuffer指的是给模型绘制面时,每个面所用的顶点index。在unity里叫triangles
            int[] triangles = mesh.triangles;
            for (int j = 0; j < triangles.Length; j++)
            {
                wxFileUtil.WriteData(fileStream, (ushort)triangles[j]);
            }
            // 记录indexBuffer在buffer里的结束位置
            indiceLength = fileStream.Position - indiceStart;

            // 因为读取的时候是根据4位来读的所以末尾补0
            long isFour = indiceLength % 4;

            if (isFour != 0)
            {
                wxFileUtil.WriteData(fileStream, (ushort)0.0);
            }

            long boneStartPosition = fileStream.Position;

            if (mesh.bindposes != null && mesh.bindposes.Length != 0)
            {
                Matrix4x4[] bonePoses = new Matrix4x4[mesh.bindposes.Length];
                for (int i = 0; i < mesh.bindposes.Length; i++)
                {
                    bonePoses[i] = mesh.bindposes[i];
                    bonePoses[i] = bonePoses[i].inverse;
                    Vector3    s   = default(Vector3);
                    Quaternion q   = default(Quaternion);
                    Vector3    pos = default(Vector3);
                    MathUtil.Decompose(bonePoses[i].transpose, out s, out q, out pos);
                    pos.x       *= -1f;
                    q.x         *= -1f;
                    q.w         *= -1f;
                    bonePoses[i] = Matrix4x4.TRS(pos, q, s);
                }
                for (int i = 0; i < mesh.bindposes.Length; i++)
                {
                    Matrix4x4 matrix4x = bonePoses[i];
                }
                for (int i = 0; i < mesh.bindposes.Length; i++)
                {
                    Matrix4x4 inverse = bonePoses[i].inverse;
                    for (int j = 0; j < 16; j++)
                    {
                        wxFileUtil.WriteData(fileStream, inverse[j]);
                    }
                }
                boneEndPosition = fileStream.Position;
            }
            long bonePoseLength = boneEndPosition - boneStartPosition;

            fileStream.Close();

            metadata.AddField("indiceFormat", 1);                              //   BIT16 = 1,BIT32 = 2
            metadata.AddField("vertexLayout", vertexLayout.GetLayoutString()); //"POSITION,NORMAL,COLOR,UV,BLENDWEIGHT,BLENDINDICES,TANGENT",
            metadata.AddField("vertexStart", 0);
            metadata.AddField("vertexLength", vertexLength);
            metadata.AddField("indiceStart", vertexLength);  // indice的偏移量
            metadata.AddField("indiceLength", indiceLength); // indice的长度
            metadata.AddField("bonePoseStart", boneStartPosition);
            metadata.AddField("bonePoseLength", bonePoseLength);
            metadata.AddField("capsule", GetCapsule());

            bool       succ        = false;
            JSONObject bonesObject = GetSkinPaths(renderer.sharedMesh.name, ref succ);

            metadata.AddField("rootBone", bonesObject.GetField("root"));
            metadata.AddField("bones", bonesObject.GetField("bones"));
            metadata.AddField("version", 1);

            // 加入submesh
            JSONObject subMeshs = new JSONObject(JSONObject.Type.ARRAY);

#if !UNITY_2017_1_OR_NEWER
            int indexStart = 0;
#endif
            ushort subMeshCount = (ushort)mesh.subMeshCount;
            for (int i = 0; i < subMeshCount; i++)
            {
                JSONObject subMeshObj = new JSONObject(JSONObject.Type.OBJECT);
#if !UNITY_2017_1_OR_NEWER
                subMeshObj.AddField("start", indexStart);
                subMeshObj.AddField("length", mesh.GetIndices(i).Length);
                indexStart += mesh.GetIndices(i).Length;
#else
                subMeshObj.AddField("start", mesh.GetIndexStart(i));
                subMeshObj.AddField("length", mesh.GetIndexCount(i));
#endif
                subMeshs.Add(subMeshObj);
            }
            // submesh一般指的是mesh里的其中一部分,所以用indiceBuffer的区间表示
            metadata.AddField("subMeshs", subMeshs);


            return(fileStream.ToArray());
        }
示例#5
0
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
            JSONObject data = new JSONObject(JSONObject.Type.OBJECT);

            json.AddField("type", "MeshRenderer");
            json.AddField("data", data);

            Mesh mesh = (renderer.gameObject.GetComponent(typeof(MeshFilter)) as MeshFilter).sharedMesh;

            if (mesh != null)
            {
                WXMesh meshConverter = new WXMesh(mesh);
                string meshPath      = meshConverter.Export(context.preset);
                data.AddField("mesh", meshPath);
                context.AddResource(meshPath);
            }
            else
            {
                Debug.LogError(string.Format("{0} mesh is null", renderer.name));
            }

            JSONObject materialArray = new JSONObject(JSONObject.Type.ARRAY);

            Material[] materials = renderer.sharedMaterials;
            foreach (Material material in materials)
            {
                if (material != null)
                {
                    WXMaterial materialConverter = new WXMaterial(material, renderer);
                    string     materialPath      = materialConverter.Export(context.preset);
                    materialArray.Add(materialPath);
                    context.AddResource(materialPath);
                }
            }
            data.AddField("materials", materialArray);

            int        lightmapIndex  = renderer.lightmapIndex;
            JSONObject litmapScaleArr = new JSONObject(JSONObject.Type.ARRAY);

            data.AddField("lightMapScaleOffset", litmapScaleArr);
            litmapScaleArr.Add(renderer.lightmapScaleOffset.x);
            litmapScaleArr.Add(renderer.lightmapScaleOffset.y);
            litmapScaleArr.Add(renderer.lightmapScaleOffset.z);
            litmapScaleArr.Add(renderer.lightmapScaleOffset.w);
            data.AddField("lightMapIndex", lightmapIndex);

            ShadowCastingMode mode        = renderer.shadowCastingMode;
            StaticEditorFlags shadowFlags = GameObjectUtility.GetStaticEditorFlags(renderer.gameObject);

            if (mode == ShadowCastingMode.Off || (shadowFlags & StaticEditorFlags.LightmapStatic) != 0)
            {
                data.AddField("castShadow", false);
            }
            else
            {
                data.AddField("castShadow", true);
            }

            bool receiveShadow = renderer.receiveShadows;

            data.AddField("receiveShadow", receiveShadow);
            return(json);
        }
        protected override JSONObject ExportResource(ExportPreset preset)
        {
            WXHierarchyContext hierarchyContext = new WXHierarchyContext(preset, prefabPath);

            hierarchyContext.prefab2dType = typeof(WXNGUITree);

            // 初始化输出的JSON对象
            JSONObject prefabJSONObject = new JSONObject(JSONObject.Type.OBJECT);

            JSONObject metaJson = new JSONObject(JSONObject.Type.OBJECT);

            prefabJSONObject.AddField("meta", metaJson);


            // 填充meta
            metaJson.AddField("name", exportName);
            metaJson.AddField("type", "2D");

            if (exportAsScene)
            {
                JSONObject configJson = new JSONObject(JSONObject.Type.OBJECT);
                metaJson.AddField("config", configJson);

                JSONObject resolutionJson = new JSONObject(JSONObject.Type.ARRAY);

                UIRoot uiRoot = getUIRoot(prefabRoot);
                if (uiRoot != null)
                {
                    Debug.Log("uiRoot is");
                    // var a = JsonUtility.ToJson(uiRoot, true);
                    // Debug.Log(a);
                    // Debug.Log(uiRoot.activeHeight);
                    // Debug.Log(uiRoot.manualWidth);
                    // Debug.Log(uiRoot.manualHeight);

                    UIRoot.Scaling scalingStyle = uiRoot.scalingStyle;
                    configJson.AddField("scalingStyle", (int)scalingStyle);
                    configJson.AddField("manualWidth", uiRoot.manualWidth);
                    configJson.AddField("manualHeight", uiRoot.manualHeight);
                    configJson.AddField("minimumHeight", uiRoot.minimumHeight);
                    configJson.AddField("maximumHeight", uiRoot.maximumHeight);
                    configJson.AddField("fitWidth", uiRoot.fitWidth);
                    configJson.AddField("fitHeight", uiRoot.fitHeight);
                    configJson.AddField("adjustByDPI", uiRoot.adjustByDPI);
                    configJson.AddField("shrinkPortraitUI", uiRoot.shrinkPortraitUI);

                    if (scalingStyle == UIRoot.Scaling.Flexible)
                    {
                        // 目前引擎没有对Flexible这种情况的支持,所以默认先导出一个假定的resolution
                        resolutionJson.Add(uiRoot.activeHeight);
                        resolutionJson.Add(uiRoot.activeHeight);
                    }
                    else
                    {
                        resolutionJson.Add(uiRoot.manualWidth);
                        resolutionJson.Add(uiRoot.manualHeight);
                    }
                }
                else
                {
                    // 无root情况,使用默认大小
                    resolutionJson.Add(1280);
                    resolutionJson.Add(720);
                }

                configJson.AddField("resolution", resolutionJson);
            }

            // 开始遍历
            WXEntity rootEntity = hierarchyContext.IterateGameObject(prefabRoot);

            prefabJSONObject.AddField("gameObjectList", hierarchyContext.GetGameObjectListJSON());
            prefabJSONObject.AddField("componentList", hierarchyContext.GetComponentListJSON());

            JSONObject editorInfo = new JSONObject(JSONObject.Type.OBJECT);

            editorInfo.AddField("assetVersion", 2);
            prefabJSONObject.AddField("editorInfo", editorInfo);
            //Debug.Log("Export Prefab " + prefabPath + "  " + hierarchyContext.resourceList.Count);

            foreach (string resource in hierarchyContext.resourceList)
            {
                AddDependencies(resource);
            }

            return(prefabJSONObject);
        }
示例#7
0
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            JSONObject json = new JSONObject(JSONObject.Type.OBJECT);

            json.AddField("type", "UISprite");

            JSONObject subJSON = new JSONObject(JSONObject.Type.OBJECT);

            JSONObject color = new JSONObject(JSONObject.Type.ARRAY);

            color.Add(255f * uiTexture.color.r);
            color.Add(255f * uiTexture.color.g);
            color.Add(255f * uiTexture.color.b);
            color.Add(255f * uiTexture.color.a);
            subJSON.AddField("color", color);
            subJSON.AddField("colorBlendType", 0);

            UI2DSprite.Type type = uiTexture.type;
            subJSON.AddField("type", (int)type);

            UI2DSprite.Flip flipType = uiTexture.flip;
            subJSON.AddField("flip", (int)flipType);
            subJSON.AddField("fillCenter", uiTexture.centerType == UI2DSprite.AdvancedType.Sliced);
            subJSON.AddField("fillDir", (int)uiTexture.fillDirection);
            subJSON.AddField("fillAmount", uiTexture.fillAmount);
            subJSON.AddField("invertFill", uiTexture.invert);

            string texturePath = "";

            if (uiTexture.mainTexture != null)
            {
                Texture2D texture2D = (Texture2D)uiTexture.mainTexture;
                if (texture2D != null)
                {
                    string path = AssetDatabase.GetAssetPath(texture2D.GetInstanceID());

                    texturePath = new WXTexture(texture2D).Export(context.preset);// MaterialUtil.SaveTextureFile(texture2D);
                    context.AddResource(texturePath);

                    UISpriteData data = new UISpriteData();
                    data.width  = uiTexture.mainTexture.width;
                    data.height = uiTexture.mainTexture.height;

                    WXSpriteFrame spriteFrame = new WXSpriteFrame(data, texturePath, path);
                    string        key         = spriteFrame.Export(context.preset);

                    subJSON.AddField("spriteFrame", key);
                    context.AddResource(key);
                }
            }
            else
            {
                JSONObject nullJSON = new JSONObject(JSONObject.Type.NULL);
                subJSON.AddField("spriteFrame", nullJSON);
            }

            subJSON.AddField("active", uiTexture.enabled);

            json.AddField("data", subJSON);

            return(json);
        }
示例#8
0
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
            JSONObject data = new JSONObject(JSONObject.Type.OBJECT);

            json.AddField("type", "TrailRenderer");
            json.AddField("data", data);

            JSONObject materialArray = new JSONObject(JSONObject.Type.ARRAY);

            Material[] materials = renderer.sharedMaterials;
            foreach (Material material in materials)
            {
                WXMaterial materialConverter = new WXMaterial(material, renderer);
                string     materialPath      = materialConverter.Export(context.preset);
                materialArray.Add(materialPath);
                context.AddResource(materialPath);
            }
            data.AddField("materials", materialArray);

            ShadowCastingMode mode        = renderer.shadowCastingMode;
            StaticEditorFlags shadowFlags = GameObjectUtility.GetStaticEditorFlags(renderer.gameObject);

            if (mode == ShadowCastingMode.Off || (shadowFlags & StaticEditorFlags.LightmapStatic) != 0)
            {
                data.AddField("castShadow", false);
            }
            else
            {
                data.AddField("castShadow", true);
            }

            bool receiveShadow = renderer.receiveShadows;

            data.AddField("receiveShadow", receiveShadow);

            int alignmentNum = 0;

#if UNITY_2017_1_OR_NEWER
            LineAlignment alignment = renderer.alignment;
            switch (alignment)
            {
            case LineAlignment.View:
                alignmentNum = 0;
                break;

    #if UNITY_2018_2_OR_NEWER
            case LineAlignment.TransformZ:
                alignmentNum = 1;
                break;
    #else
            case LineAlignment.Local:
                alignmentNum = 1;
                break;
    #endif
            }
            data.AddField("alignment", alignmentNum);
#endif

            Color startColor = renderer.startColor;
            data.AddField("startColor", parseColor(startColor));

            Color endColor = renderer.endColor;
            data.AddField("endColor", parseColor(endColor));

            float startWidth = renderer.startWidth;
            data.AddField("startWidth", startWidth);

            float endWidth = renderer.endWidth;
            data.AddField("endWidth", endWidth);

            float time = renderer.time;
            data.AddField("time", time);

            LineTextureMode textureMode    = renderer.textureMode;
            int             textureModeNum = 0;
            switch (textureMode)
            {
            case LineTextureMode.Stretch:
                textureModeNum = 0;
                break;

            case LineTextureMode.Tile:
                textureModeNum = 1;
                break;
            }
            data.AddField("textureMode", textureModeNum);

            data.AddField("numCapVertices", renderer.numCapVertices);
            data.AddField("numCornerVertices", renderer.numCornerVertices);
            data.AddField("minVertexDistance", renderer.minVertexDistance);

            data.AddField("gColor", GetGradientColor(renderer.colorGradient));

            data.AddField("widthCurve", GetCurveData(renderer.widthCurve));
            data.AddField("widthMultiplier", renderer.widthMultiplier);

            return(json);
        }
        // 导出AnimationTrack
        private int ExportAnimationTrack(AnimationTrack animationTrack, JSONObject trackListArr, JSONObject clipListArr)
        {
            JSONObject trackJSON = GenerateBaseTrack(animationTrack, PlaybaleTrackTypeMap["AnimationTrack"]);

            trackJSON.AddField("applyAvatarMask", animationTrack.applyAvatarMask);
            JSONObject infiniteClipOffsetPositionArr = new JSONObject(JSONObject.Type.ARRAY);
            JSONObject infiniteClipOffsetRotationArr = new JSONObject(JSONObject.Type.ARRAY);

            trackJSON.AddField("infiniteClipOffsetPosition", infiniteClipOffsetPositionArr);
            trackJSON.AddField("infiniteClipOffsetRotation", infiniteClipOffsetRotationArr);
#if UNITY_2018_3_OR_NEWER
            trackJSON.AddField("trackOffset", TrackOffsetMap[animationTrack.trackOffset]);
#else
            if (animationTrack.applyOffsets)
            {
                trackJSON.AddField("trackOffset", TrackOffsetMap["ApplyTransformOffsets"]);
            }
            else
            {
                trackJSON.AddField("trackOffset", TrackOffsetMap["Auto"]);
            }
#endif
#if UNITY_2019_1_OR_NEWER
            infiniteClipOffsetPositionArr.Add(-animationTrack.infiniteClipOffsetPosition.x);
            infiniteClipOffsetPositionArr.Add(animationTrack.infiniteClipOffsetPosition.y);
            infiniteClipOffsetPositionArr.Add(animationTrack.infiniteClipOffsetPosition.z);
            infiniteClipOffsetRotationArr.Add(-animationTrack.infiniteClipOffsetRotation.x);
            infiniteClipOffsetRotationArr.Add(animationTrack.infiniteClipOffsetRotation.y);
            infiniteClipOffsetRotationArr.Add(animationTrack.infiniteClipOffsetRotation.z);
            infiniteClipOffsetRotationArr.Add(-animationTrack.infiniteClipOffsetRotation.w);
#else
            infiniteClipOffsetPositionArr.Add(-animationTrack.openClipOffsetPosition.x);
            infiniteClipOffsetPositionArr.Add(animationTrack.openClipOffsetPosition.y);
            infiniteClipOffsetPositionArr.Add(animationTrack.openClipOffsetPosition.z);
            infiniteClipOffsetRotationArr.Add(-animationTrack.openClipOffsetRotation.x);
            infiniteClipOffsetRotationArr.Add(animationTrack.openClipOffsetRotation.y);
            infiniteClipOffsetRotationArr.Add(animationTrack.openClipOffsetRotation.z);
            infiniteClipOffsetRotationArr.Add(-animationTrack.openClipOffsetRotation.w);
#endif
            if (animationTrack.avatarMask != null)
            {
                WXAvatarMask mask = new WXAvatarMask(animationTrack.avatarMask);
                string       uid  = AddDependencies(mask);
                trackJSON.AddField("avatarMask", uid);
            }
            else
            {
                trackJSON.AddField("avatarMask", new JSONObject(JSONObject.Type.NULL));
            }

            JSONObject positionArr = new JSONObject(JSONObject.Type.ARRAY);
            positionArr.Add(-animationTrack.position.x);
            positionArr.Add(animationTrack.position.y);
            positionArr.Add(animationTrack.position.z);
            trackJSON.AddField("position", positionArr);

            JSONObject rotationArr = new JSONObject(JSONObject.Type.ARRAY);
            rotationArr.Add(-animationTrack.rotation.x);
            rotationArr.Add(animationTrack.rotation.y);
            rotationArr.Add(animationTrack.rotation.z);
            rotationArr.Add(-animationTrack.rotation.w);
            trackJSON.AddField("rotation", rotationArr);

            JSONObject matchTargetFieldsJSON = new JSONObject(JSONObject.Type.OBJECT);
            trackJSON.AddField("matchTargetFields", matchTargetFieldsJSON);
            matchTargetFieldsJSON.AddField("PositionX", (animationTrack.matchTargetFields & MatchTargetFields.PositionX) == MatchTargetFields.PositionX);
            matchTargetFieldsJSON.AddField("PositionY", (animationTrack.matchTargetFields & MatchTargetFields.PositionY) == MatchTargetFields.PositionY);
            matchTargetFieldsJSON.AddField("PositionZ", (animationTrack.matchTargetFields & MatchTargetFields.PositionZ) == MatchTargetFields.PositionZ);
            matchTargetFieldsJSON.AddField("RotationX", (animationTrack.matchTargetFields & MatchTargetFields.RotationX) == MatchTargetFields.RotationX);
            matchTargetFieldsJSON.AddField("RotationY", (animationTrack.matchTargetFields & MatchTargetFields.RotationY) == MatchTargetFields.RotationY);
            matchTargetFieldsJSON.AddField("RotationZ", (animationTrack.matchTargetFields & MatchTargetFields.RotationZ) == MatchTargetFields.RotationZ);

            UnityEditor.SerializedObject   serializedObject = new UnityEditor.SerializedObject(animationTrack);
            UnityEditor.SerializedProperty serializedClip   = serializedObject.FindProperty("m_Clips");

            JSONObject clipsIndexArr = trackJSON.GetField("clips");
            if (animationTrack.inClipMode) // 普通clip
            // 貌似有时候序列化的m_Clips顺序跟 timelineClipList 的顺序对不上,但是很难复现。没有找到顺序可以必定对上的方法,先这样吧
            {
                IEnumerable <TimelineClip> timelineClipList = animationTrack.GetClips();
                int num = 0;
                foreach (TimelineClip timelineClip in timelineClipList)
                {
                    JSONObject clipJSON = GenerateBaseTimelineClip(timelineClip, PlaybaleClipTypeMap["Animation"]);
                    JSONObject clipData = new JSONObject(JSONObject.Type.OBJECT);
                    float      m_PostExtrapolationTime = (float)serializedClip.FindPropertyRelative("Array.data[" + num + "].m_PostExtrapolationTime").doubleValue;
                    float      m_PreExtrapolationTime  = (float)serializedClip.FindPropertyRelative("Array.data[" + num + "].m_PreExtrapolationTime").doubleValue;
                    clipJSON.SetField("postExtrapolationTime", m_PostExtrapolationTime);
                    clipJSON.SetField("preExtrapolationTime", m_PreExtrapolationTime);
                    clipJSON.AddField("data", clipData);

                    bool m_Recordable = serializedClip.FindPropertyRelative("Array.data[" + num + "].m_Recordable").boolValue;
                    clipData.AddField("recordable", m_Recordable);

                    string clipPath = ExportAnimationClip(timelineClip.animationClip);
                    if (string.IsNullOrEmpty(clipPath))
                    {
                        clipData.AddField("clip", JSONObject.nullJO);
                    }
                    else
                    {
                        clipData.AddField("clip", clipPath);
                    }


                    AnimationPlayableAsset asset = (AnimationPlayableAsset)timelineClip.asset;
                    // clipData.AddField("clipCaps", ClipCapsMap.ContainsKey(timelineClip.clipCaps) ? ClipCapsMap[timelineClip.clipCaps] : ClipCapsMap[ClipCaps.None]);
                    // clipData.AddField("duration", (float)asset.duration);
#if UNITY_2018_3_OR_NEWER
                    // 2018_3才开始支持
                    clipData.AddField("applyFootIK", asset.applyFootIK);
#else
                    clipData.AddField("applyFootIK", false);
#endif

#if UNITY_2019_1_OR_NEWER
                    // 2019_1才开始支持
                    clipData.AddField("loop", LoopModeMap[asset.loop]);
#else
                    clipData.AddField("loop", LoopModeMap["UseSourceAsset"]);
#endif

                    clipData.AddField("useTrackMatchFields", asset.useTrackMatchFields);

                    JSONObject clipMatchTargetFieldsJSON = new JSONObject(JSONObject.Type.OBJECT);
                    clipData.AddField("matchTargetFields", clipMatchTargetFieldsJSON);
                    clipMatchTargetFieldsJSON.AddField("PositionX", (asset.matchTargetFields & MatchTargetFields.PositionX) == MatchTargetFields.PositionX);
                    clipMatchTargetFieldsJSON.AddField("PositionY", (asset.matchTargetFields & MatchTargetFields.PositionY) == MatchTargetFields.PositionY);
                    clipMatchTargetFieldsJSON.AddField("PositionZ", (asset.matchTargetFields & MatchTargetFields.PositionZ) == MatchTargetFields.PositionZ);
                    clipMatchTargetFieldsJSON.AddField("RotationX", (asset.matchTargetFields & MatchTargetFields.RotationX) == MatchTargetFields.RotationX);
                    clipMatchTargetFieldsJSON.AddField("RotationY", (asset.matchTargetFields & MatchTargetFields.RotationY) == MatchTargetFields.RotationY);
                    clipMatchTargetFieldsJSON.AddField("RotationZ", (asset.matchTargetFields & MatchTargetFields.RotationZ) == MatchTargetFields.RotationZ);

                    JSONObject clipPositionArr = new JSONObject(JSONObject.Type.ARRAY);
                    clipPositionArr.Add(-asset.position.x);
                    clipPositionArr.Add(asset.position.y);
                    clipPositionArr.Add(asset.position.z);
                    clipData.AddField("position", clipPositionArr);

                    JSONObject clipRotationArr = new JSONObject(JSONObject.Type.ARRAY);
                    clipRotationArr.Add(-asset.rotation.x);
                    clipRotationArr.Add(asset.rotation.y);
                    clipRotationArr.Add(asset.rotation.z);
                    clipRotationArr.Add(-asset.rotation.w);
                    clipData.AddField("rotation", clipRotationArr);

                    clipsIndexArr.Add(ExportTimelineClip(clipJSON, clipListArr));
                    num++;
                }
            }
            else // infiniteClip
            {
#if UNITY_2019_1_OR_NEWER
                // 2019_1才开始支持
                AnimationClip infiniteClip = animationTrack.infiniteClip;
#else
                // 序列化取出私有变量
                UnityEditor.SerializedObject   trackSerializedObject = new UnityEditor.SerializedObject(animationTrack);
                UnityEditor.SerializedProperty animClipSerialize     = trackSerializedObject.FindProperty("m_AnimClip");
                AnimationClip infiniteClip = animClipSerialize.objectReferenceValue as AnimationClip;
#endif
                string infinityClipPath = ExportAnimationClip(infiniteClip);
                if (string.IsNullOrEmpty(infinityClipPath))
                {
                    trackJSON.SetField("infinityClip", JSONObject.nullJO);
                }
                else
                {
                    trackJSON.SetField("infinityClip", infinityClipPath);
                }
            }
            // 导出子track
            JSONObject childrenJSON = trackJSON.GetField("children");
            IEnumerable <TrackAsset> childTrackAssetList = animationTrack.GetChildTracks();
            List <int> indexList = ExportTrackList(childTrackAssetList, trackListArr, clipListArr);
            foreach (int index in indexList)
            {
                childrenJSON.Add(index);
            }
            return(ExportTrack(trackJSON, trackListArr));
        }
示例#10
0
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
            JSONObject data = new JSONObject(JSONObject.Type.OBJECT);

            json.AddField("type", "SkinnedMeshRenderer");
            json.AddField("data", data);

            // Mesh mesh = (renderer.gameObject.GetComponent (typeof(MeshFilter)) as MeshFilter).sharedMesh;
            // SkinnedMeshRenderer component = renderer.gameObject.GetComponent<SkinnedMeshRenderer>();
            Mesh mesh = renderer.sharedMesh;

            if (mesh != null)
            {
                WXSkinnedMesh meshConverter = new WXSkinnedMesh(mesh, renderer);
                string        meshPath      = meshConverter.Export(context.preset);
                data.AddField("mesh", meshPath);
                context.AddResource(meshPath);
            }
            else
            {
                Debug.LogWarning("mesh is null");
            }
            JSONObject materialArray = new JSONObject(JSONObject.Type.ARRAY);

            Material[] materials = renderer.sharedMaterials;
            foreach (Material material in materials)
            {
                WXMaterial materialConverter = new WXMaterial(material, renderer);
                string     materialPath      = materialConverter.Export(context.preset);
                materialArray.Add(materialPath);
                context.AddResource(materialPath);
            }
            data.AddField("materials", materialArray);
            data.AddField("props", GenProps());

            int        lightmapIndex  = renderer.lightmapIndex;
            JSONObject litmapScaleArr = new JSONObject(JSONObject.Type.ARRAY);

            data.AddField("lightMapScaleOffset", litmapScaleArr);
            litmapScaleArr.Add(renderer.lightmapScaleOffset.x);
            litmapScaleArr.Add(renderer.lightmapScaleOffset.y);
            litmapScaleArr.Add(renderer.lightmapScaleOffset.z);
            litmapScaleArr.Add(renderer.lightmapScaleOffset.w);
            data.AddField("lightMapIndex", lightmapIndex);

            ShadowCastingMode mode = renderer.shadowCastingMode;

            if (mode == ShadowCastingMode.Off)
            {
                data.AddField("castShadow", false);
            }
            else
            {
                data.AddField("castShadow", true);
            }

            bool receiveShadow = renderer.receiveShadows;

            data.AddField("receiveShadow", receiveShadow);

            return(json);
        }
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            JSONObject json = new JSONObject(JSONObject.Type.OBJECT);

            json.AddField("type", "UILabel");

            JSONObject subJSON = new JSONObject(JSONObject.Type.OBJECT);
            string     str     = uiLabel.text.Replace("\r\n", "\\n").Replace("\\", "\\\\").Replace("\"", "\\\"");

            subJSON.AddField("text", str);
            subJSON.AddField("fontSize", uiLabel.fontSize);

            int    instanceID = 0;
            string fontFamily = "";

            if (uiLabel.trueTypeFont)
            {
                // NGUI font
                instanceID = uiLabel.trueTypeFont.material.GetInstanceID();
                string path = AssetDatabase.GetAssetPath(instanceID); // 相对路径
                if (path.IndexOf("Library") != 0)
                {
                    // Debug.Log(fontFamily);
                    WXFont fontConverter = new WXFont(path);
                    fontFamily = fontConverter.Export(context.preset);
                    context.AddResource(fontFamily);
                }
                else
                {
                    string name = this.uiLabel.gameObject.name;
                    Debug.LogWarning("UI Label:" + name + " use system font!!");
                }
            }
            else if (uiLabel.bitmapFont)
            {
                fontFamily = "";
                WXBitmapFont bitmapFont = new WXBitmapFont(uiLabel.bitmapFont);
                string       path       = bitmapFont.Export(context.preset);
                context.AddResource(path);
                subJSON.AddField("bitmapFont", path);
            }

            if (fontFamily != "")
            {
                subJSON.AddField("font", fontFamily);
            }

            string fontStyle = uiLabel.fontStyle.ToString();

            subJSON.AddField("bold", fontStyle == "Bold" || fontStyle == "Bold And Italic");
            subJSON.AddField("italic", fontStyle == "Italic" || fontStyle == "Bold And Italic");

            int alignment = 0;

            switch (uiLabel.alignment.ToString())
            {
            case "Left":
                alignment = 1;
                break;

            case "Center":
                alignment = 2;
                break;

            case "Right":
                alignment = 3;
                break;

            default:
                alignment = 0;
                string rawPivot = uiLabel.rawPivot.ToString();
                switch (rawPivot)
                {
                case "Left":
                    alignment = 1;
                    break;

                case "Center":
                    alignment = 2;
                    break;

                case "Right":
                    alignment = 3;
                    break;
                }
                break;
            }
            subJSON.AddField("align", alignment);

            // 应轩辕要求,缺省值改成 2
            int    valign = 2;
            string pivot  = uiLabel.pivot.ToString();

            switch (pivot)
            {
            case "Top":
                valign = 1;
                break;

            case "Center":
                valign = 2;
                break;

            case "Bottom":
                valign = 3;
                break;

            default:
                valign = 2;
                break;
            }
            subJSON.AddField("valign", valign);

            if (uiLabel.effectStyle != UILabel.Effect.None)
            {
                JSONObject c = new JSONObject(JSONObject.Type.ARRAY);
                c.Add(255f * uiLabel.effectColor.r);
                c.Add(255f * uiLabel.effectColor.g);
                c.Add(255f * uiLabel.effectColor.b);
                c.Add(255f * uiLabel.effectColor.a);
                switch (uiLabel.effectStyle)
                {
                case UILabel.Effect.None:
                    break;

                case UILabel.Effect.Shadow:
                    JSONObject v2 = new JSONObject(JSONObject.Type.ARRAY);
                    v2.Add(uiLabel.effectDistance.x);
                    v2.Add(uiLabel.effectDistance.y);
                    subJSON.AddField("shadowOffset", v2);
                    subJSON.AddField("shadowColor", c);
                    break;

                case UILabel.Effect.Outline8:
                    subJSON.AddField("strokeColor", c);
                    subJSON.AddField("stroke", uiLabel.effectDistance.x);
                    break;

                case UILabel.Effect.Outline:
                    subJSON.AddField("strokeColor", c);
                    subJSON.AddField("stroke", uiLabel.effectDistance.x);
                    break;

                default:
                    break;
                }
            }

            subJSON.AddField("spacing", uiLabel.spacingX);

            JSONObject color = new JSONObject(JSONObject.Type.ARRAY);

            color.Add(255f * uiLabel.color.r);
            color.Add(255f * uiLabel.color.g);
            color.Add(255f * uiLabel.color.b);
            color.Add(255f * uiLabel.color.a);
            subJSON.AddField("fontColor", color);
            subJSON.AddField("colorBlendType", 0);

            subJSON.AddField("applyGradient", uiLabel.applyGradient);

            JSONObject topColor    = new JSONObject(JSONObject.Type.ARRAY);
            JSONObject bottomColor = new JSONObject(JSONObject.Type.ARRAY);

            topColor.Add(255f * uiLabel.gradientTop.r);
            topColor.Add(255f * uiLabel.gradientTop.g);
            topColor.Add(255f * uiLabel.gradientTop.b);
            topColor.Add(255f * uiLabel.gradientTop.a);

            bottomColor.Add(255f * uiLabel.gradientBottom.r);
            bottomColor.Add(255f * uiLabel.gradientBottom.g);
            bottomColor.Add(255f * uiLabel.gradientBottom.b);
            bottomColor.Add(255f * uiLabel.gradientBottom.a);

            subJSON.AddField("gradientTop", topColor);
            subJSON.AddField("gradientBottom", bottomColor);

            subJSON.AddField("active", uiLabel.enabled);
            json.AddField("data", subJSON);

            return(json);
        }
示例#12
0
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            JSONObject json = new JSONObject(JSONObject.Type.OBJECT);

            json.AddField("type", getTypeName());


            JSONObject subJSON = new JSONObject(JSONObject.Type.OBJECT);
            string     str     = uiLabel.text;

            subJSON.AddField("text", str);

            subJSON.AddField("fontSize", uiLabel.fontSize);


            JSONObject color = new JSONObject(JSONObject.Type.ARRAY);

            color.Add(255f * uiLabel.color.r);
            color.Add(255f * uiLabel.color.g);
            color.Add(255f * uiLabel.color.b);
            color.Add(255f * uiLabel.color.a);
            subJSON.AddField("fontColor", color);


            int    instanceID = 0;
            string fontFamily = "";

            if (uiLabel.font)
            {
                // NGUI font
                instanceID = uiLabel.font.material.GetInstanceID();
                string path = AssetDatabase.GetAssetPath(instanceID); // 相对路径
                if (path.IndexOf("Library") != 0)
                {
                    // Debug.Log(fontFamily);
                    WXUGUIFont fontConverter = new WXUGUIFont(path);
                    fontFamily = fontConverter.Export(context.preset);
                    context.AddResource(fontFamily);
                }
                else
                {
                    string name = this.uiLabel.gameObject.name;
                    Debug.LogWarning("UI Label:" + name + " use system font!!");
                }
            }


            if (fontFamily != "")
            {
                subJSON.AddField("font", fontFamily);
            }


            int alignment = 0;

            if (uiLabel.alignment == TextAnchor.LowerLeft || uiLabel.alignment == TextAnchor.MiddleLeft || uiLabel.alignment == TextAnchor.UpperLeft)
            {
                alignment = 1;
            }
            else if (uiLabel.alignment == TextAnchor.LowerCenter || uiLabel.alignment == TextAnchor.MiddleCenter || uiLabel.alignment == TextAnchor.UpperCenter)
            {
                alignment = 2;
            }
            else if (uiLabel.alignment == TextAnchor.LowerRight || uiLabel.alignment == TextAnchor.MiddleRight || uiLabel.alignment == TextAnchor.UpperRight)
            {
                alignment = 3;
            }
            subJSON.AddField("align", alignment);

            int valign = 0;

            if (uiLabel.alignment == TextAnchor.LowerLeft || uiLabel.alignment == TextAnchor.LowerCenter || uiLabel.alignment == TextAnchor.LowerRight)
            {
                valign = 3;
            }
            else if (uiLabel.alignment == TextAnchor.MiddleLeft || uiLabel.alignment == TextAnchor.MiddleCenter || uiLabel.alignment == TextAnchor.MiddleRight)
            {
                valign = 2;
            }
            else if (uiLabel.alignment == TextAnchor.UpperLeft || uiLabel.alignment == TextAnchor.UpperCenter || uiLabel.alignment == TextAnchor.UpperRight)
            {
                valign = 1;
            }
            subJSON.AddField("valign", valign);


            //switch (uiLabel.alignment.ToString())
            //{

            //}
            //if(uiLabel.)

            subJSON.AddField("active", uiLabel.IsActive());
            json.AddField("data", subJSON);

            return(json);
        }
示例#13
0
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            JSONObject json = new JSONObject(JSONObject.Type.OBJECT);

            json.AddField("type", "UIButton");

            /*
             * JSONObject colorHover = new JSONObject(JSONObject.Type.ARRAY);
             * colorHover.Add(uiButton.hover.r);
             * colorHover.Add(uiButton.hover.g);
             * colorHover.Add(uiButton.hover.b);
             * colorHover.Add(uiButton.hover.a);
             * json.AddField("colorHover", colorHover);
             */

            JSONObject subJSON = new JSONObject(JSONObject.Type.OBJECT);

            JSONObject colorPressed = new JSONObject(JSONObject.Type.ARRAY);

            colorPressed.Add(255f * uiButton.pressed.r);
            colorPressed.Add(255f * uiButton.pressed.g);
            colorPressed.Add(255f * uiButton.pressed.b);
            colorPressed.Add(255f * uiButton.pressed.a);
            subJSON.AddField("pressedColor", colorPressed);

            JSONObject colorDisabledColor = new JSONObject(JSONObject.Type.ARRAY);

            colorDisabledColor.Add(255f * uiButton.disabledColor.r);
            colorDisabledColor.Add(255f * uiButton.disabledColor.g);
            colorDisabledColor.Add(255f * uiButton.disabledColor.b);
            colorDisabledColor.Add(255f * uiButton.disabledColor.a);
            subJSON.AddField("disabledColor", colorDisabledColor);


            JSONObject colorNormal = new JSONObject(JSONObject.Type.ARRAY);

            if (uiButton.tweenTarget != null)
            {
                var mWidget = uiButton.tweenTarget.GetComponent <UIWidget>();
                colorNormal.Add(255f * mWidget.color.r);
                colorNormal.Add(255f * mWidget.color.g);
                colorNormal.Add(255f * mWidget.color.b);
                colorNormal.Add(255f * mWidget.color.a);
                subJSON.AddField("normalColor", colorNormal);
            }


            UISprite uiSprite = uiButton.GetComponent(typeof(UISprite)) as UISprite;

            if (uiSprite != null && uiSprite.atlas != null)
            {
                Material  atlasMaterial = uiSprite.atlas.spriteMaterial;
                Texture2D texture2D     = (Texture2D)atlasMaterial.GetTexture("_MainTex");
                if (texture2D != null)
                {
                    string path = AssetDatabase.GetAssetPath(texture2D.GetInstanceID());

                    if (uiButton.normalSprite != null && uiButton.normalSprite != "")
                    {
                        string normalSpriteKey = this.getStateSprite(context, uiSprite, uiButton.normalSprite);
                        if (normalSpriteKey != null)
                        {
                            subJSON.AddField("normalSprite", normalSpriteKey);
                        }
                        else
                        {
                            subJSON.AddField("normalSprite", new JSONObject(JSONObject.Type.NULL));
                        }
                    }
                    else
                    {
                        subJSON.AddField("normalSprite", new JSONObject(JSONObject.Type.NULL));
                    }

                    if (uiButton.pressedSprite != null && uiButton.pressedSprite != "")
                    {
                        string pressedSpriteKey = this.getStateSprite(context, uiSprite, uiButton.pressedSprite);
                        if (pressedSpriteKey != null)
                        {
                            subJSON.AddField("pressedSprite", pressedSpriteKey);
                        }
                        else
                        {
                            subJSON.AddField("pressedSprite", new JSONObject(JSONObject.Type.NULL));
                        }
                    }
                    else
                    {
                        subJSON.AddField("pressedSprite", new JSONObject(JSONObject.Type.NULL));
                    }

                    if (uiButton.disabledSprite != null && uiButton.disabledSprite != "")
                    {
                        string disabledSpriteKey = this.getStateSprite(context, uiSprite, uiButton.disabledSprite);
                        if (disabledSpriteKey != null)
                        {
                            subJSON.AddField("disabledSprite", disabledSpriteKey);
                        }
                        else
                        {
                            subJSON.AddField("disabledSprite", new JSONObject(JSONObject.Type.NULL));
                        }
                    }
                    else
                    {
                        subJSON.AddField("disabledSprite", new JSONObject(JSONObject.Type.NULL));
                    }
                }
                else
                {
                    subJSON.AddField("normalSprite", new JSONObject(JSONObject.Type.NULL));
                    subJSON.AddField("pressedSprite", new JSONObject(JSONObject.Type.NULL));
                    subJSON.AddField("disabledSprite", new JSONObject(JSONObject.Type.NULL));
                }
            }
            else
            {
                subJSON.AddField("normalSprite", new JSONObject(JSONObject.Type.NULL));
                subJSON.AddField("pressedSprite", new JSONObject(JSONObject.Type.NULL));
                subJSON.AddField("disabledSprite", new JSONObject(JSONObject.Type.NULL));
            }

            subJSON.AddField("active", uiButton.enabled);

            json.AddField("data", subJSON);

            return(json);
        }
        public int TraverseBlendTree(ref BlendTree tree)
        {
            bool treeExist;
            var  treeInfo = controllerInfo.blendTrees.AddObject(tree, out treeExist);

            if (treeExist)
            {
                return(treeInfo.Key);
            }
            var json = treeInfo.Value;

            json.AddField("name", tree.name);

            var childrenJSON = new JSONObject(JSONObject.Type.ARRAY);

            json.AddField("children", childrenJSON);
            ChildMotion[] children = tree.children;
            for (int i = 0; i < children.Length; i++)
            {
                var childJSON = new JSONObject(JSONObject.Type.OBJECT);
                childrenJSON.Add(childJSON);
                var    motionJSON = new JSONObject(JSONObject.Type.OBJECT);
                Motion motion     = children[i].motion;
                if (motion.GetType() == typeof(AnimationClip))
                {
                    AnimationClip clip = motion as AnimationClip;
                    motionJSON.AddField("type", "AnimationClip");
                    motionJSON.AddField("id", HandleAnimationClip(ref clip));
                }
                else if (motion.GetType() == typeof(BlendTree))
                {
                    BlendTree sub = motion as BlendTree;
                    motionJSON.AddField("type", "BlendTree");
                    motionJSON.AddField("id", TraverseBlendTree(ref sub));
                }
                childJSON.AddField("motion", motionJSON);
                childJSON.AddField("timeScale", children[i].timeScale);
            }

            var blendJSON = new JSONObject(JSONObject.Type.OBJECT);

            json.AddField("blend", blendJSON);
            blendJSON.AddField("type", (int)tree.blendType);
            if (tree.blendType == BlendTreeType.Simple1D)
            {
                bool temp;
                blendJSON.AddField("parameter", controllerInfo.parameters.AddObject(tree.blendParameter, out temp).Key);
                var thresholdsJSON = new JSONObject(JSONObject.Type.ARRAY);
                blendJSON.AddField("thresholds", thresholdsJSON);
                for (int i = 0; i < children.Length; i++)
                {
                    thresholdsJSON.Add(children[i].threshold);
                }
                blendJSON.AddField("minThreshold", tree.minThreshold);
                blendJSON.AddField("maxThreshold", tree.maxThreshold);
            }
            else if (tree.blendType == BlendTreeType.SimpleDirectional2D || tree.blendType == BlendTreeType.FreeformDirectional2D || tree.blendType == BlendTreeType.FreeformCartesian2D)
            {
                bool temp;
                blendJSON.AddField("parameterX", controllerInfo.parameters.AddObject(tree.blendParameter, out temp).Key);
                blendJSON.AddField("parameterY", controllerInfo.parameters.AddObject(tree.blendParameterY, out temp).Key);
                var positionsJSON = new JSONObject(JSONObject.Type.ARRAY);
                blendJSON.AddField("positions", positionsJSON);
                for (int i = 0; i < children.Length; i++)
                {
                    var pos     = children[i].position;
                    var posJSON = new JSONObject(JSONObject.Type.ARRAY);
                    positionsJSON.Add(posJSON);
                    posJSON.Add(pos.x);
                    posJSON.Add(pos.y);
                }
            }
            else if (tree.blendType == BlendTreeType.Direct)
            {
                var paramJSON = new JSONObject(JSONObject.Type.ARRAY);
                blendJSON.AddField("parameters", paramJSON);
                for (int i = 0; i < children.Length; i++)
                {
                    if (children[i].directBlendParameter != null)
                    {
                        paramJSON.Add(children[i].directBlendParameter);
                    }
                    else
                    {
                        paramJSON.Add(new JSONObject(JSONObject.Type.NULL));
                    }
                }
            }
            return(treeInfo.Key);
        }
示例#15
0
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
            JSONObject data = new JSONObject(JSONObject.Type.OBJECT);

            json.AddField("type", "LineRenderer");
            json.AddField("data", data);

            data.AddField("active", renderer.enabled);
            JSONObject materialArray = new JSONObject(JSONObject.Type.ARRAY);

            Material[] materials = renderer.sharedMaterials;
            foreach (Material material in materials)
            {
                WXMaterial materialConverter = new WXMaterial(material, renderer);
                string     materialPath      = materialConverter.Export(context.preset);
                materialArray.Add(materialPath);
                context.AddResource(materialPath);
            }
            data.AddField("materials", materialArray);

            ShadowCastingMode mode        = renderer.shadowCastingMode;
            StaticEditorFlags shadowFlags = GameObjectUtility.GetStaticEditorFlags(renderer.gameObject);

#if UNITY_2019_2_OR_NEWER
            if (mode == ShadowCastingMode.Off || (shadowFlags & StaticEditorFlags.ContributeGI) != 0)
#else
            if (mode == ShadowCastingMode.Off || (shadowFlags & StaticEditorFlags.LightmapStatic) != 0)
#endif
            {
                data.AddField("castShadow", false);
            }
            else
            {
                data.AddField("castShadow", true);
            }

            bool receiveShadow = renderer.receiveShadows;
            data.AddField("receiveShadow", receiveShadow);
            int alignmentNum = 0;
#if UNITY_2017_1_OR_NEWER
            LineAlignment alignment = renderer.alignment;
            switch (alignment)
            {
            case LineAlignment.View:
                alignmentNum = 0;
                break;

#if UNITY_2018_2_OR_NEWER
            case LineAlignment.TransformZ:
                alignmentNum = 1;
                break;
#else
            case LineAlignment.Local:
                alignmentNum = 1;
                break;
#endif
            }
            data.AddField("alignment", alignmentNum);
#endif
            Color startColor = renderer.startColor;
            data.AddField("startColor", parseColor(startColor));

            Color endColor = renderer.endColor;
            data.AddField("endColor", parseColor(endColor));

            float startWidth = renderer.startWidth;
            data.AddField("startWidth", startWidth);

            float endWidth = renderer.endWidth;
            data.AddField("endWidth", endWidth);

            LineTextureMode textureMode    = renderer.textureMode;
            int             textureModeNum = 0;
            switch (textureMode)
            {
            case LineTextureMode.Stretch:
                textureModeNum = 0;
                break;

            case LineTextureMode.Tile:
                textureModeNum = 1;
                break;
            }
            data.AddField("textureMode", textureModeNum);

            int positionCount = 0;
#if UNITY_2017_1_OR_NEWER
            positionCount = renderer.positionCount;
#else
            positionCount = renderer.numPositions;
#endif
            Vector3[] positionsVec = new Vector3[positionCount];
            renderer.GetPositions(positionsVec);
            JSONObject jSONObject = new JSONObject(JSONObject.Type.ARRAY);
            for (int i = 0; i < positionCount; i++)
            {
                JSONObject vec = new JSONObject(JSONObject.Type.ARRAY);
                vec.Add(positionsVec[i].x * -1f);
                vec.Add(positionsVec[i].y);
                vec.Add(positionsVec[i].z);
                jSONObject.Add(vec);
            }
            data.AddField("positions", jSONObject);

            data.AddField("numCapVertices", renderer.numCapVertices);
            data.AddField("numCornerVertices", renderer.numCornerVertices);
#if UNITY_2017_1_OR_NEWER
            data.AddField("loop", renderer.loop);
#endif
            data.AddField("useWorldSpace", renderer.useWorldSpace);

            data.AddField("gColor", GetGradientColor(renderer.colorGradient));

            data.AddField("widthCurve", GetCurveData(renderer.widthCurve));
            data.AddField("widthMultiplier", renderer.widthMultiplier);

            return(json);
        }
        protected override JSONObject ExportResource(ExportPreset preset)
        {
            WXHierarchyContext hierarchyContext = new WXHierarchyContext(preset, prefabPath);

            // 初始化输出的JSON对象
            JSONObject prefabJSONObject = new JSONObject(JSONObject.Type.OBJECT);

            JSONObject metaJson = new JSONObject(JSONObject.Type.OBJECT);

            prefabJSONObject.AddField("meta", metaJson);


            // 填充meta
            metaJson.AddField("name", exportName);
            metaJson.AddField("type", "2D");

            if (exportAsScene)
            {
                JSONObject configJson = new JSONObject(JSONObject.Type.OBJECT);
                metaJson.AddField("config", configJson);

                JSONObject resolutionJson = new JSONObject(JSONObject.Type.ARRAY);


                Canvas uiRoot = getUIRoot(prefabRoot);
                if (uiRoot != null)
                {
                    var canvasScaler = uiRoot.GetComponent <CanvasScaler>();
                    if (canvasScaler != null && canvasScaler.uiScaleMode == CanvasScaler.ScaleMode.ScaleWithScreenSize)
                    {
                        resolutionJson.Add(canvasScaler.referenceResolution.x * uiRoot.transform.localScale.x);
                        resolutionJson.Add(canvasScaler.referenceResolution.y * uiRoot.transform.localScale.y);
                        if (canvasScaler.screenMatchMode == CanvasScaler.ScreenMatchMode.MatchWidthOrHeight)
                        {
                            if (canvasScaler.matchWidthOrHeight > 0.75)
                            {
                                configJson.AddField("adaptationType", 0); //以高度适配
                            }
                            else if (canvasScaler.matchWidthOrHeight < 0.25)
                            {
                                configJson.AddField("adaptationType", 1); //以宽适配
                            }
                            // 默认居中
                        }
                    }
                    else
                    {
                        RectTransform ct = uiRoot.transform as RectTransform;
                        resolutionJson.Add(ct.rect.width);
                        resolutionJson.Add(ct.rect.height);
                    }
                }
                else
                {
                    // 无root情况,使用默认大小
                    resolutionJson.Add(1280);
                    resolutionJson.Add(720);
                }


                configJson.AddField("resolution", resolutionJson);
            }

            //todo add a empty object in prefabRoot。自研引擎的场景根节点不支持挂载componets, 所以强制增加一个空节点
            //Canvas root = getUIRoot(prefabRoot);
            //if(root != null)
            //{
            //    Debug.Log("ugui root is canvas. Add an empty gameobject.");
            //    GameObject newroot = new GameObject();
            //    root.transform.parent = newroot.transform;
            //    prefabRoot = newroot;
            //} else {
            //    Debug.Log("ugui root is not canvas.");
            //}


            // 开始遍历
            WXEntity rootEntity = hierarchyContext.IterateGameObject(prefabRoot);

            prefabJSONObject.AddField("gameObjectList", hierarchyContext.GetGameObjectListJSON());
            prefabJSONObject.AddField("componentList", hierarchyContext.GetComponentListJSON());

            JSONObject metadata = new JSONObject(JSONObject.Type.OBJECT);

            prefabJSONObject.AddField("version", 2);
            //Debug.Log("Export Prefab " + prefabPath + "  " + hierarchyContext.resourceList.Count);

            foreach (string resource in hierarchyContext.resourceList)
            {
                AddDependencies(resource);
            }

            return(prefabJSONObject);
        }
        private void GetLightConfig(JSONObject propsObj, WXHierarchyContext context)
        {
            if (RenderSettings.ambientMode == AmbientMode.Skybox)
            {
                propsObj.AddField("ambientMode", 0);
            }
            else if (RenderSettings.ambientMode == AmbientMode.Trilight)
            {
                propsObj.AddField("ambientMode", 1);
            }
            else // if (RenderSettings.ambientMode == AmbientMode.Flat)
            {
                propsObj.AddField("ambientMode", 2);
            }
            Color      ambientLight    = RenderSettings.ambientLight;
            JSONObject ambientLightObj = new JSONObject(JSONObject.Type.ARRAY);

            ambientLightObj.Add(ambientLight.r);
            ambientLightObj.Add(ambientLight.g);
            ambientLightObj.Add(ambientLight.b);
            propsObj.AddField("ambientColor", ambientLightObj);
            propsObj.AddField("ambientIntensity", RenderSettings.ambientIntensity);
            JSONObject ambientSkyColorObj = new JSONObject(JSONObject.Type.ARRAY);

            ambientSkyColorObj.Add(RenderSettings.ambientSkyColor.r);
            ambientSkyColorObj.Add(RenderSettings.ambientSkyColor.g);
            ambientSkyColorObj.Add(RenderSettings.ambientSkyColor.b);
            ambientSkyColorObj.Add(RenderSettings.ambientSkyColor.a);
            propsObj.AddField("ambientSkyColor", ambientSkyColorObj);

            JSONObject ambientEquatorColorObj = new JSONObject(JSONObject.Type.ARRAY);

            ambientEquatorColorObj.Add(RenderSettings.ambientEquatorColor.r);
            ambientEquatorColorObj.Add(RenderSettings.ambientEquatorColor.g);
            ambientEquatorColorObj.Add(RenderSettings.ambientEquatorColor.b);
            ambientEquatorColorObj.Add(RenderSettings.ambientEquatorColor.a);
            propsObj.AddField("ambientEquatorColor", ambientEquatorColorObj);

            JSONObject ambientGroundColorObj = new JSONObject(JSONObject.Type.ARRAY);

            ambientGroundColorObj.Add(RenderSettings.ambientGroundColor.r);
            ambientGroundColorObj.Add(RenderSettings.ambientGroundColor.g);
            ambientGroundColorObj.Add(RenderSettings.ambientGroundColor.b);
            ambientGroundColorObj.Add(RenderSettings.ambientGroundColor.a);
            propsObj.AddField("ambientGroundColor", ambientGroundColorObj);

            object Rs = RenderSettings.defaultReflectionMode;

            if (RenderSettings.defaultReflectionMode == DefaultReflectionMode.Custom)
            {
                //saveCubeMapFile(RenderSettings.customReflection, propsObj, false, null);
                propsObj.AddField("reflectionIntensity", RenderSettings.reflectionIntensity);
            }
            else
            {
                propsObj.AddField("reflectionResolution", RenderSettings.defaultReflectionResolution);
            }

            // saveLightMapFile(propsObj);
            propsObj.AddField("fogMode", 0);
            if (RenderSettings.fog)
            {
                JSONObject jSONObject5 = new JSONObject(JSONObject.Type.ARRAY);
                Color      fogColor    = RenderSettings.fogColor;
                jSONObject5.Add(fogColor.r);
                jSONObject5.Add(fogColor.g);
                jSONObject5.Add(fogColor.b);
                propsObj.AddField("fogColor", jSONObject5);
                propsObj.AddField("fogMode", (int)RenderSettings.fogMode);
            }
            if (RenderSettings.fogMode == FogMode.Linear)
            {
                propsObj.AddField("fogStart", RenderSettings.fogStartDistance);
                propsObj.AddField("fogRange", RenderSettings.fogEndDistance - RenderSettings.fogStartDistance);
            }
            else
            {
                propsObj.AddField("fogDensity", RenderSettings.fogDensity);
            }
            if (RenderSettings.skybox != null)
            {
                WXMaterial materialConverter = new WXMaterial(RenderSettings.skybox, null);
                propsObj.AddField("skybox", AddDependencies(materialConverter));
            }
            else
            {
                propsObj.AddField("skybox", new JSONObject(JSONObject.Type.NULL));
            }

            // lightMapMode
            JSONObject subtractiveShadowColorObj = new JSONObject(JSONObject.Type.ARRAY);

#if UNITY_5_6_OR_NEWER
            Color subtractiveShadowColor = RenderSettings.subtractiveShadowColor;
#else
            // before 5.5 use default Color
            Color subtractiveShadowColor = new Color(0.42f, 0.48f, 0.63f, 1f);
#endif
            subtractiveShadowColorObj.Add(subtractiveShadowColor.r);
            subtractiveShadowColorObj.Add(subtractiveShadowColor.g);
            subtractiveShadowColorObj.Add(subtractiveShadowColor.b);
            subtractiveShadowColorObj.Add(subtractiveShadowColor.a);
            propsObj.AddField("subtractiveShadowColor", subtractiveShadowColorObj);


            bool           shadowMaskFlag   = false;
            JSONObject     lightMapDatasObj = new JSONObject(JSONObject.Type.ARRAY);
            LightmapData[] lightmaps        = LightmapSettings.lightmaps;
            if (lightmaps != null && lightmaps.Length != 0)
            {
                for (int i = 0; i < lightmaps.Length; i++)
                {
                    LightmapData lightmap = lightmaps[i];

                    JSONObject lightMapDescObj = new JSONObject(JSONObject.Type.OBJECT);
#if UNITY_5_6_OR_NEWER
                    if (
                        lightmap.lightmapColor == null ||
                        "" == AssetDatabase.GetAssetPath(lightmap.lightmapColor.GetInstanceID())
                        )
                    {
                        continue;
                    }

                    if (lightmap.shadowMask)
                    {
                        shadowMaskFlag = true;
                        WXLightMap textureConverter = new WXLightMap(lightmap.shadowMask);
                        lightMapDescObj.AddField("shadowMask", AddDependencies(textureConverter));

                        WXLightMap textureConverter2 = new WXLightMap(lightmap.lightmapColor);
                        lightMapDescObj.AddField("color", AddDependencies(textureConverter2));
                    }
                    else
                    {
                        WXLightMap textureConverter = new WXLightMap(lightmap.lightmapColor);
                        lightMapDescObj.AddField("color", AddDependencies(textureConverter));
                    }
#else
                    if (
                        lightmap.lightmapLight == null ||
                        "" == AssetDatabase.GetAssetPath(lightmap.lightmapLight.GetInstanceID())
                        )
                    {
                        continue;
                    }

                    WXLightMap textureConverter = new WXLightMap(lightmap.lightmapLight);
                    lightMapDescObj.AddField("color", AddDependencies(textureConverter));
#endif
                    lightMapDatasObj.Add(lightMapDescObj);
                }
            }

            propsObj.AddField("lightMapDatas", lightMapDatasObj);

            // 0:subtractive 1:shadowMask
            propsObj.AddField("lightMapType", shadowMaskFlag ? (int)LightMapType.ShadowMask : (int)LightMapType.Subtractive);
        }
        protected override JSONObject ExportResource(ExportPreset preset)
        {
            if (shader == null)
            {
                return(null);
            }

            // .effect
            JSONObject jsonFile = new JSONObject(JSONObject.Type.OBJECT);

            JSONObject m_shaderProperties = new JSONObject(JSONObject.Type.ARRAY);

            foreach (property p in this.properties)
            {
                JSONObject m_property = new JSONObject(JSONObject.Type.OBJECT);
                m_property.AddField("key", p.key);
                m_property.AddField("type", p.type);
                m_property.AddField("default", p.defaultValue);
                m_shaderProperties.Add(m_property);
            }

            JSONObject m_textures = new JSONObject(JSONObject.Type.ARRAY);

            foreach (property p in this.textures)
            {
                JSONObject m_property = new JSONObject(JSONObject.Type.OBJECT);
                m_property.AddField("key", p.key + "_ST");
                m_property.AddField("type", "Vector4");
                JSONObject defaultValue = new JSONObject(JSONObject.Type.ARRAY);
                defaultValue.Add(1); defaultValue.Add(1);
                defaultValue.Add(0); defaultValue.Add(0);
                m_property.AddField("default", defaultValue);
                m_shaderProperties.Add(m_property);

                JSONObject m_texture = new JSONObject(JSONObject.Type.OBJECT);
                m_texture.AddField("key", p.key);
                m_texture.AddField("type", p.type);
                m_texture.AddField("default", p.defaultValue);
                m_textures.Add(m_texture);
            }
            jsonFile.SetField("shaderProperties", m_shaderProperties);
            jsonFile.SetField("textures", m_textures);
            jsonFile.SetField("defaultRenderQueue", 2000);
            JSONObject m_passes = new JSONObject(JSONObject.Type.ARRAY);
            JSONObject m_pass   = new JSONObject(JSONObject.Type.OBJECT);

            m_pass.SetField("lightMode", "ForwardBase");
            m_pass.SetField("useMaterialRenderStates", false);

            m_pass.SetField("renderStates", new JSONObject(JSONObject.Type.OBJECT));

            JSONObject m_compileFlags = new JSONObject(JSONObject.Type.ARRAY);

            m_compileFlags.Add("Skin");
            m_compileFlags.Add("Particle");
            m_compileFlags.Add("Line");
            m_compileFlags.Add("Trail");
            m_pass.SetField("compileFlags", m_compileFlags);

            JSONObject m_multiCompile = new JSONObject(JSONObject.Type.ARRAY);

            m_pass.SetField("multiCompile", m_multiCompile);

            m_passes.Add(m_pass);
            jsonFile.SetField("passes", m_passes);

            JSONObject metadata = new JSONObject(JSONObject.Type.OBJECT);

            metadata.AddField("version", 1);

            //if (BeefBall.currentExportPreset.configs.ContainsKey("GenShaderTemplate")
            //&& (bool)BeefBall.currentExportPreset.configs["GenShaderTemplate"])
            //{
            string vs_uid = AddFile(new WXVertexFile(this));

            vs_uid = "." + vs_uid.Substring(vs_uid.LastIndexOf('/'));
            string fs_uid = AddFile(new WXPixelFile(this));

            fs_uid = "." + fs_uid.Substring(fs_uid.LastIndexOf('/'));

            m_pass.SetField("vs", vs_uid);
            m_pass.SetField("ps", fs_uid);
            //}

            var editorInfo = new JSONObject(JSONObject.Type.OBJECT);

            editorInfo.AddField("assetVersion", 2);

            jsonFile.AddField("editorInfo", editorInfo);
            return(jsonFile);
        }
        protected override void DoExport()
        {
            EditorUtility.ClearProgressBar();
            BridgeExport.isProcessing = false;

            List <string> allRecursiveAssets = new List <string>();

            // string choosedPath = GetExportPath();
            // string savePath = Path.Combine(choosedPath, "Assets/");
            var savePath = Path.Combine(ExportStore.storagePath, "Assets/");

            updateRecourcesDir();

            int totalCount = 0;

            string [] arr_dir = dirs.ToArray();

            JSONObject jsonConfig = new JSONObject(JSONObject.Type.ARRAY);

            if (arr_dir.Length > 0)
            {
                for (int index = 0; index < supportedTypes.Length; index++)
                {
                    string   filter = "t:" + supportedTypes[index];
                    string[] guids  = AssetDatabase.FindAssets(filter, arr_dir);
                    // Debug.Log(guids.Length);
                    if (guids.Length == 0)
                    {
                        continue;
                    }

                    JSONObject category = new JSONObject(JSONObject.Type.OBJECT);
                    JSONObject data     = new JSONObject(JSONObject.Type.ARRAY);
                    category.AddField("type", supportedTypes[index]);
                    category.AddField("files", data);

                    var t = 0;
                    HashSet <string> setFiles = new HashSet <string>();
                    for (int i = 0; i < guids.Length; i++)
                    {
                        string path = AssetDatabase.GUIDToAssetPath(guids[i]);
                        if (path.StartsWith("Assets"))
                        {
                            path = path.Substring(6);
                        }
                        string absolutePath = Path.Combine(Application.dataPath, path);
                        // #if UNITY_EDITOR_WIN
                        // string absolutePath = Application.dataPath + "\\" + path;
                        // #else
                        // string absolutePath = Application.dataPath + "/" + path;
                        // #endif

                        // string filename = System.IO.Path.GetFileName(absolutePath);

                        string copyToPath = Path.Combine(savePath, path);
                        // #if UNITY_EDITOR_WIN
                        // string copyToPath = savePath + "\\" + path;
                        // #else
                        // string copyToPath = savePath + "/" + path;
                        // #endif

                        string extension = System.IO.Path.GetExtension(path);
                        if (setExclude.Contains(extension))
                        {
                            continue;
                        }

                        if (supportedTypes[index] != "GameObject")
                        {
                            #if USE_RAW_MODE
                            string        projpath    = "Assets" + path;
                            WXRawResource rawResource = new WXRawResource(projpath);
                            string        ret_path    = rawResource.Export(this);
                            allRecursiveAssets.Add(ret_path);
                            #else
                            wxFileUtil.CopyFile(absolutePath, copyToPath);
                            #endif
                        }

                        JSONObject fileInfo = new JSONObject(JSONObject.Type.OBJECT);
                        // fileInfo.AddField("key", Path.GetFileNameWithoutExtension(filename));
                        string key = getResourcePath(path);
                        if (setFiles.Contains(key))
                        {
                            continue;
                        }
                        else
                        {
                            setFiles.Add(key);
                        }
                        fileInfo.AddField("key", key);
                        fileInfo.AddField("name", "Assets" + path);
                        data.Add(fileInfo);
                        totalCount++;
                        EditorUtility.DisplayProgressBar("原始资源导出", "", t++ / guids.Length);
                    }
                    jsonConfig.Add(category);
                }
            }
            #if USE_RAW_MODE
            string tempConfigFile = Path.Combine(Application.dataPath, "Resources.json");
            wxFileUtil.SaveJsonFile(jsonConfig, tempConfigFile);
            string        configpath   = "Assets/Resources.json";
            WXRawResource rawConfig    = new WXRawResource(configpath);
            string        ret_cfg_path = rawConfig.Export(this);
            allRecursiveAssets.Add(ret_cfg_path);
            File.Delete(tempConfigFile);
            #endif
            // string content = jsonConfig.ToString();
            // ExportStore.AddTextFile(configpath, content, WXUtility.GetMD5FromString(content));
            // List<string> useConfig = new List<string>();
            // useConfig.Add(configpath);
            // ExportStore.AddResource(configpath, "raw", null, useConfig);
            // allRecursiveAssets.Add(configpath);


            ExportStore.GenerateResourcePackage(
                "WXResources",
                allRecursiveAssets
                );

            EditorUtility.ClearProgressBar();
            Debug.Log("导出成功,总共导出文件个数:" + totalCount);
        }
        public WXEffect(Shader _shader)
        {
            this.shader     = (Shader)_shader;
            this.properties = new List <property>();
            this.textures   = new List <property>();
            int instanceID = shader.GetInstanceID();

            unityAssetPath = AssetDatabase.GetAssetPath(instanceID);

            this.property_count = ShaderUtil.GetPropertyCount(shader);

            for (int i = 0; i < property_count; i++)
            {
                string name     = ShaderUtil.GetPropertyName(shader, i);
                string typeName = "";
                ShaderUtil.ShaderPropertyType type = ShaderUtil.GetPropertyType(shader, i);
                JSONObject defaultValue            = new JSONObject(0);
                switch (type)
                {
                case ShaderUtil.ShaderPropertyType.Float:
                case ShaderUtil.ShaderPropertyType.Range:
                    typeName     = "Float";
                    defaultValue = new JSONObject(JSONObject.Type.ARRAY);
                    defaultValue.Add(0);
                    break;

                case ShaderUtil.ShaderPropertyType.Vector:
                    typeName     = "Vector4";
                    defaultValue = new JSONObject(JSONObject.Type.ARRAY);
                    defaultValue.Add(0); defaultValue.Add(0);
                    defaultValue.Add(0); defaultValue.Add(1);
                    break;

                case ShaderUtil.ShaderPropertyType.Color:
                    typeName     = "Vector4";
                    defaultValue = new JSONObject(JSONObject.Type.ARRAY);
                    defaultValue.Add(1); defaultValue.Add(1);
                    defaultValue.Add(1); defaultValue.Add(1);
                    break;

                case ShaderUtil.ShaderPropertyType.TexEnv:
                    typeName     = "unresolved_tex";
                    defaultValue = JSONObject.CreateStringObject("white");
                    break;
                }
                if (typeName == "")
                {
                    continue;
                }
                if (typeName == "unresolved_tex")
                {
                    UnityEngine.Rendering.TextureDimension texType = ShaderUtil.GetTexDim(shader, i);
                    switch (texType)
                    {
                    case UnityEngine.Rendering.TextureDimension.Tex2D:
                        typeName = "Texture2D";
                        break;

                    case UnityEngine.Rendering.TextureDimension.Cube:
                        typeName = "TextureCube";
                        break;
                    }
                    if (typeName == "unresolved_tex")
                    {
                        continue;
                    }
                    this.textures.Add(new property {
                        key = name, type = typeName, defaultValue = defaultValue
                    });
                }
                else
                {
                    this.properties.Add(new property {
                        key = name, type = typeName, defaultValue = defaultValue
                    });
                }
            }
        }
示例#21
0
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
            JSONObject data = new JSONObject(JSONObject.Type.OBJECT);

            json.AddField("type", getTypeName());
            json.AddField("data", data);
            data.AddField("active", true);

            JSONObject scriptList = WXUIUCommonScript.AddInteractionScript(go, entity, context, false);

            data.AddField("scriptList", scriptList);

            Image targetGraphic = (Image)input.targetGraphic;

            if (targetGraphic != null)
            {
                data.AddField("targetGraphic", context.AddComponent(new WXUIUSpriteScript(targetGraphic, go, entity), targetGraphic));
            }


            JSONObject onValueChangedList = new JSONObject(JSONObject.Type.ARRAY);

            data.AddField("onValueChanged", onValueChangedList);

            int onChangeCount = input.onValueChanged.GetPersistentEventCount();

            for (int i = 0; i < onChangeCount; i++)
            {
                var __onChange = new JSONObject(JSONObject.Type.OBJECT);

                var target     = input.onValueChanged.GetPersistentTarget(i);
                var targetType = target.GetType().ToString();
                __onChange.AddField("targetType", targetType);
                if (targetType == "UnityEngine.GameObject")
                {
                    GameObject _go = (GameObject)target;
                    __onChange.AddField("target", WXUIUCommonScript.AddComponent(_go, entity, context));
                }
                else
                { //todo 其他类型的到时候再考虑
                    MonoBehaviour _target = (MonoBehaviour)target;
                    __onChange.AddField("target", context.AddComponent(new WXEngineMonoBehaviour(_target), _target));
                }


                __onChange.AddField("method", input.onValueChanged.GetPersistentMethodName(i));

                onValueChangedList.Add(__onChange);
            }

            JSONObject onEditEndList = new JSONObject(JSONObject.Type.ARRAY);

            data.AddField("onEditEnd", onEditEndList);

            int onEidtEndCount = input.onEndEdit.GetPersistentEventCount();

            for (int i = 0; i < onEidtEndCount; i++)
            {
                var __onEnd = new JSONObject(JSONObject.Type.OBJECT);

                var target     = input.onEndEdit.GetPersistentTarget(i);
                var targetType = target.GetType().ToString();
                __onEnd.AddField("targetType", targetType);
                if (targetType == "UnityEngine.GameObject")
                {
                    GameObject _go = (GameObject)target;
                    __onEnd.AddField("target", WXUIUCommonScript.AddComponent(_go, entity, context));
                }
                else
                { //todo 其他类型的到时候再考虑
                    MonoBehaviour _target = (MonoBehaviour)target;
                    __onEnd.AddField("target", context.AddComponent(new WXEngineMonoBehaviour(_target), _target));
                }


                __onEnd.AddField("method", input.onEndEdit.GetPersistentMethodName(i));

                onEditEndList.Add(__onEnd);
            }

            Text placeHolder = (Text)input.placeholder;

            if (placeHolder != null)
            {
                JSONObject color = new JSONObject(JSONObject.Type.ARRAY);
                color.Add(255f * placeHolder.color.r);
                color.Add(255f * placeHolder.color.g);
                color.Add(255f * placeHolder.color.b);
                color.Add(255f * placeHolder.color.a);
                data.AddField("promptColor", color);
                input.placeholder.gameObject.SetActive(false);
            }


            data.AddField("ref", context.AddComponent(new WXUIUInputField(input, go, entity), input));

            return(json);
        }
        private byte[] WriteMeshFile(ref JSONObject metadata)
        {
            MemoryStream fileStream = new MemoryStream();

            string             meshName     = mesh.name;
            WXMeshVertexLayout vertexLayout = new WXMeshVertexLayout(mesh);
            ushort             subMeshCount = (ushort)mesh.subMeshCount;

            long vertexStart  = 0L;
            long vertexLength = 0L;
            long indiceStart  = 0L;
            long indiceLength = 0L;

            vertexStart = fileStream.Position;
            Vector3 vertexPositionMax = new Vector3(0, 0, 0);

            for (int j = 0; j < mesh.vertexCount; j++)
            {
                Vector3 vector = mesh.vertices[j];
                wxFileUtil.WriteData(fileStream, vector.x * -1f, vector.y, vector.z);
                vertexPositionMax.Set(vertexPositionMax.x + vector.x * -1f, vertexPositionMax.y + vector.y, vertexPositionMax.z + vector.z);

                if (vertexLayout.NORMAL)
                {
                    Vector3 vector2 = mesh.normals[j];
                    wxFileUtil.WriteData(fileStream, vector2.x * -1f, vector2.y, vector2.z);
                }
                if (vertexLayout.COLOR)
                {
                    Color color = mesh.colors[j];
                    wxFileUtil.WriteData(fileStream, color.r, color.g, color.b, color.a);
                }
                if (vertexLayout.UV)
                {
                    Vector2 vector3 = mesh.uv[j];
                    wxFileUtil.WriteData(fileStream, vector3.x, vector3.y * -1f + 1f);
                }
                if (vertexLayout.UV1)
                {
                    Vector2 vector4 = mesh.uv2[j];
                    wxFileUtil.WriteData(fileStream, vector4.x, vector4.y * -1f + 1f);
                }
                if (vertexLayout.TANGENT)
                {
                    Vector4 vector5 = mesh.tangents[j];
                    wxFileUtil.WriteData(fileStream, vector5.x * -1f, vector5.y, vector5.z, vector5.w);
                }
            }
            vertexLength = fileStream.Position - vertexStart;

            indiceStart = fileStream.Position;
            int[] triangles = mesh.triangles;
            for (int j = 0; j < triangles.Length; j++)
            {
                wxFileUtil.WriteData(fileStream, (ushort)triangles[j]);
            }
            indiceLength = fileStream.Position - indiceStart;
            fileStream.Close();

            vertexPositionMax.Set(vertexPositionMax.x / mesh.vertices.Length, vertexPositionMax.y / mesh.vertices.Length, vertexPositionMax.z / mesh.vertices.Length);
            float capsuleRadius = CalCapsuleRadius(vertexPositionMax, mesh.vertices);

            JSONObject capsule = new JSONObject(JSONObject.Type.OBJECT);

            capsule.AddField("x", vertexPositionMax.x);
            capsule.AddField("y", vertexPositionMax.y);
            capsule.AddField("z", vertexPositionMax.z);
            capsule.AddField("radius", capsuleRadius);

            metadata.AddField("indiceFormat", 1);                              //   BIT16 = 1,BIT32 = 2
            metadata.AddField("vertexLayout", vertexLayout.GetLayoutString()); //"POSITION,NORMAL,COLOR,UV,BLENDWEIGHT,BLENDINDICES,TANGENT",
            metadata.AddField("vertexStart", 0);
            metadata.AddField("vertexLength", vertexLength);
            metadata.AddField("indiceStart", vertexLength);  // indice的偏移量
            metadata.AddField("indiceLength", indiceLength); // indice的长度
            metadata.AddField("capsule", capsule);
            metadata.AddField("version", 1);


            JSONObject subMeshs = new JSONObject(JSONObject.Type.ARRAY);

#if !UNITY_2017_1_OR_NEWER
            int indexStart = 0;
#endif
            for (int i = 0; i < subMeshCount; i++)
            {
                JSONObject subMeshObj = new JSONObject(JSONObject.Type.OBJECT);
#if UNITY_2017_1_OR_NEWER
                subMeshObj.AddField("start", mesh.GetIndexStart(i));
                subMeshObj.AddField("length", mesh.GetIndexCount(i));
#else
                subMeshObj.AddField("start", indexStart);
                subMeshObj.AddField("length", mesh.GetIndices(i).Length);
                indexStart += mesh.GetIndices(i).Length;
#endif
                subMeshs.Add(subMeshObj);
            }
            metadata.AddField("subMeshs", subMeshs);

            JSONObject boundBox       = new JSONObject(JSONObject.Type.OBJECT);
            JSONObject boundBoxCenter = new JSONObject(JSONObject.Type.ARRAY);
            boundBoxCenter.Add(mesh.bounds.center.x);
            boundBoxCenter.Add(mesh.bounds.center.y);
            boundBoxCenter.Add(mesh.bounds.center.z);
            JSONObject boundBoxSize = new JSONObject(JSONObject.Type.ARRAY);
            boundBoxSize.Add(mesh.bounds.size.x);
            boundBoxSize.Add(mesh.bounds.size.y);
            boundBoxSize.Add(mesh.bounds.size.z);
            boundBox.AddField("center", boundBoxCenter);
            boundBox.AddField("size", boundBoxSize);
            metadata.AddField("boundBox", boundBox);

            return(fileStream.ToArray());
        }
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
            JSONObject data = new JSONObject(JSONObject.Type.OBJECT);

            json.AddField("type", "MeshRenderer");
            json.AddField("data", data);

            data.AddField("active", renderer.enabled);

            JSONObject materialArray = new JSONObject(JSONObject.Type.ARRAY);

            Material[] materials     = renderer.sharedMaterials;
            int        materialCount = 0;

            foreach (Material material in materials)
            {
                if (material != null)
                {
                    WXMaterial materialConverter = new WXMaterial(material, renderer);
                    string     materialPath      = materialConverter.Export(context.preset);
                    materialArray.Add(materialPath);
                    context.AddResource(materialPath);
                    materialCount++;
                }
            }
            data.AddField("materials", materialArray);

            MeshFilter meshFilter = renderer.gameObject.GetComponent <MeshFilter> ();

            if (meshFilter != null && meshFilter.sharedMesh != null)
            {
                Mesh   mesh          = meshFilter.sharedMesh;
                WXMesh meshConverter = new WXMesh(mesh, materialCount);
                string meshPath      = meshConverter.Export(context.preset);
                data.AddField("mesh", meshPath);
                context.AddResource(meshPath);
            }
            else
            {
                ErrorUtil.ExportErrorReporter.create()
                .setGameObject(renderer.gameObject)
                .setHierarchyContext(context)
                .error(ErrorUtil.ErrorCode.MeshRenderer_MeshNotFound, "Mesh资源转换失败,没法拿到对应的MeshFilter或者它上面的mesh");
            }

            int        lightmapIndex  = renderer.lightmapIndex;
            JSONObject litmapScaleArr = new JSONObject(JSONObject.Type.ARRAY);

            data.AddField("lightMapScaleOffset", litmapScaleArr);
            litmapScaleArr.Add(renderer.lightmapScaleOffset.x);
            litmapScaleArr.Add(renderer.lightmapScaleOffset.y);
            litmapScaleArr.Add(renderer.lightmapScaleOffset.z);
            litmapScaleArr.Add(renderer.lightmapScaleOffset.w);
            data.AddField("lightMapIndex", lightmapIndex);

            ShadowCastingMode mode        = renderer.shadowCastingMode;
            StaticEditorFlags shadowFlags = GameObjectUtility.GetStaticEditorFlags(renderer.gameObject);

#if UNITY_2019_2_OR_NEWER
            if (mode == ShadowCastingMode.Off || (shadowFlags & StaticEditorFlags.ContributeGI) != 0)
#else
            if (mode == ShadowCastingMode.Off || (shadowFlags & StaticEditorFlags.LightmapStatic) != 0)
#endif
            {
                data.AddField("castShadow", false);
            }
            else
            {
                data.AddField("castShadow", true);
            }

            bool receiveShadow = renderer.receiveShadows;
            data.AddField("receiveShadow", receiveShadow);
            return(json);
        }
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
            JSONObject data = new JSONObject(JSONObject.Type.OBJECT);

            json.AddField("type", getTypeName());
            json.AddField("data", data);

            data.AddField("interactable", (bool)slider.interactable);
            data.AddField("transition", (int)slider.transition); // 0-3

            //   RectTransform sliderRect = slider.GetComponent<RectTransform>();
            //   sliderRect.pivot = new Vector2(0, 0);


            JSONObject colorPressed = new JSONObject(JSONObject.Type.ARRAY);
            var        pressedColor = slider.colors.pressedColor;

            colorPressed.Add(255f * pressedColor.r);
            colorPressed.Add(255f * pressedColor.g);
            colorPressed.Add(255f * pressedColor.b);
            colorPressed.Add(255f * pressedColor.a);
            data.AddField("pressedColor", colorPressed);

            JSONObject colorDisabled = new JSONObject(JSONObject.Type.ARRAY);
            var        disabledColor = slider.colors.disabledColor;

            colorDisabled.Add(255f * disabledColor.r);
            colorDisabled.Add(255f * disabledColor.g);
            colorDisabled.Add(255f * disabledColor.b);
            colorDisabled.Add(255f * disabledColor.a);
            data.AddField("disabledColor", colorDisabled);


            JSONObject colorNormal = new JSONObject(JSONObject.Type.ARRAY);
            var        normalColor = slider.colors.normalColor;

            colorNormal.Add(255f * normalColor.r);
            colorNormal.Add(255f * normalColor.g);
            colorNormal.Add(255f * normalColor.b);
            colorNormal.Add(255f * normalColor.a);
            data.AddField("normalColor", colorNormal);

            Image targetGraphic = (Image)slider.targetGraphic;

            if (targetGraphic != null)
            {
                data.AddField("targetGraphic", context.AddComponent(new WXUIUSpriteScript(targetGraphic, go, entity), targetGraphic));
            }

            SpriteState state = slider.spriteState;

            if (state.pressedSprite != null)
            {
                string pressedSpriteKey = this.getStateSprite(context, state.pressedSprite);
                if (pressedSpriteKey != null)
                {
                    data.AddField("pressedSprite", pressedSpriteKey);
                }
                else
                {
                    data.AddField("pressedSprite", new JSONObject(JSONObject.Type.NULL));
                }
            }

            if (state.disabledSprite != null)
            {
                string disabledSpriteKey = this.getStateSprite(context, state.disabledSprite);
                if (disabledSpriteKey != null)
                {
                    data.AddField("disabledSprite", disabledSpriteKey);
                }
                else
                {
                    data.AddField("disabledSprite", new JSONObject(JSONObject.Type.NULL));
                }
            }

            if (slider.fillRect != null)
            {
                data.AddField("fillRect", context.AddComponent(new WXUGUITransform2DComponent(slider.fillRect)));

                Image fillRectImage = (Image)slider.fillRect.transform.GetComponent <Image>();

                if (fillRectImage != null)
                {
                    RectTransform t = fillRectImage.transform as RectTransform;

                    if (slider.direction == Slider.Direction.LeftToRight)
                    {
                        t.pivot = new Vector2(0, 0);
                    }
                    if (slider.direction == Slider.Direction.RightToLeft)
                    {
                        t.pivot = new Vector2(1, 0);
                    }
                    if (slider.direction == Slider.Direction.TopToBottom)
                    {
                        t.pivot = new Vector2(0, 1);
                    }
                    if (slider.direction == Slider.Direction.BottomToTop)
                    {
                        t.pivot = new Vector2(0, 0);
                    }

                    data.AddField("fillRectImage", context.AddComponent(new WXUIUSpriteScript(fillRectImage, go, entity), fillRectImage));
                }
            }



            if (slider.handleRect != null)
            {
                data.AddField("handleRect", context.AddComponent(new WXUGUITransform2DComponent(slider.handleRect)));

                Image handleRectImage = (Image)slider.handleRect.transform.GetComponent <Image>();

                if (handleRectImage != null)
                {
                    data.AddField("handleRectImage", context.AddComponent(new WXUIUSpriteScript(handleRectImage, go, entity), handleRectImage));
                }
            }

            JSONObject onValueChangedList = new JSONObject(JSONObject.Type.ARRAY);

            data.AddField("onValueChanged", onValueChangedList);

            int onChangeCount = slider.onValueChanged.GetPersistentEventCount();

            for (int i = 0; i < onChangeCount; i++)
            {
                var __onChange = new JSONObject(JSONObject.Type.OBJECT);

                var target     = slider.onValueChanged.GetPersistentTarget(i);
                var targetType = target.GetType().ToString();
                __onChange.AddField("targetType", targetType);
                if (targetType == "UnityEngine.GameObject")
                {
                    GameObject _go = (GameObject)target;
                    __onChange.AddField("target", WXUIUCommonScript.AddComponent(_go, entity, context));
                }
                else
                { //todo 其他类型的到时候再考虑
                    MonoBehaviour _target = (MonoBehaviour)target;
                    __onChange.AddField("target", context.AddComponent(new WXEngineMonoBehaviour(_target), _target));
                }


                __onChange.AddField("method", slider.onValueChanged.GetPersistentMethodName(i));

                onValueChangedList.Add(__onChange);
            }



            data.AddField("direction", (int)slider.direction);

            data.AddField("maxValue", slider.maxValue);

            data.AddField("minValue", slider.minValue);

            data.AddField("normalizedValue", slider.normalizedValue);

            data.AddField("wholeNumbers", slider.wholeNumbers);

            data.AddField("value", slider.value);



            data.AddField("active", slider.IsActive());



            return(json);
        }
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            ParticleSystemRenderer particleSystemRenderer = particleSys.GetComponent <ParticleSystemRenderer>();

            JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
            JSONObject data = new JSONObject(JSONObject.Type.OBJECT);

            json.AddField("type", getTypeName());
            json.AddField("data", data);

            JSONObject materials = new JSONObject(JSONObject.Type.ARRAY);

            data.AddField("materials", materials);
            Material[] mats = particleSystemRenderer.sharedMaterials;
            foreach (Material material in mats)
            {
                if (material != null)
                {
                    WXMaterial materialConverter = new WXMaterial(material, particleSystemRenderer);
                    string     materialPath      = materialConverter.Export(context.preset);
                    materials.Add(materialPath);
                    context.AddResource(materialPath);
                }
            }

            JSONObject modCommon     = new JSONObject(JSONObject.Type.OBJECT);
            JSONObject modCommonData = new JSONObject(JSONObject.Type.OBJECT);

            data.AddField("common", modCommonData);

            modCommonData.AddField("startSize3D", particleSys.main.startSize3D);
            if (particleSys.main.startSize3D)
            {
                modCommonData.AddField("startSizeX", ParseMinMaxCurve(particleSys.main.startSizeX));
                modCommonData.AddField("startSizeY", ParseMinMaxCurve(particleSys.main.startSizeY));
                modCommonData.AddField("startSizeZ", ParseMinMaxCurve(particleSys.main.startSizeZ));
            }
            else
            {
                modCommonData.AddField("startSize", ParseMinMaxCurve(particleSys.main.startSize));
            }
            modCommonData.AddField("startColor", ParseMinMaxGradient(particleSys.main.startColor));
            modCommonData.AddField("startLifetime", ParseMinMaxCurve(particleSys.main.startLifetime));
            modCommonData.AddField("startRotation3D", particleSys.main.startRotation3D);
            if (particleSys.main.startRotation3D)
            {
                modCommonData.AddField("startRotationX", ParseMinMaxCurve(particleSys.main.startRotationX, (float)(180 / Math.PI)));
                modCommonData.AddField("startRotationY", ParseMinMaxCurve(particleSys.main.startRotationY, (float)(180 / Math.PI)));
                modCommonData.AddField("startRotationZ", ParseMinMaxCurve(particleSys.main.startRotationZ, (float)(180 / Math.PI)));
            }
            else
            {
                modCommonData.AddField("startRotationZ", ParseMinMaxCurve(particleSys.main.startRotation, (float)(180 / Math.PI)));
            }
            modCommonData.AddField("startSpeed", ParseMinMaxCurve(particleSys.main.startSpeed));
            modCommonData.AddField("gravityModifier", ParseMinMaxCurve(particleSys.main.gravityModifier));
#if UNITY_2018_1_OR_NEWER
            modCommonData.AddField("randomizeRotation", particleSys.main.flipRotation);
#endif
            modCommonData.AddField("randomSeed", particleSys.randomSeed);
            modCommonData.AddField("autoRandomSeed", particleSys.useAutoRandomSeed);

            ParticleSystemScalingMode pScalingMode = particleSys.main.scalingMode;
            int pScalingModeNum = 0;
            switch (pScalingMode)
            {
            case ParticleSystemScalingMode.Hierarchy:
                pScalingModeNum = 0;
                break;

            case ParticleSystemScalingMode.Local:
                pScalingModeNum = 1;
                break;

            case ParticleSystemScalingMode.Shape:
                pScalingModeNum = 2;
                break;
            }
            modCommonData.AddField("scalingMode", pScalingModeNum);

            ParticleSystemSimulationSpace simulationSpace = particleSys.main.simulationSpace;
            int simulationSpaceNum = 0;
            switch (simulationSpace)
            {
            case ParticleSystemSimulationSpace.Local:
                simulationSpaceNum = 0;
                break;

            case ParticleSystemSimulationSpace.World:
                simulationSpaceNum = 1;
                break;

            case ParticleSystemSimulationSpace.Custom:
                simulationSpaceNum = 2;
                break;
            }
            modCommonData.AddField("simulationSpace", simulationSpaceNum);

            JSONObject emitter     = new JSONObject(JSONObject.Type.OBJECT);
            JSONObject emitterData = new JSONObject(JSONObject.Type.OBJECT);
            data.AddField("emitter", emitterData);
            emitterData.AddField("playOnAwake", particleSys.main.playOnAwake);
            emitterData.AddField("looping", particleSys.main.loop);
            emitterData.AddField("duration", particleSys.main.duration);
            emitterData.AddField("startDelay", ParseMinMaxCurve(particleSys.main.startDelay));


            if (particleSys.emission.enabled)
            {
                JSONObject burst = new JSONObject(JSONObject.Type.ARRAY);
                emitterData.AddField("bursts", burst);
                int count = particleSys.emission.burstCount;
                ParticleSystem.Burst[] bursts = new ParticleSystem.Burst[count];
                particleSys.emission.GetBursts(bursts);
                for (int i = 0; i < count; i++)
                {
                    //burst.Add(ParseBurst(particleSys.emission.GetBurst(i)));
                    burst.Add(ParseBurst(bursts[i]));
                }

                emitterData.AddField("rateOverTime", ParseMinMaxCurve(particleSys.emission.rateOverTime));
            }
            emitterData.AddField("maxParticles", particleSys.main.maxParticles);

            if (particleSystemRenderer.enabled)
            {
                JSONObject renderer     = new JSONObject(JSONObject.Type.OBJECT);
                JSONObject rendererData = new JSONObject(JSONObject.Type.OBJECT);
                data.AddField("renderer", rendererData);
                ParticleSystemRenderMode pRenderMode = particleSystemRenderer.renderMode;
                int pRenderModeNum = 0;
                switch (pRenderMode)
                {
                case ParticleSystemRenderMode.Billboard:
                    pRenderModeNum = 1;
                    break;

                case ParticleSystemRenderMode.Stretch:
                    pRenderModeNum = 2;
                    rendererData.AddField("cameraScale", particleSystemRenderer.cameraVelocityScale);
                    rendererData.AddField("speedScale", particleSystemRenderer.velocityScale);
                    rendererData.AddField("lengthScale", particleSystemRenderer.lengthScale);
                    break;

                case ParticleSystemRenderMode.HorizontalBillboard:
                    pRenderModeNum = 3;
                    break;

                case ParticleSystemRenderMode.VerticalBillboard:
                    pRenderModeNum = 4;
                    break;

                case ParticleSystemRenderMode.Mesh:
                    Mesh mesh = particleSystemRenderer.mesh;
                    if (mesh != null)
                    {
                        WXMesh meshConverter = new WXMesh(mesh);
                        string meshPath      = meshConverter.Export(context.preset);
                        rendererData.AddField("mesh", meshPath);
                        rendererData.AddField("meshCount", particleSystemRenderer.meshCount);
                        context.AddResource(meshPath);
                    }
                    else
                    {
                        Debug.LogError(string.Format("{0} mesh is null", particleSys.name));
                    }
                    pRenderModeNum = 5;
                    break;

                case ParticleSystemRenderMode.None:
                    pRenderModeNum = 0;
                    break;

                default:
                    pRenderModeNum = 1;
                    break;
                }
                rendererData.AddField("renderMode", pRenderModeNum);

                int mode = 1;
                switch (particleSystemRenderer.alignment)
                {
                case ParticleSystemRenderSpace.View:
                    mode = 1;
                    break;

                case ParticleSystemRenderSpace.World:
                    mode = 2;
                    break;

                case ParticleSystemRenderSpace.Local:
                    mode = 3;
                    break;

                case ParticleSystemRenderSpace.Facing:
                    mode = 4;
                    break;

#if UNITY_2017_1_OR_NEWER
                case ParticleSystemRenderSpace.Velocity:
                    mode = 5;
                    break;
#endif
                default:
                    break;
                }
                rendererData.AddField("renderAlignment", mode);


                mode = 0;
                switch (particleSystemRenderer.sortMode)
                {
                case ParticleSystemSortMode.None:
                    mode = 0;
                    break;

                case ParticleSystemSortMode.Distance:
                    mode = 1;
                    break;

                case ParticleSystemSortMode.OldestInFront:
                    mode = 2;
                    break;

                case ParticleSystemSortMode.YoungestInFront:
                    mode = 3;
                    break;

                default:
                    break;
                }
                rendererData.AddField("sortMode", mode);
                rendererData.AddField("sortingFudge", particleSystemRenderer.sortingFudge);
                rendererData.AddField("normalDirection", particleSystemRenderer.normalDirection);
                rendererData.AddField("minParticleSize", particleSystemRenderer.minParticleSize);
                rendererData.AddField("maxParticleSize", particleSystemRenderer.maxParticleSize);

                var flipValue = TryGetContainProperty(particleSystemRenderer, "flip");
                if (flipValue != null)
                {
                    rendererData.AddField("flip", GetVect3((Vector3)flipValue));
                }
                else
                {
                    renderer.AddField("flip", GetVect3(new Vector3(0, 0, 0)));
                }
                //rendererData.AddField("flip", GetVect3(particleSystemRenderer.flip));
                rendererData.AddField("pivot", GetVect3(particleSystemRenderer.pivot));

                var allowRollData = TryGetContainProperty(particleSystemRenderer, "allowRoll");
                if (allowRollData != null)
                {
                    rendererData.AddField("allowRoll", (bool)allowRollData);
                }
                else
                {
                    rendererData.AddField("allowRoll", false);
                }
            }
            else
            {
                String info = "entity: " + particleSys.gameObject.name + " 的粒子组件没有renderer模块,不可导出;请加上renderer模块,或删除该粒子组件";

                ErrorUtil.ExportErrorReporter.create()
                .setGameObject(particleSys.gameObject)
                .setHierarchyContext(context)
                .error(0, "粒子组件没有renderer模块,不可导出;请加上renderer模块,或删除该粒子组件");
            }

            if (particleSys.rotationOverLifetime.enabled)
            {
                JSONObject rotationByLife     = new JSONObject(JSONObject.Type.OBJECT);
                JSONObject rotationByLifeData = new JSONObject(JSONObject.Type.OBJECT);
                data.AddField("rotationByLife", rotationByLifeData);

                rotationByLifeData.AddField("separateAxes", particleSys.rotationOverLifetime.separateAxes);
                if (particleSys.rotationOverLifetime.separateAxes)
                {
                    rotationByLifeData.AddField("x", ParseMinMaxCurve(particleSys.rotationOverLifetime.x, (float)(180 / Math.PI)));
                    rotationByLifeData.AddField("y", ParseMinMaxCurve(particleSys.rotationOverLifetime.y, (float)(180 / Math.PI)));
                    rotationByLifeData.AddField("z", ParseMinMaxCurve(particleSys.rotationOverLifetime.z, (float)(180 / Math.PI)));
                }
                else
                {
                    rotationByLifeData.AddField("z", ParseMinMaxCurve(particleSys.rotationOverLifetime.z, (float)(180 / Math.PI)));
                }
            }

            if (particleSys.sizeOverLifetime.enabled)
            {
                JSONObject sizeOverLifetime     = new JSONObject(JSONObject.Type.OBJECT);
                JSONObject sizeOverLifetimeData = new JSONObject(JSONObject.Type.OBJECT);
                data.AddField("sizeByLife", sizeOverLifetimeData);

                sizeOverLifetimeData.AddField("separateAxes", particleSys.sizeOverLifetime.separateAxes);
                if (particleSys.sizeOverLifetime.separateAxes)
                {
                    sizeOverLifetimeData.AddField("x", ParseMinMaxCurve(particleSys.sizeOverLifetime.x));
                    sizeOverLifetimeData.AddField("y", ParseMinMaxCurve(particleSys.sizeOverLifetime.y));
                    sizeOverLifetimeData.AddField("z", ParseMinMaxCurve(particleSys.sizeOverLifetime.z));
                }
                else
                {
                    sizeOverLifetimeData.AddField("x", ParseMinMaxCurve(particleSys.sizeOverLifetime.size));
                }
            }

            if (particleSys.velocityOverLifetime.enabled)
            {
                JSONObject speedByLifeData = new JSONObject(JSONObject.Type.OBJECT);
                data.AddField("speedByLife", speedByLifeData);
                switch (particleSys.velocityOverLifetime.space)
                {
                case ParticleSystemSimulationSpace.Local:
                    speedByLifeData.AddField("space", 1);
                    break;

                case ParticleSystemSimulationSpace.World:
                    speedByLifeData.AddField("space", 2);
                    break;

                case ParticleSystemSimulationSpace.Custom:
                    break;

                default:
                    break;
                }

                speedByLifeData.AddField("x", ParseMinMaxCurve(particleSys.velocityOverLifetime.x));
                speedByLifeData.AddField("y", ParseMinMaxCurve(particleSys.velocityOverLifetime.y));
                speedByLifeData.AddField("z", ParseMinMaxCurve(particleSys.velocityOverLifetime.z));
#if UNITY_2018_1_OR_NEWER
                speedByLifeData.AddField("orbitalX", ParseMinMaxCurve(particleSys.velocityOverLifetime.orbitalX));
                speedByLifeData.AddField("orbitalY", ParseMinMaxCurve(particleSys.velocityOverLifetime.orbitalY));
                speedByLifeData.AddField("orbitalZ", ParseMinMaxCurve(particleSys.velocityOverLifetime.orbitalZ));
                speedByLifeData.AddField("orbitalOffsetX", ParseMinMaxCurve(particleSys.velocityOverLifetime.orbitalOffsetX));
                speedByLifeData.AddField("orbitalOffsetY", ParseMinMaxCurve(particleSys.velocityOverLifetime.orbitalOffsetY));
                speedByLifeData.AddField("orbitalOffsetZ", ParseMinMaxCurve(particleSys.velocityOverLifetime.orbitalOffsetZ));
                speedByLifeData.AddField("radial", ParseMinMaxCurve(particleSys.velocityOverLifetime.radial));
#endif
#if UNITY_2017_1_OR_NEWER
                speedByLifeData.AddField("speedScale", ParseMinMaxCurve(particleSys.velocityOverLifetime.speedModifier));
#endif
            }

            if (particleSys.limitVelocityOverLifetime.enabled)
            {
                JSONObject speedLimitByLifeData = new JSONObject(JSONObject.Type.OBJECT);
                data.AddField("speedLimitByLife", speedLimitByLifeData);
                speedLimitByLifeData.AddField("separateAxes", particleSys.limitVelocityOverLifetime.separateAxes);
                if (particleSys.limitVelocityOverLifetime.separateAxes)
                {
                    speedLimitByLifeData.AddField("x", ParseMinMaxCurve(particleSys.limitVelocityOverLifetime.limitX, particleSys.limitVelocityOverLifetime.limitXMultiplier));
                    speedLimitByLifeData.AddField("y", ParseMinMaxCurve(particleSys.limitVelocityOverLifetime.limitY, particleSys.limitVelocityOverLifetime.limitYMultiplier));
                    speedLimitByLifeData.AddField("z", ParseMinMaxCurve(particleSys.limitVelocityOverLifetime.limitZ, particleSys.limitVelocityOverLifetime.limitZMultiplier));
                }
                else
                {
                    speedLimitByLifeData.AddField("x", ParseMinMaxCurve(particleSys.limitVelocityOverLifetime.limit, particleSys.limitVelocityOverLifetime.limitMultiplier));
                }
                speedLimitByLifeData.AddField("dampen", particleSys.limitVelocityOverLifetime.dampen);
                switch (particleSys.limitVelocityOverLifetime.space)
                {
                case ParticleSystemSimulationSpace.Local:
                    speedLimitByLifeData.AddField("space", 1);
                    break;

                case ParticleSystemSimulationSpace.World:
                    speedLimitByLifeData.AddField("space", 2);
                    break;

                case ParticleSystemSimulationSpace.Custom:
                    break;

                default:
                    break;
                }
#if UNITY_2017_1_OR_NEWER
                speedLimitByLifeData.AddField("drag", ParseMinMaxCurve(particleSys.limitVelocityOverLifetime.drag));
                speedLimitByLifeData.AddField("dragMultiplyBySize", particleSys.limitVelocityOverLifetime.multiplyDragByParticleSize);
                speedLimitByLifeData.AddField("dragMultiplyBySpeed", particleSys.limitVelocityOverLifetime.multiplyDragByParticleVelocity);
#endif
            }

            if (particleSys.colorOverLifetime.enabled)
            {
                JSONObject colorOverLifetime     = new JSONObject(JSONObject.Type.OBJECT);
                JSONObject colorOverLifetimeData = new JSONObject(JSONObject.Type.OBJECT);
                data.AddField("colorByLife", colorOverLifetimeData);
                colorOverLifetimeData.AddField("gColor", ParseMinMaxGradient(particleSys.colorOverLifetime.color));
            }

            if (particleSys.shape.enabled)
            {
                JSONObject shapeData = new JSONObject(JSONObject.Type.OBJECT);
                var        haveShape = true;
                if (particleSys.shape.shapeType == ParticleSystemShapeType.Cone || particleSys.shape.shapeType == ParticleSystemShapeType.ConeVolume || particleSys.shape.shapeType == ParticleSystemShapeType.ConeVolumeShell || particleSys.shape.shapeType == ParticleSystemShapeType.ConeShell)
                {
                    shapeData.AddField("shape", ParseConeShape(particleSys.shape));
                }
                else if (particleSys.shape.shapeType == ParticleSystemShapeType.Sphere || particleSys.shape.shapeType == ParticleSystemShapeType.SphereShell)
                {
                    shapeData.AddField("shape", ParseSphereShape(particleSys.shape));
                }
                else if (particleSys.shape.shapeType == ParticleSystemShapeType.Circle || particleSys.shape.shapeType == ParticleSystemShapeType.CircleEdge)
                {
                    shapeData.AddField("shape", ParseCircleShape(particleSys.shape));
                }
                else if (particleSys.shape.shapeType == ParticleSystemShapeType.Box || particleSys.shape.shapeType == ParticleSystemShapeType.BoxEdge || particleSys.shape.shapeType == ParticleSystemShapeType.BoxShell)
                {
                    shapeData.AddField("shape", ParseBox(particleSys.shape));
                }
                else if (particleSys.shape.shapeType == ParticleSystemShapeType.Hemisphere || particleSys.shape.shapeType == ParticleSystemShapeType.HemisphereShell)
                {
                    shapeData.AddField("shape", ParseHemisphere(particleSys.shape));
                }
                // else if (particleSys.shape.shapeType == ParticleSystemShapeType.SingleSidedEdge) {
                //     shapeData.AddField("shape", ParseSingleSidedEdge(particleSys.shape));
                // }
                else
                {
                    var parentChain = go.name;
                    var parent      = go.transform.parent;
                    while (parent)
                    {
                        parentChain += " -> " + parent.gameObject.name;
                        parent       = parent.parent;
                    }
                    Debug.LogError("unSupport shape (" + particleSys.shape.shapeType.ToString() + ") at: " + parentChain);
                    haveShape = false;
                }
                if (haveShape)
                {
                    data.AddField("emitterShape", shapeData);
                }
            }

            if (particleSys.textureSheetAnimation.enabled)
            {
                JSONObject textureSheetAnimationData = new JSONObject(JSONObject.Type.OBJECT);
                data.AddField("textureSheetAnimation", textureSheetAnimationData);
                int mode = 1;
#if UNITY_2017_1_OR_NEWER
                mode = 1;
                switch (particleSys.textureSheetAnimation.mode)
                {
                case ParticleSystemAnimationMode.Grid:
                    mode = 1;
                    break;

                case ParticleSystemAnimationMode.Sprites:
                    mode = 2;
                    break;

                default:
                    break;
                }
                textureSheetAnimationData.AddField("mode", mode);
#endif
                JSONObject vec2 = new JSONObject(JSONObject.Type.ARRAY);
                vec2.Add(particleSys.textureSheetAnimation.numTilesX);
                vec2.Add(particleSys.textureSheetAnimation.numTilesY);
                textureSheetAnimationData.AddField("tiles", vec2);
                mode = 1;
                switch (particleSys.textureSheetAnimation.animation)
                {
                case ParticleSystemAnimationType.WholeSheet:
                    mode = 1;
                    break;

                case ParticleSystemAnimationType.SingleRow:
                    mode = 2;
                    break;

                default:
                    break;
                }
                textureSheetAnimationData.AddField("animationType", mode);
                textureSheetAnimationData.AddField("randomRow", particleSys.textureSheetAnimation.useRandomRow);
                textureSheetAnimationData.AddField("row", particleSys.textureSheetAnimation.rowIndex);

                //mode = 1;
                //switch (particleSys.textureSheetAnimation.timeMode)
                //{
                //    case ParticleSystemAnimationTimeMode.Lifetime:
                //        mode = 1;
                //        break;
                //    case ParticleSystemAnimationTimeMode.Speed:
                //        mode = 2;
                //        break;
                //    case ParticleSystemAnimationTimeMode.FPS:
                //        mode = 3;
                //        break;
                //    default:
                //        break;
                //}
                textureSheetAnimationData.AddField("timeMode", 1);
                if (mode == 1)
                {
                    textureSheetAnimationData.AddField("frameOverTime", ParseMinMaxCurve(particleSys.textureSheetAnimation.frameOverTime, particleSys.textureSheetAnimation.numTilesX * particleSys.textureSheetAnimation.numTilesY));
                }
                else
                {
                    textureSheetAnimationData.AddField("frameOverTime", ParseMinMaxCurve(particleSys.textureSheetAnimation.frameOverTime, particleSys.textureSheetAnimation.numTilesX));
                }
                textureSheetAnimationData.AddField("startFrame", ParseMinMaxCurve(particleSys.textureSheetAnimation.startFrame));
                textureSheetAnimationData.AddField("cycles", particleSys.textureSheetAnimation.cycleCount);
                mode = 0;
                var a = particleSys.textureSheetAnimation.uvChannelMask;
                var b = a & UVChannelFlags.UV0;
                if ((a & UVChannelFlags.UV0) != 0)
                {
                    mode += 1;
                }
                if ((a & UVChannelFlags.UV1) != 0)
                {
                    mode += 2;
                }
                if ((a & UVChannelFlags.UV2) != 0)
                {
                    mode += 3;
                }
                if ((a & UVChannelFlags.UV3) != 0)
                {
                    mode += 4;
                }

                textureSheetAnimationData.AddField("affectedUVChannels", mode);
            }

            if (particleSys.subEmitters.enabled)
            {
                JSONObject subEmittersData = new JSONObject(JSONObject.Type.ARRAY);
                data.AddField("subEmitters", subEmittersData);

                int count = particleSys.subEmitters.subEmittersCount;
                for (int i = 0; i < count; i++)
                {
                    ParticleSystemSubEmitterProperties properties = particleSys.subEmitters.GetSubEmitterProperties(i);
                    ParticleSystemSubEmitterType       type       = particleSys.subEmitters.GetSubEmitterType(i);
                    JSONObject res     = new JSONObject(JSONObject.Type.OBJECT);
                    int        typeNum = 0;
                    switch (type)
                    {
                    case ParticleSystemSubEmitterType.Birth:
                        typeNum = 0;
                        break;

                    case ParticleSystemSubEmitterType.Collision:
                        typeNum = 1;
                        break;

                    case ParticleSystemSubEmitterType.Death:
                        typeNum = 2;
                        break;

                    default:
                        break;
                    }
                    res.AddField("type", typeNum);
                    int propertiesNum = 0;
                    switch (properties)
                    {
                    case ParticleSystemSubEmitterProperties.InheritNothing:
                        propertiesNum = 0;
                        break;

                    case ParticleSystemSubEmitterProperties.InheritEverything:
                        propertiesNum = 1;
                        break;

                    case ParticleSystemSubEmitterProperties.InheritColor:
                        propertiesNum = 2;
                        break;

                    case ParticleSystemSubEmitterProperties.InheritSize:
                        propertiesNum = 3;
                        break;

                    case ParticleSystemSubEmitterProperties.InheritRotation:
                        propertiesNum = 4;
                        break;

                    default:
                        break;
                    }
                    res.AddField("properties", propertiesNum);

                    subEmittersData.Add(res);
                }
            }

            return(json);
        }
示例#26
0
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
            JSONObject data = new JSONObject(JSONObject.Type.OBJECT);

            // 位置信息
            JSONObject position = new JSONObject(JSONObject.Type.ARRAY);

            if (usingDefault)
            {
                position.Add(0f);
                position.Add(0f);
                position.Add(0f);
            }
            else
            {
                position.Add(this.transform.localPosition.x * -1f);
                position.Add(this.transform.localPosition.y);
                position.Add(this.transform.localPosition.z);
            }

            // 旋转信息
            JSONObject rotation = new JSONObject(JSONObject.Type.ARRAY);

            if (usingDefault)
            {
                rotation.Add(0f);
                rotation.Add(0f);
                rotation.Add(0f);
                rotation.Add(1f);
            }
            else
            {
                rotation.Add(this.transform.localRotation.x * -1f);
                rotation.Add(this.transform.localRotation.y);
                rotation.Add(this.transform.localRotation.z);
                rotation.Add(this.transform.localRotation.w * -1f);
            }

            // 缩放信息
            JSONObject scale = new JSONObject(JSONObject.Type.ARRAY);

            if (usingDefault)
            {
                scale.Add(1f);
                scale.Add(1f);
                scale.Add(1f);
            }
            else
            {
                scale.Add(this.transform.localScale.x);
                scale.Add(this.transform.localScale.y);
                scale.Add(this.transform.localScale.z);
            }

            json.AddField("type", this.getTypeName());
            json.AddField("data", data);
            data.AddField("position", position);
            data.AddField("rotation", rotation);
            data.AddField("scale", scale);

            return(json);
        }
示例#27
0
        public JSONObject GetAvatarNodeData(GameObject gameObject, GameObject animatorGameObject, ref int id, string path = "")
        {
            bool currentNodeHasNotLegalChild = FindNotLegalChild(gameObject);

            if (
                (
                    (UnityEngine.Object)SelectParentbyType(
                        gameObject, WXUtility.ComponentType.Animator
                        ) != (UnityEngine.Object)animatorGameObject

                    ||

                    WXUtility
                    .componentsOnGameObject(gameObject)
                    .IndexOf(WXUtility.ComponentType.Animator) != -1

                ) && (UnityEngine.Object)gameObject != (UnityEngine.Object)animatorGameObject
                )
            {
                return(null);
            }
            if (currentNodeHasNotLegalChild)
            {
                JSONObject nodeJSON  = new JSONObject(JSONObject.Type.OBJECT);
                JSONObject nodeProps = new JSONObject(JSONObject.Type.OBJECT);
                JSONObject translate = new JSONObject(JSONObject.Type.ARRAY);
                JSONObject rotation  = new JSONObject(JSONObject.Type.ARRAY);
                JSONObject scale     = new JSONObject(JSONObject.Type.ARRAY);

                Vector3    localPosition = gameObject.transform.localPosition;
                Quaternion localRotation = gameObject.transform.localRotation;
                Vector3    localScale    = gameObject.transform.localScale;

                nodeProps.AddField("name", gameObject.name);
                nodeJSON.AddField("props", nodeProps);

                translate = new JSONObject(JSONObject.Type.ARRAY);
                nodeProps.AddField("translate", translate);
                translate.Add(localPosition.x * -1f);
                translate.Add(localPosition.y);
                translate.Add(localPosition.z);
                rotation = new JSONObject(JSONObject.Type.ARRAY);
                nodeProps.AddField("rotation", rotation);
                rotation.Add(localRotation.x * -1f);
                rotation.Add(localRotation.y);
                rotation.Add(localRotation.z);
                rotation.Add(localRotation.w * -1f);
                scale = new JSONObject(JSONObject.Type.ARRAY);
                nodeProps.AddField("scale", scale);
                scale.Add(localScale.x);
                scale.Add(localScale.y);
                scale.Add(localScale.z);

                id = id + 1;
                if (id > -1)
                {
                    if (path.Length > 0)
                    {
                        path = path + "/" + gameObject.name;
                    }
                    else
                    {
                        path = gameObject.name;
                    }
                }
                JSONObject nodeChildrenArray = new JSONObject(JSONObject.Type.ARRAY);
                if (gameObject.transform.childCount > 0)
                {
                    for (int i = 0; i < gameObject.transform.childCount; i++)
                    {
                        JSONObject child = GetAvatarNodeData(gameObject.transform.GetChild(i).gameObject, animatorGameObject, ref id, path);
                        if (child != null)
                        {
                            nodeChildrenArray.Add(child);
                        }
                    }
                }
                nodeJSON.AddField("child", nodeChildrenArray);

                return(nodeJSON);
            }
            return(null);
        }
示例#28
0
        private static void RegisterUnityProperties()
        {
            AddTypePropertyHandler(typeof(Vector2), (obj, context, requireList) =>
            {
                Vector2 v = (Vector2)obj;
                if (v == null)
                {
                    return(null);
                }

                JSONObject vec2 = new JSONObject(JSONObject.Type.ARRAY);
                vec2.Add(v.x);
                vec2.Add(v.y);

                return(vec2);
            });

            AddTypePropertyHandler(typeof(Vector3), (obj, context, requireList) =>
            {
                Vector3 v = (Vector3)obj;
                if (v == null)
                {
                    return(null);
                }

                JSONObject vec3 = new JSONObject(JSONObject.Type.ARRAY);
                vec3.Add(v.x);
                vec3.Add(v.y);
                vec3.Add(v.z);

                return(vec3);
            });

            AddTypePropertyHandler(typeof(Vector4), (obj, context, requireList) =>
            {
                Vector4 v = (Vector4)obj;
                if (v == null)
                {
                    return(null);
                }

                JSONObject vec4 = new JSONObject(JSONObject.Type.ARRAY);
                vec4.Add(v.x);
                vec4.Add(v.y);
                vec4.Add(v.z);
                vec4.Add(v.w);

                return(vec4);
            });

            AddTypePropertyHandler(typeof(Quaternion), (obj, context, requireList) =>
            {
                Quaternion v = (Quaternion)obj;
                if (v == null)
                {
                    return(null);
                }

                JSONObject array4 = new JSONObject(JSONObject.Type.ARRAY);
                array4.Add(v.x);
                array4.Add(v.y);
                array4.Add(v.z);
                array4.Add(v.w);

                return(array4);
            });


            AddTypePropertyHandler(typeof(Matrix4x4), (obj, context, requireList) =>
            {
                Matrix4x4 v = (Matrix4x4)obj;
                if (v == null)
                {
                    return(null);
                }

                JSONObject array16 = new JSONObject(JSONObject.Type.ARRAY);
                array16.Add(v.m00);
                array16.Add(v.m01);
                array16.Add(v.m02);
                array16.Add(v.m03);
                array16.Add(v.m10);
                array16.Add(v.m11);
                array16.Add(v.m12);
                array16.Add(v.m13);
                array16.Add(v.m20);
                array16.Add(v.m21);
                array16.Add(v.m22);
                array16.Add(v.m23);
                array16.Add(v.m30);
                array16.Add(v.m31);
                array16.Add(v.m32);
                array16.Add(v.m33);

                return(array16);
            });

            AddTypePropertyHandler(typeof(Color), (obj, context, requireList) =>
            {
                Color c = (Color)obj;
                if (c == null)
                {
                    return(null);
                }

                JSONObject vec4 = new JSONObject(JSONObject.Type.ARRAY);
                vec4.Add((int)(c.r * 255));
                vec4.Add((int)(c.g * 255));
                vec4.Add((int)(c.b * 255));
                vec4.Add((int)(c.a * 255));

                return(vec4);
            });

            AddTypePropertyHandler(typeof(TextAsset), (obj, context, requireList) =>
            {
                TextAsset t = (TextAsset)obj;
                if (!t)
                {
                    return(null);
                }

                string path = AssetDatabase.GetAssetPath(t);
                // string copyToPath = Path.Combine(WXResourceStore.storagePath, path);
                // Debug.Log("WXResourceStore.storagePath:" + WXResourceStore.storagePath);
                // Debug.Log("path:" + path);
                // Debug.Log("copyToPath:" + copyToPath);

                // Regex regex = new Regex(".txt$");
                // copyToPath = regex.Replace(copyToPath, ".json");

                // if (!Directory.Exists(WXResourceStore.storagePath + "Assets/")) {
                //     Directory.CreateDirectory(WXResourceStore.storagePath + "Assets/");
                // }

                // FileStream fs = new FileStream(copyToPath, FileMode.Create, FileAccess.Write);

                // wxFileUtil.WriteData(fs, JsonConvert.SerializeObject(new { text = t.text }));
                // fs.Close();

                JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
                JSONObject data = new JSONObject(JSONObject.Type.OBJECT);
                // Debug.Log("JsonConvert.SerializeObject(t.text): " + JsonConvert.SerializeObject(t.text));
                string text = t.text.Replace("\r\n", "\\n").Replace("\\", "\\\\").Replace("\"", "\\\"");
                data.AddField("text", text);
                data.AddField("path", path);
                json.AddField("type", "UnityEngine.TextAsset".EscapeNamespaceSimple());
                json.AddField("value", data);
                return(json);
            });

            AddTypePropertyHandler(typeof(Material), (obj, context, requireList) =>
            {
                Material material = (Material)obj;
                if (material == null)
                {
                    return(null);
                }

                WXMaterial materialConverter = new WXMaterial(material, null);
                string materialPath          = materialConverter.Export(context.preset);
                context.AddResource(materialPath);

                JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
                JSONObject data = new JSONObject(JSONObject.Type.OBJECT);
                json.AddField("type", "UnityEngine.Material".EscapeNamespaceSimple());
                json.AddField("value", data);
                data.AddField("path", materialPath);

                return(json);
            });

            AddTypePropertyHandler(typeof(UnityEngine.LayerMask), (obj, context, requireList) =>
            {
                LayerMask mask = (LayerMask)obj;

                return(JSONObject.Create(mask.value));
            });

            AddTypePropertyHandler(typeof(List <>), (obj, context, requireList) =>
            {
                IEnumerable list = (IEnumerable)obj;
                if (list == null)
                {
                    return(null);
                }

                JSONObject result = new JSONObject(JSONObject.Type.ARRAY);

                var enumerator = ((IEnumerable)list).GetEnumerator();
                while (enumerator.MoveNext())
                {
                    object itemObj = enumerator.Current;
                    if (itemObj == null)
                    {
                        continue;
                    }
                    if (itemObj.GetType() == typeof(List <>))
                    {
                        throw new Exception("不支持嵌套List");
                    }
                    else
                    {
                        Type type             = itemObj.GetType();
                        JSONObject itemResult = innerHandleField(type, itemObj, context, requireList);
                        if (itemResult != null)
                        {
                            result.Add(itemResult);
                        }
                    }
                }
                return(result);
            });

            AddTypePropertyHandler(typeof(PuertsBeefBallSDK.RemoteResource), (obj, context, requireList) =>
            {
                var m = (PuertsBeefBallSDK.RemoteResource)obj;
                return(JSONObject.CreateStringObject(m.resourcePath));
            });

            // disgusting code logic :(
            // refactor should be needed
            AddTypePropertyHandler(typeof(PuertsBeefBallBehaviour), (obj, context, requireList) =>
            {
                var m = (PuertsBeefBallBehaviour)obj;
                if (!m)
                {
                    return(null);
                }

                JSONObject innerData = new JSONObject(JSONObject.Type.OBJECT);

                var escapedTypeName = WXMonoBehaviourExportHelper.EscapeNamespace(m.GetType().FullName);
                innerData.AddField("type", escapedTypeName);
                innerData.AddField("value", context.AddComponentInProperty(new PuertsBeefBallBehaviourConverter(m), (Component)obj));
                return(innerData);
            });

            AddTypePropertyHandler(typeof(Component), (obj, context, requireList) =>
            {
                Component c = (Component)obj;
                if (!c)
                {
                    return(null);
                }

                JSONObject innerData = new JSONObject(JSONObject.Type.OBJECT);

                var escapedTypeName = WXMonoBehaviourExportHelper.EscapeNamespace(c.GetType().FullName);
                innerData.AddField("type", escapedTypeName);
                innerData.AddField("value", context.AddComponentInProperty(new WXUnityComponent(c), c));
                return(innerData);
            });

            // 在前面condition逻辑里,理论上已经把所有可能为prefab的逻辑走完
            AddTypePropertyHandler(typeof(GameObject), (obj, context, requireList) =>
            {
                throw new Exception("不支持节点属性指向GameObject,请改为指向Transform或是具体逻辑组件");

                // var go = (GameObject)obj;
                // if (!go) return null;

                // JSONObject innerData = new JSONObject(JSONObject.Type.OBJECT);

                // return GetPrefabOnSerializedField(context, go, innerData);
            });
        }
        protected override JSONObject ToJSON(WXHierarchyContext context)
        {
            if (uiSprite != null)
            {
                //if (uiSprite.isAnchored)
                //{
                //    JSONObject anchorJson = new JSONObject(JSONObject.Type.OBJECT);
                //    anchorJson.AddField("type", "UIWidget");
                //    JSONObject anchorSubJSON = new JSONObject(JSONObject.Type.OBJECT);
                //    anchorSubJSON.AddField("leftMargin", uiSprite.leftAnchor.absolute);
                //    anchorSubJSON.AddField("rightMargin", uiSprite.rightAnchor.absolute);
                //    anchorSubJSON.AddField("topMargin", uiSprite.topAnchor.absolute);
                //    anchorSubJSON.AddField("bottomMargin", uiSprite.bottomAnchor.absolute);
                //    anchorJson.AddField("data", anchorSubJSON);

                //}

                JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
                json.AddField("type", "UISprite");

                JSONObject subJSON = new JSONObject(JSONObject.Type.OBJECT);

                JSONObject color = new JSONObject(JSONObject.Type.ARRAY);
                color.Add(255f * uiSprite.color.r);
                color.Add(255f * uiSprite.color.g);
                color.Add(255f * uiSprite.color.b);
                color.Add(255f * uiSprite.color.a);
                subJSON.AddField("color", color);
                subJSON.AddField("colorBlendType", 0);

                //if (uiSprite.name == "PageBagChecked")
                //{
                //    Debug.Log("++==++==++");

                //    Debug.Log(uiSprite.isAnchored);
                //    Debug.Log(uiSprite.bottomAnchor.absolute);
                //    Debug.Log(uiSprite.bottomAnchor.target.name);
                //}

                UI2DSprite.Type type = uiSprite.type;
                subJSON.AddField("type", (int)type);

                UI2DSprite.Flip flipType = uiSprite.flip;
                subJSON.AddField("flip", (int)flipType);
                subJSON.AddField("fillCenter", uiSprite.centerType == UI2DSprite.AdvancedType.Sliced);
                subJSON.AddField("fillDir", (int)uiSprite.fillDirection);
                subJSON.AddField("fillAmount", uiSprite.fillAmount);
                subJSON.AddField("invertFill", uiSprite.invert);

                if (uiSprite.atlas != null)
                {
                    string uuid = WXSpriteFrame.getSprite(uiSprite.atlas, uiSprite.spriteName, context.preset);
                    if (uuid == null)
                    {
                        Debug.LogWarning("获取sprite失败: " + uiSprite.spriteName);
                    }
                    else
                    {
                        context.AddResource(uuid);
                    }

                    if (uuid != null)
                    {
                        subJSON.AddField("spriteFrame", uuid);
                    }
                    else
                    {
                        JSONObject nullJSON = new JSONObject(JSONObject.Type.NULL);
                        subJSON.AddField("spriteFrame", nullJSON);
                    }
                }
                else
                {
                    JSONObject nullJSON = new JSONObject(JSONObject.Type.NULL);
                    subJSON.AddField("spriteFrame", nullJSON);
                }

                subJSON.AddField("active", uiSprite.enabled);
                json.AddField("data", subJSON);

                return(json);
            }
            else
            {
                JSONObject json = new JSONObject(JSONObject.Type.OBJECT);
                json.AddField("type", "UISprite");

                JSONObject subJSON = new JSONObject(JSONObject.Type.OBJECT);

                JSONObject color = new JSONObject(JSONObject.Type.ARRAY);
                color.Add(255f);
                color.Add(255f);
                color.Add(255f);
                color.Add(255f);
                subJSON.AddField("color", color);
                subJSON.AddField("colorBlendType", 0);
                subJSON.AddField("type", (int)UI2DSprite.Type.Simple);
                subJSON.AddField("flip", (int)UI2DSprite.Flip.Nothing);
                subJSON.AddField("fillCenter", false);
                subJSON.AddField("fillDir", (int)UI2DSprite.FillDirection.Horizontal);
                subJSON.AddField("fillAmount", 0);
                subJSON.AddField("invertFill", false);

                JSONObject nullJSON = new JSONObject(JSONObject.Type.NULL);
                subJSON.AddField("spriteFrame", nullJSON);

                subJSON.AddField("active", true);
                json.AddField("data", subJSON);

                return(json);
            }
        }
        public int HandleState(ref AnimatorState state)
        {
            bool stateExist;
            var  stateInfo = controllerInfo.states.AddObject(state, out stateExist);

            if (!stateExist)
            {
                stateInfo.Value.AddField("name", state.name);
                var        stateJSON        = stateInfo.Value;
                JSONObject stateTransitions = new JSONObject(JSONObject.Type.ARRAY);
                for (int j = 0; j < state.transitions.Length; j++)
                {
                    AnimatorStateTransition trans = state.transitions[j];
                    stateTransitions.Add(HandleStateTransition(state.name, ref trans));
                }
                stateJSON.AddField("transitions", stateTransitions);

                // animationClip
                Motion motion = state.motion;
                if (motion == null)
                {
                    stateJSON.AddField("motion", new JSONObject(JSONObject.Type.NULL));
                }
                else if (motion.GetType() == typeof(AnimationClip))
                {
                    JSONObject    clipJSON = new JSONObject(JSONObject.Type.OBJECT);
                    AnimationClip clip     = motion as AnimationClip;
                    if (handleBeforeAnimationClip != null && !handleBeforeAnimationClip(clip, state, gameObject))
                    {
                        // 如果return false,说明这个animationclip被外面所接管
                        clipJSON.AddField("id", "");
                    }
                    else
                    {
                        string clipUid = HandleAnimationClip(ref clip);
                        clipJSON.AddField("id", clipUid);
                    }
                    clipJSON.AddField("type", "AnimationClip");
                    stateJSON.AddField("motion", clipJSON);
                }
                else if (motion.GetType() == typeof(BlendTree))
                {
                    JSONObject btJSON = new JSONObject(JSONObject.Type.OBJECT);
                    BlendTree  bt     = motion as BlendTree;
                    btJSON.AddField("type", "BlendTree");
                    btJSON.AddField("id", TraverseBlendTree(ref bt));
                    stateJSON.AddField("motion", btJSON);
                }
                stateJSON.AddField("cycleOffset", state.cycleOffset);
                if (state.cycleOffsetParameterActive)
                {
                    stateJSON.AddField("cycleOffsetParameter", state.cycleOffsetParameter);
                }
                else
                {
                    stateJSON.AddField("cycleOffsetParameter", new JSONObject(JSONObject.Type.NULL));
                }
                stateJSON.AddField("mirror", state.mirror);
                if (state.mirrorParameterActive)
                {
                    stateJSON.AddField("mirrorParameter", state.mirrorParameter);
                }
                else
                {
                    stateJSON.AddField("mirrorParameter", new JSONObject(JSONObject.Type.NULL));
                }
                stateInfo.Value.AddField("speed", state.speed);
                if (state.speedParameterActive)
                {
                    stateJSON.AddField("speedParameter", state.speedParameter);
                }
                else
                {
                    stateJSON.AddField("speedParameter", new JSONObject(JSONObject.Type.NULL));
                }
#if UNITY_2017_1_OR_NEWER
                if (state.timeParameterActive)
                {
                    stateJSON.AddField("timeParameter", state.timeParameter);
                }
                else
                {
#endif
                stateJSON.AddField("timeParameter", new JSONObject(JSONObject.Type.NULL));
#if UNITY_2017_1_OR_NEWER
            }
#endif
                return(stateInfo.Key);
            }
            else
            {
                return(stateInfo.Key);
            }
        }