Пример #1
0
        public override JObject Serialize(ZOSimDocumentRoot documentRoot, UnityEngine.Object parent = null)
        {
            JObject json = new JObject(
                new JProperty("name", Name),
                new JProperty("type", Type),
                new JProperty("ros_topic", ROSTopic),
                new JProperty("update_rate_hz", UpdateRateHz)
                );

            JSON = json;
            return(json);
        }
        public JObject Serialize(ZOSimDocumentRoot documentRoot, UnityEngine.Object parent = null)
        {
            JObject json = new JObject(
                new JProperty("name", Name),
                new JProperty("type", Type),
                new JProperty("hinge_joint", _hingeJoint.Name),
                new JProperty("min_limit_degrees", MinSteeringLockDegrees),
                new JProperty("max_limit_degrees", MaxSteeringLockDegrees),
                new JProperty("pid_controller", _pidController.Serialize(documentRoot))

                );

            _json = json;
            return(json);
        }
Пример #3
0
        public JObject Serialize(ZOSimDocumentRoot documentRoot, UnityEngine.Object parent = null)
        {
            JObject gripControllerJSON = new JObject(
                new JProperty("name", Name),
                new JProperty("type", Type),
                new JProperty("servo_motor_actuators",
                              new JArray(_fingerActuators[0].Name, _fingerActuators[1].Name)),
                new JProperty("min_limit_degrees", _minMaxLimitsDegrees.x),
                new JProperty("max_limit_degrees", _minMaxLimitsDegrees.y),
                new JProperty("speed", _onKeyMoveSpeed)
                );

            _json = gripControllerJSON;
            return(gripControllerJSON);
        }
        public void Deserialize(ZOSimDocumentRoot documentRoot, JObject json)
        {
            // Assert.Equals(json["type"].Value<string>() == Type);

            _json = json;
            Name  = json.ValueOrDefault("name", Name);

            // TODO: build Hinge Joint if it doesn't exist?

            MinSteeringLockDegrees = json.ValueOrDefault <float>("min_limit_degrees", MinSteeringLockDegrees);
            MaxSteeringLockDegrees = json.ValueOrDefault <float>("max_limit_degrees", MaxSteeringLockDegrees);
            if (_pidController == null)
            {
                _pidController = new ZOPIDController();
            }
            _pidController.Deserialize(documentRoot, json["pid_controller"].Value <JObject>());
        }
        public override void OnInspectorGUI()
        {
            DrawDefaultInspector();

            ZOSimDocumentRoot zoSimBaseComponent = (ZOSimDocumentRoot)target;

            if (GUILayout.Button("Save ZOSim"))
            {
                Debug.Log("INFO: ZOSimBaseComponent Save ZOSim");
                if (EditorUtility.DisplayDialog("Override File:", "Override File: " + zoSimBaseComponent.ZOSimDocumentFilePath, "OK", "Cancel"))
                {
                    zoSimBaseComponent.SaveToZOSimFile(zoSimBaseComponent.ZOSimDocumentFilePath);
                }
            }

            if (GUILayout.Button("Load ZOSim"))
            {
                Debug.Log("INFO: ZOSimBaseComponent Load ZOSim");
                if (EditorUtility.DisplayDialog("Override Object:", "Override Object with file: " + zoSimBaseComponent.ZOSimDocumentFilePath, "OK", "Cancel"))
                {
                    zoSimBaseComponent.LoadFromZOSimFile(zoSimBaseComponent.ZOSimDocumentFilePath);
                }
            }
        }
