예제 #1
0
 public static void SaveToFile(string file, FileSaving config)
 {
     lock (_lock)
     {
         var xns = new System.Xml.Serialization.XmlSerializerNamespaces();
         System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(config.GetType());
         System.IO.Stream stream;
         if (config.GetType().Name != "opencv_storage")
         {
             stream = new System.IO.MemoryStream();
         }
         else
         {
             System.IO.File.WriteAllText(file, "");
             stream = System.IO.File.OpenWrite(file);
         }
         xns.Add(string.Empty, string.Empty);
         x.Serialize(stream, config, xns);
         if (config.GetType().Name != "opencv_storage")
         {
             stream.Position = 0;
             byte[] bs = new byte[stream.Length];
             ((System.IO.MemoryStream)stream).Read(bs, 0, bs.Length);
             string s = xmlHeader + "<opencv_storage>" +
                        System.Text.Encoding.UTF8.GetString(bs).Replace(xmlHeader, "") + "</opencv_storage>";
             System.IO.File.WriteAllText(file, s);
         }
         stream.Close();
     }
 }
예제 #2
0
	/// <summary>
	/// used by loadFileDialog
	/// </summary>
	/// <param name="dir">Dir.</param>
	static void loadFileDialog_callback(string dir)
	{
		//lastUsedDirectory = dir;
		Debug.Log("loaded file " + dir);
		if (dir=="Cancel_pressed")
			return;
		//remove all world objects currently in scene (except for body/hands)
		worldObject[] goArray = UnityEngine.MonoBehaviour.FindObjectsOfType(typeof(worldObject)) as worldObject[];
		List<string> doNotRemove = new List<string>() { "leftHand", "rightHand", "mainBody" };
		foreach (worldObject obj in goArray)
		{
			if (!doNotRemove.Contains(obj.objectName))
			{
				Debug.Log("destroying " + obj.objectName);
				Destroy(obj.gameObject);
			}
		}

		/*customItemController[] goA = UnityEngine.MonoBehaviour.FindObjectsOfType(typeof(customItemController)) as customItemController[];
		foreach (customItemController c in goA)
		{
			string wName = c.objectName;
			Debug.Log("have item " + wName);
		}*/

		FileSaving g = new FileSaving(dir); //loads the file
	}
예제 #3
0
    /// <summary>
    /// opens fileName and automatically loads it over the current task
    /// </summary>
    /// <param name="fileName">File name.</param>
    public FileSaving(string fileName)
    {
        loadObjs();
        //load from fileName
        Stream          s      = File.OpenRead(fileName);
        BinaryFormatter bf     = new BinaryFormatter();
        FileSaving      loaded = (FileSaving)bf.Deserialize(s);

        s.Close();
        //copy data from the loaded class to this
        taskDescriptor              = loaded.taskDescriptor;
        worldObjects                = loaded.worldObjects;
        bodyX                       = loaded.bodyX;
        bodyY                       = loaded.bodyY;
        bodyRotation                = loaded.bodyRotation;
        rightHandX                  = loaded.rightHandX;
        rightHandY                  = loaded.rightHandY;
        leftHandX                   = loaded.leftHandX;
        leftHandY                   = loaded.leftHandY;
        gravityX                    = loaded.gravityX;
        gravityY                    = loaded.gravityY;
        gameSpeed                   = loaded.gameSpeed;
        centerCamera                = loaded.centerCamera;
        showDetailedVisionMarkers   = loaded.showDetailedVisionMarkers;
        showPeripheralVisionMarkers = loaded.showPeripheralVisionMarkers;

        loadToCurrentTask();
    }
        private static void SaveFile()
        {
            FileSaving?.Invoke();

            var bytes = Serialize(_data);

            File.WriteAllBytes(_savePath, bytes);
        }
예제 #5
0
    void OnGUI()
    {
        //Debug.Log("hi");
        GUILayout.BeginHorizontal();

        GUILayout.Label("PAGI-World\nA physically realistic simulation environment for artificial general intelligence systems");

        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();

        if (GUILayout.Button("Load Main Task"))
        {
            Application.LoadLevel("scene");
        }

                #if UNITY_EDITOR
        if (GUILayout.Button("Load Task From File"))
        {
            string path = (UnityEditor.EditorUtility.OpenFilePanel(
                               "Open Task File",
                               "",
                               "tsk"));
            if (path != "" && path != null)
            {
                Application.LoadLevel("scene");
                //remove all world objects currently in scene (except for body/hands)
                worldObject[] goArray     = UnityEngine.MonoBehaviour.FindObjectsOfType(typeof(worldObject)) as worldObject[];
                List <string> doNotRemove = new List <string>()
                {
                    "leftHand", "rightHand", "mainBody"
                };
                foreach (worldObject obj in goArray)
                {
                    if (!doNotRemove.Contains(obj.objectName))
                    {
                        //Debug.Log("destroying " + obj.objectName);
                        Destroy(obj.gameObject);
                    }
                }

                FileSaving g = new FileSaving(path);
            }
            //Application.LoadLevel("scene");
        }
                #endif

        GUILayout.EndHorizontal();
    }
예제 #6
0
    void OnGUI()
    {
        //Debug.Log("hi");
        GUILayout.BeginHorizontal();

        GUILayout.Label("PAGI-World\nA physically realistic simulation environment for artificial general intelligence systems");

        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();

        if (GUILayout.Button("Load Main Task"))
            Application.LoadLevel("scene");

        #if UNITY_EDITOR
            if (GUILayout.Button("Load Task From File"))
            {
                string path = (UnityEditor.EditorUtility.OpenFilePanel(
                    "Open Task File",
                    "",
                    "tsk"));
                if (path!="" && path!=null)
                {
                    Application.LoadLevel("scene");
                    //remove all world objects currently in scene (except for body/hands)
                    worldObject[] goArray = UnityEngine.MonoBehaviour.FindObjectsOfType(typeof(worldObject)) as worldObject[];
                    List<string> doNotRemove = new List<string>() { "leftHand", "rightHand", "mainBody" };
                    foreach (worldObject obj in goArray)
                    {
                        if (!doNotRemove.Contains(obj.objectName))
                        {
                            //Debug.Log("destroying " + obj.objectName);
                            Destroy(obj.gameObject);
                        }
                    }

                    FileSaving g = new FileSaving(path);
                }
                //Application.LoadLevel("scene");
            }
        #endif

        GUILayout.EndHorizontal();
    }
예제 #7
0
	/// <summary>
	/// used by saveFileDialog
	/// </summary>
	/// <param name="dir">Dir.</param>
	static void saveFileDialog_callback(string s)
	{
		//lastUsedDirectory = s;
		if (s!="" && s!=null)
		{
			if (s=="Cancel_pressed")
				return;
			bool noErrors = true;
			try {
				FileSaving f = new FileSaving();
				f.taskDescriptor = "Default task descriptor";
				Debug.Log("Saving to file " + s);
				f.writeToFile(s);
			}
			catch(System.Exception e)
			{
				GlobalVariables.messageDisplay.showMessage("There was an error: " + e.ToString(), null, "Error");
				noErrors = false;
			}
			if (noErrors)
				GlobalVariables.messageDisplay.showMessage("File Saved Successfully!", null, "Awesome!");
		}
	}
예제 #8
0
        public async Task <IActionResult> Upload([FromForm] IFormFile fileData)
        {
            try
            {
                if (fileData == null)
                {
                    return(BadRequest("null file"));
                }
                if (fileData.Length == 0)
                {
                    return(BadRequest("empty file"));
                }
                if (!accepted_FileTypes.Any(s => s == Path.GetExtension(fileData.FileName).ToLower()))
                {
                    return(BadRequest("invalid file type."));
                }
                var folderName = Path.Combine("Resources", "Files");
                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
                var fileName   = ContentDispositionHeaderValue.Parse(fileData.ContentDisposition).FileName.Trim('"');

                var fullpath = Path.Combine(pathToSave, fileName);

                using (var stream = new FileStream(fullpath, FileMode.Create))
                {
                    await fileData.CopyToAsync(stream);
                }
                var fileSaving = new FileSaving(mapper, fileRepository);
                await fileSaving.SavingFileDataToDataBase(fullpath);


                return(Ok());
            }
            catch (Exception)
            {
                return(StatusCode(500, "internal server error"));
            }
        }
예제 #9
0
 public virtual void Save()
 {
     FileSaving.SaveToFile(fileName, this);
 }
예제 #10
0
 /// <summary>
 /// The OnFileSaving
 /// </summary>
 /// <param name="e">The e<see cref="FileSavingEventArgs"/></param>
 protected virtual void OnFileSaving(FileSavingEventArgs e)
 {
     FileSaving?.Invoke(this, e);
 }