Пример #6
0
        public void Deserialize(ZOSimDocumentRoot documentRoot, JObject json)
        {
            // Assert.Equals(json["type"].Value<string>() == Type);

            _json = json;
            Name  = json.ValueOrDefault("name", Name);
            UnityHingeJoint.anchor          = json.ToVector3OrDefault("anchor", UnityHingeJoint.anchor);
            UnityHingeJoint.axis            = json.ToVector3OrDefault("axis", UnityHingeJoint.axis);
            UnityHingeJoint.connectedAnchor = json.ToVector3OrDefault("connected_anchor", UnityHingeJoint.connectedAnchor);
            UnityHingeJoint.useSpring       = json.ValueOrDefault <bool>("use_spring", UnityHingeJoint.useSpring);


            if (json.ContainsKey("spring"))
            {
                JObject     springJSON = json["spring"].Value <JObject>();
                JointSpring spring     = UnityHingeJoint.spring;
                spring.spring          = springJSON.ValueOrDefault <float>("spring", spring.spring);
                spring.damper          = springJSON.ValueOrDefault <float>("damper", spring.damper);
                spring.targetPosition  = springJSON.ValueOrDefault <float>("target_position", spring.targetPosition);
                UnityHingeJoint.spring = spring;
            }

            UnityHingeJoint.useMotor = json.ValueOrDefault <bool>("use_motor", UnityHingeJoint.useMotor);
            if (json.ContainsKey("use_motor"))
            {
                JObject    motorJSON = json["motor"].Value <JObject>();
                JointMotor motor     = UnityHingeJoint.motor;
                motor.targetVelocity  = motorJSON.ValueOrDefault <float>("target_velocity", motor.targetVelocity);
                motor.force           = motorJSON.ValueOrDefault <float>("force", motor.force);
                motor.freeSpin        = motorJSON.ValueOrDefault <bool>("free_spin", motor.freeSpin);
                UnityHingeJoint.motor = motor;
            }

            UnityHingeJoint.useLimits = json.ValueOrDefault <bool>("use_limits", UnityHingeJoint.useLimits);
            if (json.ContainsKey("limits"))
            {
                JObject     limitsJSON = json["limits"].Value <JObject>();
                JointLimits limits     = UnityHingeJoint.limits;
                limits.min               = limitsJSON.ValueOrDefault <float>("min", limits.min);
                limits.max               = limitsJSON.ValueOrDefault <float>("max", limits.max);
                limits.bounciness        = limitsJSON.ValueOrDefault <float>("bounciness", limits.bounciness);
                limits.bounceMinVelocity = limitsJSON.ValueOrDefault <float>("bounce_min_velocity", UnityHingeJoint.limits.bounceMinVelocity);
                limits.contactDistance   = limitsJSON.ValueOrDefault <float>("contact_distance", limits.contactDistance);
                UnityHingeJoint.limits   = limits;
            }

            // find connected body.  this likely will need to be done post LoadFromJSON as it may
            // not be created yet.
            documentRoot.OnPostDeserializationNotification((docRoot) => {
                if (JSON.ContainsKey("connected_occurrence"))
                {
                    ZOSimOccurrence connectedOccurrence = docRoot.GetOccurrence(JSON["connected_occurrence"].Value <string>());
                    if (connectedOccurrence)
                    {
                        UnityHingeJoint.connectedBody = connectedOccurrence.GetComponent <Rigidbody>();
                    }
                    else
                    {
                        Debug.LogWarning("WARNING: ZOHingeJoint failed to find connected occurrence: " + JSON["connected_occurrence"].Value <string>());
                    }
                }
            });
        }