예제 #11
0
    // Update is called once per frame
    void Update()
    {
        if (GlobalVariables.centerCamera) //scroll camera
        {
            //Vector2 newLeft =
            if (mainCamera == null)
                Debug.Log("no camera");
            else
                mainCamera.transform.Translate((transform.position - mainCamera.transform.position) - new Vector3(0,0,10));
        }

        //Debug.Log(rigidbody2D.transform.rotation*new Vector2(0,100));
        //Debug.Log (rigidbody2D.position);
        //visualSensors[15,1].updateSensor();
        //Debug.Log(visualSensors[15,1].name);
        checkReflexes();

        //check for messages in the message queue (which stores all messages sent by TCP clients)
        while (messageQueue.Count() > 0)
        {
            AIMessage firstMsg;
            while (!messageQueue.TryGet(0, out firstMsg))
                Thread.Sleep(100);
            /*Debug.Log (messageQueue.Count() + " MESSAGES IN QUEUE: " + firstMsg.ToString());
            for (int i=0; i<messageQueue.Count(); i++)
            {
                AIMessage a;
                while (!messageQueue.TryGet(i, out a))
                    Thread.Sleep(100);
                Debug.Log("message " + i.ToString() + ": " + a.ToString());
            }*/
            while (!messageQueue.TryRemoveAt(0))
                Thread.Sleep(100);
            //process firstMsg
            firstMsg.stringContent = firstMsg.stringContent.Trim();
            switch (firstMsg.messageType)
            {
            case AIMessage.AIMessageType.other:
                Debug.Log("received unrecognized command from client connection " + firstMsg.stringContent);
                outgoingMessages.Add("UnrecognizedCommandError:" + firstMsg.stringContent.Trim() + "\n");
                break;
            case AIMessage.AIMessageType.createItem:
                Debug.Log("Received command to create item");
                Dictionary<string,System.Object> dd = (Dictionary<string,System.Object>)firstMsg.detail;
                string wName = (string)dd["name"];
                customItemController cic = Instantiate(emptyblock, new Vector3(), new Quaternion()) as customItemController;
                if (!cic.initialize((string)dd["filePath"], wName, new Vector2((float)dd["x"], (float)dd["y"]),
                               (float)dd["rotation"], (float)dd["endorphins"], (float)dd["mass"], (int)dd["friction"], (int)dd["kinematic"]))
                {
                    Debug.Log("file " + (string)dd["filePath"] + " not found");
                    outgoingMessages.Add("createItem,"+(string)dd["name"]+",FAILED,fileNotFound\n");
                }
                else
                {
                    while (customItems.ContainsKey(wName))
                    {
                        if (customItems[wName] != null)
                        {
                            Destroy(customItems[wName].gameObject);
                        }
                        customItems.Remove(wName);
                    }
                    customItems.Add(wName,cic);

                    outgoingMessages.Add("createItem,"+(string)dd["name"]+",OK\n");
                }
                break;
            case AIMessage.AIMessageType.addForceToItem:
                Debug.Log ("Received command to addForceToItem");
                //iterate through the customItems, remove any that no longer exist
                List<string> toRemove = new List<string>();
                foreach (string ky in customItems.Keys)
                    if (customItems[ky]==null)
                        toRemove.Add(ky);
                foreach (string ky in toRemove)
                    customItems.Remove(ky);
                //find the item to add force to, add it
                if (!customItems.ContainsKey(firstMsg.stringContent))
                {
                    outgoingMessages.Add("addForceToItem," + firstMsg.stringContent + ",ERR:Item_Name_Not_Found\n");
                }
                else
                {
                    if (customItems[firstMsg.stringContent] == null)
                    {
                        customItems.Remove(firstMsg.stringContent);
                        outgoingMessages.Add("addForceToItem," + firstMsg.stringContent + ",ERR:Object_Deleted\n");
                    }
                    else
                    {
                        customItems[firstMsg.stringContent].rigidbody2D.AddForce(firstMsg.vectorContent);
                        customItems[firstMsg.stringContent].rigidbody2D.AddTorque(firstMsg.floatContent);
                        outgoingMessages.Add("addForceToItem," + firstMsg.stringContent + ",OK\n");
                    }
                }
                break;
            case AIMessage.AIMessageType.getInfoAboutItem:
                Debug.Log ("Received command to getInfoAboutItem");
                //find the item to add force to, add it
                if (!customItems.ContainsKey(firstMsg.stringContent))
                {
                    outgoingMessages.Add("getInfoAboutItem," + firstMsg.stringContent + ",ERR:Item_Name_Not_Found\n");
                }
                else
                {
                    if (customItems[firstMsg.stringContent] == null)
                    {
                        customItems.Remove(firstMsg.stringContent);
                        outgoingMessages.Add("getInfoAboutItem," + firstMsg.stringContent + ",ERR:Object_Deleted\n");
                    }
                    else
                    {
                        worldObject wo = customItems[firstMsg.stringContent];
                        string toReturn = "getInfoAboutItem," + firstMsg.stringContent + ",";
                        toReturn = toReturn + wo.transform.position.x.ToString() + "," + wo.transform.position.y.ToString() + ",";
                        toReturn = toReturn + wo.rigidbody2D.velocity.x.ToString() + "," + wo.rigidbody2D.velocity.y.ToString() + "\n";
                        outgoingMessages.Add(toReturn);
                    }
                }
                break;
            case AIMessage.AIMessageType.destroyItem:
                Debug.Log ("Received command to destroyItem");
                //find the item to add force to, add it
                if (!customItems.ContainsKey(firstMsg.stringContent))
                {
                    outgoingMessages.Add("destroyItem," + firstMsg.stringContent + ",ERR:Item_Name_Not_Found\n");
                }
                else
                {
                    if (customItems[firstMsg.stringContent] == null)
                    {
                        customItems.Remove(firstMsg.stringContent);
                        outgoingMessages.Add("destroyItem," + firstMsg.stringContent + ",WARNING:Object_Already_Deleted\n");
                    }
                    else
                    {
                        Destroy(customItems[firstMsg.stringContent].gameObject);
                        customItems.Remove(firstMsg.stringContent);
                        outgoingMessages.Add("destroyItem," + firstMsg.stringContent + ",OK\n");
                    }
                }
                break;
            case AIMessage.AIMessageType.print:
                Debug.Log("received command to print message");
                Debug.Log("AI-side says: " + firstMsg.stringContent);
                outgoingMessages.Add("print,OK\n");
                break;
            case AIMessage.AIMessageType.findObj:
                Debug.Log("received message to find object: " + firstMsg.stringContent);
                string toReturn = "findObj," + firstMsg.stringContent;
                string searchType = ((string)firstMsg.detail).Trim();
                //Debug.Log(searchType);
                if (searchType == "D" || searchType == "PD")
                {
                    //Debug.Log("Checking detailed sensor");
                    foreach (visualSensor v in visualSensors)
                    {
                        v.updateSensor();
                        if (v.name.Trim() == firstMsg.stringContent.Trim())
                            toReturn += ",V" + v.indexX.ToString() + "." + v.indexY.ToString();
                    }
                }
                if (searchType == "P" || searchType == "PD")
                {
                    foreach (visualSensor p in peripheralSensors)
                    {
                        p.updateSensor();
                        if (p.name.Trim() == firstMsg.stringContent.Trim())
                            toReturn += ",P" + p.indexX.ToString() + "." + p.indexY.ToString();
                    }
                }
                outgoingMessages.Add(toReturn + "\n");
                break;

            case AIMessage.AIMessageType.loadTask:
                Debug.Log("received message to load new task");
                toReturn = "loadTask," + firstMsg.stringContent.Trim();
                //remove all world objects currently in scene (except for body/hands)
                worldObject[] goArray = UnityEngine.MonoBehaviour.FindObjectsOfType(typeof(worldObject)) as worldObject[];
                List<string> doNotRemove = new List<string>() { "leftHand", "rightHand", "mainBody" };
                foreach (worldObject obj in goArray)
                {
                    if (!doNotRemove.Contains(obj.objectName))
                    {
                        Destroy(obj.gameObject);
                    }
                }
                bool loadedOk = true;
                try
                {
                    FileSaving fs = new FileSaving(firstMsg.stringContent);
                }
                catch(Exception e)
                {
                    string errDesc = e.ToString().Replace('\n',';');
                    errDesc = errDesc.Replace('\r',' ');
                    outgoingMessages.Add(toReturn + ",ERR," + errDesc + "\n");
                    loadedOk = false;
                }
                if (loadedOk)
                    outgoingMessages.Add(toReturn + ",OK\n");
                break;

            case AIMessage.AIMessageType.setState:
                //is the state already active? If so, replace the time
                State foundState = null;
                foreach (State st in GlobalVariables.activeStates.getCopy())
                {
                    if (st.stateName == firstMsg.stringContent)
                    {
                        foundState = st;
                        break;
                    }
                }
                //Debug.Log("foundstate for " + firstMsg.stringContent + " " + (foundState!=null).ToString());
                if (foundState!=null)
                {
                    //replace state
                    GlobalVariables.activeStates.TryRemove(foundState);
                }
                if (((State)firstMsg.detail).lifeTime != TimeSpan.Zero)
                    GlobalVariables.activeStates.Add((State)firstMsg.detail);
                outgoingMessages.Add("stateUpdated," + firstMsg.stringContent.Trim() + "\n");
                break;

            case AIMessage.AIMessageType.getReflexes:
                string toR = "activeReflexes";
                foreach (Reflex r in GlobalVariables.activeReflexes.getCopy())
                {
                    toR += "," + r.reflexName;
                }
                outgoingMessages.Add(toR + "\n");
                break;

            case AIMessage.AIMessageType.getStates:
                toR = "activeStates:";
                List<State> allStates = GlobalVariables.activeStates.getCopy();
                foreach (State sta in allStates)
                {
                    toR += sta.stateName + ",";
                }
                if (allStates.Count == 0)
                    toR += "(none)";
                else
                    toR = toR.Substring(0, toR.Length-1);
                outgoingMessages.Add(toR + "\n");
                break;
            case AIMessage.AIMessageType.removeReflex:
                Reflex re = null;
                foreach (Reflex R in GlobalVariables.activeReflexes.getCopy())
                {
                    Debug.Log("comparing " + R.reflexName + " to " + firstMsg.stringContent);
                    if (R.reflexName.Trim() == firstMsg.stringContent.Trim())
                    {
                        re = R;
                        break;
                    }
                }
                if (re!=null)
                {
                    GlobalVariables.activeReflexes.TryRemove(re);
                    outgoingMessages.Add("removedReflex," + firstMsg.stringContent.Trim() + ",OK\n");
                }
                else
                    outgoingMessages.Add("removedReflexFAILED" + firstMsg.stringContent.Trim() + ",FAILED\n");

                break;
            case AIMessage.AIMessageType.setReflex:
                //does a reflex with this name already exist? If so, replace it
                re = null;
                foreach (Reflex R in GlobalVariables.activeReflexes.getCopy())
                {
                    if (R.reflexName.Trim() == firstMsg.stringContent.Trim())
                    {
                        re = R;
                        break;
                    }
                }
                if (re!=null)
                    GlobalVariables.activeReflexes.TryRemove(re);
                GlobalVariables.activeReflexes.Add((Reflex)firstMsg.detail);
                outgoingMessages.Add("reflexUpdated," + firstMsg.stringContent + "\n");
                break;

            case AIMessage.AIMessageType.dropItem:
                Debug.Log("received command to create " + firstMsg.stringContent + " at " + firstMsg.vectorContent);
                //if required, there is additional content at firstMsg.detail
                //find the asset that matches the name
                bool loaded = false;
                foreach (worldObject s in Resources.LoadAll<worldObject>("Prefabs"))
                {
                    if (s.objectName==firstMsg.stringContent.Trim())
                    {
                        worldObject newObj =  MonoBehaviour.Instantiate(s,//Resources.Load<GameObject>(wo.assetPath)
                                                                        new Vector3(firstMsg.vectorContent.x, firstMsg.vectorContent.y),
                                                                        new Quaternion()) as worldObject;
                        loaded = true;
                        break;
                    }
                }
                if (!loaded)
                    outgoingMessages.Add("dropItem," + firstMsg.stringContent + ",FAILED:obj_not_found\n");
                else
                    outgoingMessages.Add("dropItem," + firstMsg.stringContent + ",OK\n");
                break;
            case AIMessage.AIMessageType.addForce:
                Debug.Log("executing addForce command: " + firstMsg.messageType.ToString());
                //do we need to evaluate the force value, e.g. if there is a function?
                switch (firstMsg.stringContent)
                {
                    case "TEST":
                        /*string s = "";
                        int numToSend = int.Parse(firstMsg.floatContent.ToString());
                        Debug.Log("creating string ("+numToSend.ToString()+")");
                        for (int i=0; i<numToSend; i++)
                            s += "X";*/
                        Debug.Log("got TEST msg: " + firstMsg.function1.evaluate(getSensorAspectValue));
                        //outgoingMessages.Add(s+'\n');
                        break;
                    /*LHV,LHH - Left hand vertical and horizontal. v is the amount of force (positive or negative) to add in each dimension.
                    RHV,RHH - Right hand vertical and horizontal. v is the amount of force (positive or negative) to add in each dimension.
                    BMV,BMH - Body vertical and horizontal. v is the amount of force (positive or negative) to add in each dimension.
                    BR - Body rotation right or left. v is the amount of torque to use to rotate the body (can be positive or negative).
                    RHG,RHR - Right hand grip and release. v is required, but ignored here. A hand is either in a state of gripping or it isn't.
                    LHG,LHR - Left hand grip and release. v is required, but ignored here. A hand is either in a state of gripping or it isn't.*/
                    case "LHH":
                        Vector2 f = rigidbody2D.transform.rotation*new Vector2(firstMsg.function1.evaluate(getSensorAspectValue),0);//new Vector2(Mathf.Cos(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Sin(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent);
                        leftHandRigidBody.AddForce(f);
                        rigidbody2D.AddForce(-f);
                        //rigidbody2D.AddForce(new Vector2(0, 10000));
                        outgoingMessages.Add("LHH,1\n");
                    break;
                    case "LHV":
                        f = rigidbody2D.transform.rotation*new Vector2(0,firstMsg.function1.evaluate(getSensorAspectValue));//new Vector2(Mathf.Sin(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Cos(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent);
                        leftHandRigidBody.AddForce(f);//, ForceMode2D.Impulse);
                        rigidbody2D.AddForce(-f);
                        outgoingMessages.Add("LHV,1\n");
                    break;
                    case "LHvec":
                        f = rigidbody2D.transform.rotation*
                            (new Vector2(firstMsg.function1.evaluate(getSensorAspectValue), firstMsg.function2.evaluate(getSensorAspectValue)));
                        leftHandRigidBody.AddForce(f);//, ForceMode2D.Impulse);
                        rigidbody2D.AddForce(-f);
                        outgoingMessages.Add("LHvec,1\n");
                        break;
                    case "RHH":
                        f = rigidbody2D.transform.rotation*new Vector2(firstMsg.function1.evaluate(getSensorAspectValue),0);//new Vector2(Mathf.Cos(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Sin(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent);
                        rightHandRigidBody.AddForce(f);
                        rigidbody2D.AddForce(-f);
                        //rigidbody2D.AddForce(new Vector2(0, 10000));
                        outgoingMessages.Add("RHH,1\n");
                    break;
                    case "RHV":
                        f = rigidbody2D.transform.rotation*new Vector2(0,firstMsg.function1.evaluate(getSensorAspectValue));//new Vector2(Mathf.Sin(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Cos(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent);
                        rightHandRigidBody.AddForce(f);//, ForceMode2D.Impulse);
                        rigidbody2D.AddForce(-f);
                        outgoingMessages.Add("RHV,1\n");
                    break;
                    case "RHvec":
                        f = rigidbody2D.transform.rotation*
                            (new Vector2(firstMsg.function1.evaluate(getSensorAspectValue), firstMsg.function2.evaluate(getSensorAspectValue)));;
                        rigidbody2D.AddForce(-f);
                        rightHandRigidBody.AddForce(f);
                        outgoingMessages.Add("RHvec,1\n");
                        break;
                    case "BMH":
                        f = rigidbody2D.transform.rotation*new Vector2(firstMsg.function1.evaluate(getSensorAspectValue),0);//new Vector2(Mathf.Cos(Mathf.Deg2Rad*rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Sin(Mathf.Deg2Rad*rigidbody2D.rotation)*firstMsg.floatContent);
                        rigidbody2D.AddForce(f);
                        outgoingMessages.Add("BMH,1\n");
                    break;
                    case "BMV":
                        f = rigidbody2D.transform.rotation*new Vector2(0,firstMsg.function1.evaluate(getSensorAspectValue));//new Vector2(Mathf.Sin(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Cos(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent);
                        rigidbody2D.AddForce(f);
                        Debug.Log("added f: " + f.y);
                        outgoingMessages.Add("BMV,1\n");
                    break;
                    case "BMvec":
                        f = rigidbody2D.transform.rotation*
                            (new Vector2(firstMsg.function1.evaluate(getSensorAspectValue), firstMsg.function2.evaluate(getSensorAspectValue)));
                        rigidbody2D.AddForce(f);
                        outgoingMessages.Add("BMvec,1\n");
                        break;

                    case "J": //jump
                        bool foundGround = jump(30000f);
                        if (foundGround)
                            outgoingMessages.Add("J,1\n");
                        else
                            outgoingMessages.Add("J,0\n");
                        break;
                    case "BR":
                        rigidbody2D.rotation += firstMsg.function1.evaluate(getSensorAspectValue);
                        leftHand.rigidbody2D.rotation = rigidbody2D.rotation;
                        rightHand.rigidbody2D.rotation = rigidbody2D.rotation;
                        rigidbody2D.AddForce(Vector2.zero); //forces update of rotation
                        outgoingMessages.Add ("BR,1\n");
                    break;
                    case "RHG":
                        setGrip(false, true);
                        outgoingMessages.Add ("RHG,1\n");
                        break;
                    case "RHR":
                        setGrip(false, false);
                        outgoingMessages.Add ("RHR,1\n");
                        break;
                    case "LHG":
                        setGrip(true, true);
                        outgoingMessages.Add ("LHG,1\n");
                        break;
                    case "LHR":
                        setGrip(true, false);
                        outgoingMessages.Add ("LHR,1\n");
                        break;
                }
                break;
            case AIMessage.AIMessageType.sensorRequest:
                Debug.Log("checking sensor value " + firstMsg.ToString());
                switch (firstMsg.stringContent[0])
                {
                    case 'M': //a full map of the visual field
                        if (firstMsg.stringContent.Trim() == "MDN") //detailed visual field (names only)
                        {
                            StringBuilder sb = new StringBuilder("MDN,");
                            //string toReturn = "MDN,";
                            for (int y=0; y<numVisualSensorsY; y++)
                            {
                                for (int x=0; x<numVisualSensorsX; x++)
                                {
                                    visualSensor s = visualSensors[x,y];
                                    s.updateSensor();
                                    string sName = s.name;
                                    if (sName=="Background")
                                        sName = "";
                                    sb.Append(sName + ",");
                                }
                            }
                            sb[sb.Length-1] = '\n';
                            Debug.Log("msg is " + sb.ToString());
                            outgoingMessages.Add(sb.ToString());
                        }
                        else if (firstMsg.stringContent.Trim() == "MPN") //peripheral visual field (names only)
                        {
                            StringBuilder sb = new StringBuilder("MPN,");
                            int count = 0;
                            for (int y=0; y<numPeripheralSensorsY; y++)
                            {
                                for (int x=0; x<numPeripheralSensorsX; x++)
                                {
                                    visualSensor s = peripheralSensors[x,y];
                                    s.updateSensor();
                                    string sName = s.name;
                                    if (sName=="Background")
                                        sName = "";
                                    sb.Append(sName + ",");
                                    count++;
                                }
                            }
                            Debug.Log(count);
                            sb[sb.Length-1] = '\n';
                            outgoingMessages.Add(sb.ToString());
                        }
                        else
                            outgoingMessages.Add("sensorRequest,UNRECOGNIZED_SENSOR_ERROR:"+firstMsg.stringContent.Trim()+"\n");
                    break;
                    case 'B': //body touch sensor B0-B7
                        if (firstMsg.stringContent[1]=='P') //body position
                        {
                            Vector2 v = rigidbody2D.position;
                            outgoingMessages.Add("BP," + v.x.ToString() + "," + v.y.ToString() + "\n");
                        }
                        else
                        {
                            int sensorNum = int.Parse(firstMsg.stringContent[1].ToString());
                            touchSensor sensor = bodySensor[sensorNum];
                            sensor.updateSensor();
                            outgoingMessages.Add("B" + sensorNum.ToString() + "," + sensor.getReport() + "\n");
                        }
                    break;
                    case 'S': //speed sensor
                        Vector2 v = rigidbody2D.GetRelativePointVelocity(Vector2.zero);
                        outgoingMessages.Add ("S," + v.x.ToString () + "," + v.y.ToString() + "\n");
                        break;
                    case 'L': //L0-L4, or LP
                        if (firstMsg.stringContent[1]=='P')
                        {//proprioception; get sensor position relative to body
                            leftHandSensor[4].updateSensor(); //recall sensor 4 is right in the middle of the hand
                            Vector2 relativePoint = rigidbody2D.GetPoint(leftHandSensor[4].getPosition());
                            outgoingMessages.Add("LP," + relativePoint.x.ToString () + "," + relativePoint.y.ToString() + "\n");

                        }
                        else
                        {
                            int sensorNum = int.Parse(firstMsg.stringContent[1].ToString());
                            touchSensor sensor = leftHandSensor[sensorNum];
                            sensor.updateSensor();
                            outgoingMessages.Add("L" + sensorNum.ToString() + "," + sensor.getReport() + "\n");
                        }//test
                    break;
                    case 'R': //R0-R4, or RP
                        if (firstMsg.stringContent[1]=='P')
                        {//proprioception; get sensor position relative to body
                            rightHandSensor[4].updateSensor();
                        Vector2 relativePoint = rigidbody2D.GetPoint(rightHandSensor[4].getPosition());
                            outgoingMessages.Add("RP," + relativePoint.x.ToString () + "," + relativePoint.y.ToString() + "\n");
                        }
                        else
                        {
                            int sensorNum = int.Parse(firstMsg.stringContent[1].ToString());
                            touchSensor sensor = rightHandSensor[sensorNum];
                            sensor.updateSensor();
                            outgoingMessages.Add("R" + sensorNum.ToString() + "," + sensor.getReport() + "\n");
                        }
                    break;
                    case 'V': //visual sensor V0.0 - V30.20
                        string[] tmp = firstMsg.stringContent.Substring(1).Split('.');
                        //Debug.Log(tmp[0] + ", " + tmp[1]);
                        int x = int.Parse(tmp[0]);
                        int y = int.Parse(tmp[1]);
                        visualSensor s = visualSensors[x,y];
                        s.updateSensor();
                        string response = firstMsg.stringContent.Trim();
                        for (int i=0; i<s.vq.Length; i++)
                            response += "," + s.vq[i].ToString();
                        response += "," + s.type + "," + s.name + "\n";
                        outgoingMessages.Add(response);
                    break;
                    case 'P': //peripheral sensor V0.0 - V15.10
                        tmp = firstMsg.stringContent.Substring(1).Split('.');
                        //Debug.Log(tmp[0] + ", " + tmp[1]);
                        x = int.Parse(tmp[0]);
                        y = int.Parse(tmp[1]);
                        s = peripheralSensors[x,y];
                        s.updateSensor();
                        response = firstMsg.stringContent.Trim();
                        for (int i=0; i<s.vq.Length; i++)
                            response += "," + s.vq[i].ToString();
                        response += "," + s.type + "," + s.name + "\n";
                        outgoingMessages.Add(response);
                    break;
                    case 'A': //rotation sensor
                        outgoingMessages.Add("A," + (Mathf.Deg2Rad*rigidbody2D.rotation).ToString() + "\n");
                    break;
                    default:
                        outgoingMessages.Add("sensorRequest,UNRECOGNIZED_SENSOR_ERROR:"+firstMsg.stringContent.Trim()+"\n");
                    break;
                }
                //TODO
                break;
            case AIMessage.AIMessageType.establishConnection:
                break;
            case AIMessage.AIMessageType.removeConnection:
                break;
            default:
                break;
            }
        }

        //update arm positions
        //leftHand.objectName = "hi";
        Vector2 leftRelativePoint = gameObject.rigidbody2D.GetRelativePoint(leftHand.GetComponent<DistanceJoint2D>().connectedAnchor);
        Vector3 leftAnchor = new Vector3(leftRelativePoint.x, leftRelativePoint.y);
        leftArm[0].transform.position = (leftHand.transform.position*1/3 + leftAnchor*2/3);
        leftArm[1].transform.position = (leftHand.transform.position*2/3 + leftAnchor*1/3);
        Vector2 rightRelativePoint = gameObject.rigidbody2D.GetRelativePoint(rightHand.GetComponent<DistanceJoint2D>().connectedAnchor);
        Vector3 rightAnchor = new Vector3(rightRelativePoint.x, rightRelativePoint.y);
        rightArm[0].transform.position = (rightHand.transform.position*1/3 + rightAnchor*2/3);
        rightArm[1].transform.position = (rightHand.transform.position*2/3 + rightAnchor*1/3);

        //updateSensors();

        //////keyboard controls///////

        //hand gripping
        if (Input.GetKeyDown(KeyCode.LeftShift))
            setGrip(true, true);
        if (Input.GetKeyUp(KeyCode.LeftShift))
            setGrip(true, false);
        if (Input.GetKeyDown(KeyCode.RightShift))
            setGrip(false, true);
        if (Input.GetKeyUp(KeyCode.RightShift))
            setGrip(false, false);

        if (Input.GetKeyDown(KeyCode.P))
            powerMode = !powerMode;
        float handMoveForce = 50f;
        if (powerMode)
            handMoveForce *= 10;
        //right hand
        if (Input.GetKey(KeyCode.UpArrow)) {//GetKeyDown is one-time press only
            //transform.Translate(new Vector3(1,0,0));
            Vector2 f = rigidbody2D.transform.rotation*new Vector2(0,handMoveForce);//new Vector2(Mathf.Sin(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Cos(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent);
            rightHandRigidBody.AddForce(f);//, ForceMode2D.Impulse);
            rigidbody2D.AddForce(-f);
        }
        if (Input.GetKey (KeyCode.DownArrow)) {
            Vector2 f = rigidbody2D.transform.rotation*new Vector2(0,-handMoveForce);//new Vector2(Mathf.Sin(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Cos(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent);
            rightHandRigidBody.AddForce(f);//, ForceMode2D.Impulse);
            rigidbody2D.AddForce(-f);
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            Vector2 f = rigidbody2D.transform.rotation*new Vector2(-handMoveForce,0);//new Vector2(Mathf.Sin(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Cos(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent);
            rightHandRigidBody.AddForce(f);//, ForceMode2D.Impulse);
            rigidbody2D.AddForce(-f);
        }
        if (Input.GetKey(KeyCode.RightArrow))
        {
            Vector2 f = rigidbody2D.transform.rotation*new Vector2(handMoveForce,0);//new Vector2(Mathf.Sin(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Cos(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent);
            rightHandRigidBody.AddForce(f);//, ForceMode2D.Impulse);
            rigidbody2D.AddForce(-f);
        }
        //left hand
        if (Input.GetKey (KeyCode.W)) {//GetKeyDown is one-time press only
            //transform.Translate(new Vector3(1,0,0));
            Vector2 f = rigidbody2D.transform.rotation*new Vector2(0,handMoveForce);//new Vector2(Mathf.Sin(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Cos(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent);
            leftHandRigidBody.AddForce(f);
            rigidbody2D.AddForce(-f);
        }
        if (Input.GetKey (KeyCode.S)) {
            Vector2 f = rigidbody2D.transform.rotation*new Vector2(0,-handMoveForce);//new Vector2(Mathf.Sin(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Cos(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent);
            leftHandRigidBody.AddForce(f);
            rigidbody2D.AddForce(-f);
        }
        if (Input.GetKey(KeyCode.A))
        {
            Vector2 f = rigidbody2D.transform.rotation*new Vector2(-handMoveForce,0);//new Vector2(Mathf.Sin(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Cos(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent);
            leftHandRigidBody.AddForce(f);
            rigidbody2D.AddForce(-f);
        }
        if (Input.GetKey(KeyCode.D))
        {
            Vector2 f = rigidbody2D.transform.rotation*new Vector2(handMoveForce,0);//new Vector2(Mathf.Sin(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent,Mathf.Cos(Mathf.Deg2Rad*-rigidbody2D.rotation)*firstMsg.floatContent);
            leftHandRigidBody.AddForce(f);
            rigidbody2D.AddForce(-f);
        }

        /*if (Input.GetKeyDown(KeyCode.LeftShift))
        {
            leftHandRigidBody.AddForce(new Vector2(-1000, 0));
            rightHandRigidBody.AddForce(new Vector2(-1000, 0));
            rigidbody2D.AddForce(new Vector2(2000, 0));
        }
        if (Input.GetKeyDown(KeyCode.RightShift))
        {
            leftHandRigidBody.AddForce(new Vector2(1000, 0));
            rightHandRigidBody.AddForce(new Vector2(1000, 0));
            rigidbody2D.AddForce(new Vector2(-2000, 0));
        }*/

        if (Input.GetKeyDown(KeyCode.Space))
            jump(30000f);
        if (Input.GetKey(KeyCode.V))
            GlobalVariables.viewControlsVisible = true;

        //Rotate
        if (Input.GetKey(KeyCode.R))
        {
            rigidbody2D.rotation += 1.0f;
            rigidbody2D.rotation %= 360f;
            leftHandRigidBody.rotation = rigidbody2D.rotation;
            rightHandRigidBody.rotation = rigidbody2D.rotation;
            //Debug.Log (rigidbody2D.GetRelativePoint(rightAnchor));
            rigidbody2D.AddForce(new Vector2(0,0)); //this forces the screen to update his rotation
        }
        if (Input.GetKey(KeyCode.T))
        {
            rigidbody2D.rotation -= 1.0f;
            rigidbody2D.rotation %= 360f;
            leftHandRigidBody.rotation = rigidbody2D.rotation;
            rightHandRigidBody.rotation = rigidbody2D.rotation;
            //Debug.Log (rigidbody2D.GetRelativePoint(rightAnchor));
            rigidbody2D.AddForce(new Vector2(0,0)); //this forces the screen to update his rotation
        }

        //Move
        if (Input.GetKey(KeyCode.F))
            rigidbody2D.AddForce(rigidbody2D.transform.rotation*(new Vector2(-500f,0)));
        if (Input.GetKey(KeyCode.G))
            rigidbody2D.AddForce(transform.rotation*new Vector2(500f,0));
    }
예제 #12
0
    /// <summary>
    /// used by loadFileDialog
    /// </summary>
    /// <param name="dir">Dir.</param>
    static void loadFileDialog_callback(string dir)
    {
        //lastUsedDirectory = dir;
        Debug.Log("loaded file " + dir);
        if (dir=="Cancel_pressed")
            return;
        //remove all world objects currently in scene (except for body/hands)
        worldObject[] goArray = UnityEngine.MonoBehaviour.FindObjectsOfType(typeof(worldObject)) as worldObject[];
        List<string> doNotRemove = new List<string>() { "leftHand", "rightHand", "mainBody" };
        foreach (worldObject obj in goArray)
        {
            if (!doNotRemove.Contains(obj.objectName))
            {
                Debug.Log("destroying " + obj.objectName);
                Destroy(obj.gameObject);
            }
        }

        /*customItemController[] goA = UnityEngine.MonoBehaviour.FindObjectsOfType(typeof(customItemController)) as customItemController[];
        foreach (customItemController c in goA)
        {
            string wName = c.objectName;
            Debug.Log("have item " + wName);
        }*/

        FileSaving g = new FileSaving(dir); //loads the file
    }
예제 #13
0
 /// <summary>
 /// used by saveFileDialog
 /// </summary>
 /// <param name="dir">Dir.</param>
 static void saveFileDialog_callback(string s)
 {
     //lastUsedDirectory = s;
     if (s!="" && s!=null)
     {
         if (s=="Cancel_pressed")
             return;
         bool noErrors = true;
         try {
             FileSaving f = new FileSaving();
             f.taskDescriptor = "Default task descriptor";
             Debug.Log("Saving to file " + s);
             f.writeToFile(s);
         }
         catch(System.Exception e)
         {
             GlobalVariables.messageDisplay.showMessage("There was an error: " + e.ToString(), null, "Error");
             noErrors = false;
         }
         if (noErrors)
             GlobalVariables.messageDisplay.showMessage("File Saved Successfully!", null, "Awesome!");
     }
 }
 private void OnFileSaving(object sender, FileSavingArgs e)
 {
     FileSaving?.Invoke(this, e);
 }
예제 #15
0
 private void OnFileSaving(string path)
 {
     Log.InfoF($"Saving file: {path}...");
     FileSaving?.Invoke(this, path);
 }