Пример #7
0
        /// <summary>
        /// Serializes the ZOHingeJoint to ZOSim JSON.
        /// </summary>
        /// <param name="documentRoot"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public JObject Serialize(ZOSimDocumentRoot documentRoot, UnityEngine.Object parent = null)
        {
            // calculate the world anchor positions relative to the document root transform
            // BUGBUG: maybe from the base of the joint chain which is not necessarily the document root?
            Vector3 worldAnchor = this.transform.TransformPoint(UnityHingeJoint.anchor);

            worldAnchor = documentRoot.transform.InverseTransformPoint(worldAnchor);

            Vector3 worldConnectedAnchor = this.transform.TransformPoint(UnityHingeJoint.connectedAnchor);

            worldConnectedAnchor = documentRoot.transform.InverseTransformPoint(worldConnectedAnchor);

            Vector3 worldAxis = this.transform.rotation * UnityHingeJoint.axis;

            worldAxis = documentRoot.transform.InverseTransformDirection(worldAxis);

            JObject json = new JObject(
                new JProperty("name", Name),
                new JProperty("type", Type),
                new JProperty("anchor", ZOSimDocumentRoot.ToJSON(UnityHingeJoint.anchor)),
                new JProperty("world_anchor", ZOSimDocumentRoot.ToJSON(worldAnchor)),
                new JProperty("axis", ZOSimDocumentRoot.ToJSON(UnityHingeJoint.axis)),
                new JProperty("world_axis", ZOSimDocumentRoot.ToJSON(worldAxis)),
                new JProperty("connected_anchor", ZOSimDocumentRoot.ToJSON(UnityHingeJoint.connectedAnchor)),
                new JProperty("world_connected_anchor", ZOSimDocumentRoot.ToJSON(worldConnectedAnchor)),
                new JProperty("use_spring", UnityHingeJoint.useSpring),
                new JProperty("spring", new JObject(
                                  new JProperty("spring", UnityHingeJoint.spring.spring),
                                  new JProperty("damper", UnityHingeJoint.spring.damper),
                                  new JProperty("target_position", UnityHingeJoint.spring.targetPosition)
                                  )),
                new JProperty("use_motor", UnityHingeJoint.useMotor),
                new JProperty("motor", new JObject(
                                  new JProperty("target_velocity", UnityHingeJoint.motor.targetVelocity),
                                  new JProperty("force", UnityHingeJoint.motor.force),
                                  new JProperty("free_spin", UnityHingeJoint.motor.freeSpin)
                                  )),
                new JProperty("use_limits", UnityHingeJoint.useLimits),
                new JProperty("limits", new JObject(
                                  new JProperty("min", UnityHingeJoint.limits.min),
                                  new JProperty("max", UnityHingeJoint.limits.max),
                                  new JProperty("bounciness", UnityHingeJoint.limits.bounciness),
                                  new JProperty("bounce_min_velocity", UnityHingeJoint.limits.bounceMinVelocity),
                                  new JProperty("contact_distance", UnityHingeJoint.limits.contactDistance)
                                  ))
                );

            if (UnityHingeJoint.connectedBody)
            {
                ZOSimOccurrence connected_occurrence = UnityHingeJoint.connectedBody.gameObject.GetComponent <ZOSimOccurrence>();

                if (connected_occurrence)
                {
                    json["connected_occurrence"] = connected_occurrence.Name;
                }
                else
                {
                    Debug.LogWarning("WARNING: Could not get connected occurrence for ZOHingeJoint: " + Name + "\nPerhaps there is a missing ZOSimOccurrence?");
                }
            }
            else
            {
                Debug.LogWarning("WARNING: Could not get connected occurrence for ZOHingeJoint: " + Name);
            }

            ZOSimOccurrence parent_occurrence = GetComponent <ZOSimOccurrence>();

            if (parent_occurrence)
            {
                json["parent_occurrence"] = parent_occurrence.Name;
            }

            _json = json;

            return(json);
        }
Пример #8
0
        protected override void ZOUpdate()
        {
            // handle any spawn model requests
            while (_spawnZOSimModelRequests.Count > 0)
            {
                Tuple <ZOSimSpawnServiceRequest, string> spawnRequestAndId = _spawnZOSimModelRequests.Dequeue();
                ZOSimSpawnServiceRequest spawnRequest = spawnRequestAndId.Item1;
                string service_request_id             = spawnRequestAndId.Item2;

                Debug.Log("INFO: Spawning ZeroSim model: " + spawnRequest.model_name);

                try {
                    // spawn a new gameobject
                    GameObject newZoSimModel = new GameObject(spawnRequest.model_name);

                    newZoSimModel.transform.parent = null;  // make it child of the world

                    // set the initial position and orientation
                    Vector3 position = spawnRequest.initial_pose.position.ToUnityVector3();
                    Debug.Log("INFO: Spawning at location: " + position.ToString());
                    Quaternion rotation = spawnRequest.initial_pose.orientation.ToUnityQuaternion();
                    newZoSimModel.transform.position = position;
                    newZoSimModel.transform.rotation = rotation;

                    // load from JSON
                    ZOSimDocumentRoot simDocumentRoot = newZoSimModel.AddComponent <ZOSimDocumentRoot>();
                    JObject           zosimModelJSON  = JObject.Parse(spawnRequest.model_zosim);
                    simDocumentRoot.Deserialize(zosimModelJSON);

                    // fixup name
                    // TODO: check that the name is unique and if not generate a unique name or maybe return a
                    // warning that the name is not unique?  probably the later.
                    simDocumentRoot.Name = spawnRequest.model_name;

                    // report back success
                    ROSBridgeConnection.ServiceResponse <ZOSimSpawnServiceResponse>(new ZOSimSpawnServiceResponse()
                    {
                        success        = true,
                        status_message = "success!"
                    }, ROSTopic, true, service_request_id);
                } catch (System.Exception e) {
                    Debug.LogError("ERROR: spawning model: " + e.ToString());

                    // report back error
                    ROSBridgeConnection.ServiceResponse <ZOSimSpawnServiceResponse>(new ZOSimSpawnServiceResponse()
                    {
                        success        = true,
                        status_message = "ERROR: " + e.ToString()
                    }, ROSTopic, true, service_request_id);
                }


                // GameObject loadedAsset = DefaultAssets.LoadAsset<GameObject>(spawnRequest.model_name);
                // if (loadedAsset != null) {
                //     Vector3 position = spawnRequest.initial_pose.position.ToUnityVector3();
                //     Quaternion rotation = spawnRequest.initial_pose.orientation.ToUnityQuaternion();
                //     Instantiate(loadedAsset, position, rotation);

                //     // report back success
                //     ROSBridgeConnection.ServiceResponse<ZOSimSpawnServiceResponse>(new ZOSimSpawnServiceResponse() {
                //         success = true,
                //         status_message = "done!"
                //     }, "gazebo/spawn_urdf_model", true, id);

                // } else { // error loading asset
                //     ROSBridgeConnection.ServiceResponse<ZOSimSpawnServiceResponse>(new ZOSimSpawnServiceResponse() {
                //         success = false,
                //         status_message = "ERROR: loading model: " + spawnRequest.model_name
                //     }, "gazebo/spawn_urdf_model", false, id);

                // }
            }
        }
Пример #9
0
        void DoImport()
        {
            Debug.Log("INFO: Zero Sim Import...");
            ZeroSimProjectFile = null;  // HACKHACK. Doing this because we don't want todo the "drag & drop" project into Unity.  Instead we always want to ask for the project file.
            if (ZeroSimProjectFile == null)
            {
                ZeroSimProjectFile = EditorUtility.OpenFilePanelWithFilters("Import Fusion 360 Project", "", new[] { "ZoSim", "zosim, zsim, json" });
            }
            Debug.Log("INFO: Zero Sim Import Project File: " + ZeroSimProjectFile);

            // Parse the ZoSim JSON
            ZeroSimJSON  = JObject.Parse(File.ReadAllText(ZeroSimProjectFile));
            DocumentName = ZeroSimJSON["document_name"].Value <string>();

            ExportDirectoryPath = EditorUtility.OpenFolderPanel("Select Save To Folder", Application.dataPath + "/Assets", "");

            // create directory structures
            if (Directory.Exists(RootExportDirectory) == false)
            {
                Directory.CreateDirectory(RootExportDirectory);
            }
            if (Directory.Exists(VisualMeshDirectory) == false)
            {
                Directory.CreateDirectory(VisualMeshDirectory);
            }
            if (Directory.Exists(CollisionMeshDirectory) == false)
            {
                Directory.CreateDirectory(CollisionMeshDirectory);
            }
            if (Directory.Exists(AssetBundlesDirectory) == false)
            {
                Directory.CreateDirectory(AssetBundlesDirectory);
            }



            // read all components and load any assets like visual and collision meshes
            foreach (JObject component in ZeroSimJSON["components"])
            {
                OnComponent(component);
            }

            // set the scales that were set in the import UI
            // save out scales to JSON
            ZeroSimJSON["position_transform_scale"] = new JArray(_positionTransformScale.x, _positionTransformScale.y, _positionTransformScale.z);
            ZeroSimJSON["mesh_transform_scale"]     = new JArray(_meshTransformScale.x, _meshTransformScale.y, _meshTransformScale.z);
            ZeroSimJSON["asset_bundle"]             = DocumentName.ToLower();

            // create the root game object that contains the ZOSimDocumentRoot
            GameObject rootGameObject = new GameObject(ZeroSimJSON["document_name"].Value <string>());

            // add the document root component
            _documentRoot = rootGameObject.AddComponent <ZOSimDocumentRoot>();
            string zosimSaveToFilePath = Path.Combine(RootExportDirectory, DocumentName + ".zosim");
            string zosimSaveToFilePathUnityRelative = MakeRelativePath(Application.dataPath, zosimSaveToFilePath);

            // deserialize the ZoSim JSON file
            _documentRoot.ZOSimDocumentFilePath = zosimSaveToFilePathUnityRelative;
            _documentRoot.Deserialize(ZeroSimJSON);



            // turn off self collisions
            rootGameObject.AddComponent <ZO.Util.ZOTurnOffSelfCollision>();

            // NOTE:  occurrence handling is happening now in the occurrence.
            // We may want to do some asset handling of occurrence stuff though here when an occurrence has assets.
            // foreach (JObject occurrence in ZeroSimJSON["occurrences"]) {
            //     OnOccurrence(occurrence, rootGameObject, ZeroSimJSON);
            // }


            // save prefab
            string prefabFilePath = Path.Combine(RelativeRootExportDirectory, DocumentName + ".prefab");

            prefabFilePath = AssetDatabase.GenerateUniqueAssetPath(prefabFilePath);

            Debug.Log("INFO: Saving Prefab: " + prefabFilePath);

            PrefabUtility.SaveAsPrefabAsset(rootGameObject, prefabFilePath);

            // Save ZoSim file
            File.WriteAllText(zosimSaveToFilePath, ZeroSimJSON.ToString());

            // force Unity to load the assets
            UnityEditor.AssetDatabase.SaveAssets();
            UnityEditor.AssetDatabase.Refresh();


            // Add the directory we exported to (ExportDirectory + DocumentName) as an asset bundle
            AssetImporter assetImporter = AssetImporter.GetAtPath(RelativeRootExportDirectory);

            assetImporter.SetAssetBundleNameAndVariant(DocumentName, "");

            // build the asset bundle
            Debug.Log("INFO: Building asset bundles...");
            BuildPipeline.BuildAssetBundles(AssetBundlesDirectory, BuildAssetBundleOptions.None, BuildTarget.StandaloneLinux64);


            ZeroSimProjectFile = null; // need to reset
        }
Пример #10
0
 public override void Deserialize(ZOSimDocumentRoot documentRoot, JObject json)
 {
     Name         = json["name"].Value <string>();
     ROSTopic     = json["ros_topic"].Value <string>();
     UpdateRateHz = json["update_rate_hz"].Value <float>();
 }
Пример #11
0
 public void Deserialize(ZOSimDocumentRoot documentRoot, JObject json)
 {
     throw new System.NotImplementedException("TODO!");
 }