public static void RigTo(GameObject child, GameObject parent) { // disable child voxeme component Voxeme voxeme = child.GetComponent <Voxeme>(); if (voxeme != null) { voxeme.enabled = false; } child.transform.parent = parent.transform; //Debug.LogWarning(child.name + " rigged to " + parent.name); if (!child.GetComponent <Rigging>().usePhysicsRig) { if (parent.transform.Find(string.Format("{0}_collision_clone", child.name)) == null) { GameObject childCollisionClone = GameObject.Instantiate(child, child.transform.position, child.transform.rotation); foreach (Renderer renderer in childCollisionClone.GetComponentsInChildren <Renderer>()) { renderer.enabled = false; } childCollisionClone.transform.parent = parent.transform; BoxCollider[] colliders = childCollisionClone.GetComponentsInChildren <BoxCollider>(); foreach (BoxCollider collider in colliders) { if (collider.gameObject != childCollisionClone) { if (collider != null) { collider.isTrigger = false; } } } FixedJoint[] fixedJoints = childCollisionClone.GetComponentsInChildren <FixedJoint>(); foreach (FixedJoint fixedJoint in fixedJoints) { Object.Destroy(fixedJoint); } Rigidbody[] rigidbodies = childCollisionClone.GetComponentsInChildren <Rigidbody>(); foreach (Rigidbody rigidbody in rigidbodies) { Object.Destroy(rigidbody); } childCollisionClone.name = childCollisionClone.name.Replace("(Clone)", "_collision_clone"); } } }
public static GameObject RandomVoxeme() { List <Voxeme> allVoxemes = GameObject.Find("VoxWorld").GetComponent <ObjectSelector>().allVoxemes.ToList(); Voxeme voxeme = allVoxemes[RandomInt(0, allVoxemes.Count, (int)RangeFlags.MinInclusive)]; while (Helper.GetMostImmediateParentVoxeme(voxeme.gameObject).gameObject.transform.parent != null) { voxeme = allVoxemes[RandomInt(0, allVoxemes.Count, (int)RangeFlags.MinInclusive)]; } return(voxeme.gameObject); }
public static GameObject RandomVoxeme(List <GameObject> fromList, List <GameObject> exclude) { Voxeme voxeme = fromList[RandomInt(0, fromList.Count, (int)RangeFlags.MinInclusive)] .GetComponent <Voxeme>(); while ((Helper.GetMostImmediateParentVoxeme(voxeme.gameObject).gameObject.transform.parent != null) || (exclude.Contains(voxeme.gameObject))) { voxeme = fromList[RandomInt(0, fromList.Count, (int)RangeFlags.MinInclusive)].GetComponent <Voxeme>(); } return(voxeme.gameObject); }
public static void UnRig(GameObject child, GameObject parent) { // disable child voxeme component Voxeme voxeme = child.GetComponent <Voxeme>(); if (voxeme != null) { voxeme.enabled = true; } child.transform.parent = null; Transform childCollisionClone = parent.transform.Find(string.Format("{0}_collision_clone", child.name)); if (childCollisionClone != null) { Object.Destroy(childCollisionClone.gameObject); } }
// updating memory happens in LateUpdate after all visual perception happened in Update (See SyntheticVision) void Update() { ShowMemory = _interactionPrefs.showVisualMemory; if (!ShowMemory) { MemoryCanvas.SetActive(false); } else { MemoryCanvas.SetActive(true); } foreach (GameObject obj in _world.availableObjs) { Voxeme voxeme = obj.GetComponent <Voxeme>(); // Debug.Log(voxeme + " is visible?"); List <GameObject> clones = null; if (_vision.IsVisible(voxeme)) { // Debug.Log(voxeme + " is"); if (!_memorized.ContainsKey(voxeme)) { clones = GetVisualClone(obj.gameObject); _memorized.Add(voxeme, clones); if (!_perceivingInitialConfiguration) { // don't do this when you initially populate knownObjects // but otherwise // surprise! // todo _surpriseArgs can be plural _surpriseArgs = new VisionEventArgs(voxeme, InconsistencyType.Present); foreach (var clone in clones) { StartCoroutine(clone.GetComponent <BoundBox>().Flash(10)); } Debug.Log(string.Format("{0} Surprise!", voxeme)); _reactionTimer.Enabled = true; } } else { clones = _memorized[voxeme]; } } // block is not visible else { // Debug.Log(voxeme + " is not "); // but I know about it if (_memorized.ContainsKey(voxeme)) { clones = _memorized[voxeme]; // but I see it's not where it supposed to be! if (clones.All(clone => _vision.IsVisible(clone))) { // surprise! _surpriseArgs = new VisionEventArgs(voxeme, InconsistencyType.Missing); foreach (var clone in clones) { StartCoroutine(clone.GetComponent <BoundBox>().Flash(10)); Destroy(clone, 3); } _memorized.Remove(voxeme); Debug.Log(string.Format("{0} Surprise!", voxeme)); _reactionTimer.Enabled = true; } } } if (clones == null || clones.Count == 0) { continue; } foreach (var clone in clones) { if (_objectSelector.disabledObjects.Contains(voxeme.gameObject)) { clone.transform.parent = null; clone.SetActive(true); } else if (clone.transform.parent != null) { clone.transform.SetParent(voxeme.gameObject.transform); } BoundBox highlighter = clone.GetComponent <BoundBox>(); if (_vision.IsVisible(voxeme)) { highlighter.lineColor = new Color(0.0f, 1.0f, 0.0f, 0.2f); } else { highlighter.lineColor = new Color(1.0f, 0.0f, 0.0f, 0.8f); } } } if (_memorized.Count > 0 && _perceivingInitialConfiguration) { // effectively this goes false after the first frame _perceivingInitialConfiguration = false; } if (_surprise) { NewInformation(_surpriseArgs); _surprise = false; } }
public VisionEventArgs(Voxeme voxeme, InconsistencyType inconsistency) { Voxeme = voxeme; Inconsistency = inconsistency; }
private void UnknownSeen(Voxeme voxeme) { string color = voxeme.voxml.Attributes.Attrs[0].Value; // just grab the first one for now OutputHelper.PrintOutput(Role.Affector, string.Format("I didn't know that {0} block was there!", color)); }
private void KnownUnseen(Voxeme voxeme) { string color = voxeme.voxml.Attributes.Attrs[0].Value; // just grab the first one for now OutputHelper.PrintOutput(Role.Affector, string.Format("Holy cow! What happened to the {0} block?", color)); }
void OnGUI() { //testing skins - amy GUI.skin = customSkin; if (DrawInspector) { inspectorPositionAdjX = inspectorPosition.x; inspectorPositionAdjY = inspectorPosition.y; if (inspectorPosition.x + inspectorWidth > Screen.width) { if (inspectorPosition.y > Screen.height - inspectorMargin) { inspectorPositionAdjX = inspectorPosition.x - inspectorWidth; inspectorPositionAdjY = inspectorPosition.y - inspectorHeight; inspectorRect = new Rect (inspectorPosition.x - inspectorWidth, inspectorPosition.y - inspectorHeight, inspectorWidth, inspectorHeight); } else if (inspectorPosition.y + inspectorHeight > Screen.height) { inspectorPositionAdjX = inspectorPosition.x - inspectorWidth; inspectorRect = new Rect (inspectorPosition.x - inspectorWidth, inspectorPosition.y, inspectorWidth, Screen.height - inspectorPosition.y); } else { inspectorPositionAdjX = inspectorPosition.x - inspectorWidth; inspectorRect = new Rect (inspectorPosition.x - inspectorWidth, inspectorPosition.y, inspectorWidth, inspectorHeight); } } else if (inspectorPosition.y > Screen.height - inspectorMargin) { inspectorPositionAdjY = inspectorPosition.y - inspectorHeight; inspectorRect = new Rect (inspectorPosition.x, inspectorPosition.y - inspectorHeight, inspectorWidth, inspectorHeight); } else if (inspectorPosition.y + inspectorHeight > Screen.height) { inspectorRect = new Rect (inspectorPosition.x, inspectorPosition.y, inspectorWidth, Screen.height - inspectorPosition.y); } else { inspectorRect = new Rect (inspectorPosition.x, inspectorPosition.y, inspectorWidth, inspectorHeight); } GUILayout.BeginArea (inspectorRect, GUI.skin.window); scrollPosition = GUILayout.BeginScrollView (scrollPosition, false, false); if (inspectorState == InspectorState.Main) { GUILayout.BeginVertical (GUI.skin.box); inspectorStyle = GUI.skin.button; inspectorChoice = GUILayout.SelectionGrid(inspectorChoice, inspectorMenuItems, 1, inspectorStyle, GUILayout.ExpandWidth(true)); GUILayout.EndVertical(); if (inspectorChoice == (int)InspectorMainOptions.Reify) { // Reify inspectorChoice = -1; inspectorState = InspectorState.Reify; } else if (inspectorChoice == (int)InspectorMainOptions.Markup) { // View/Edit Markup inspectorChoice = -1; inspectorState = InspectorState.Markup; } else if (inspectorChoice == (int)InspectorMainOptions.Modify) { // Modify inspectorChoice = -1; inspectorState = InspectorState.Modify; } else if (inspectorChoice == (int)InspectorMainOptions.Delete) { // Delete inspectorChoice = -1; inspectorState = InspectorState.Delete; } } else if (inspectorState == InspectorState.Reify) { inspectorStyle = GUI.skin.box; GUILayout.BeginVertical (inspectorStyle); newName = GUILayout.TextField (newName, 25); inspectorChoice = GUILayout.SelectionGrid(inspectorChoice, new string[]{"Create","Cancel"}, 2, GUI.skin.button, GUILayout.ExpandWidth(true)); GUILayout.EndVertical (); if (inspectorChoice == (int)InspectorReifyOptions.Create) { // Create if (newName != "") { assetManager.ReifyAs(newName,objectSelector.selectedObjects); inspectorChoice = -1; newName = ""; DrawInspector = false; } } else if (inspectorChoice == (int)InspectorReifyOptions.Cancel) { // Cancel inspectorChoice = -1; newName = ""; DrawInspector = false; } } else if (inspectorState == InspectorState.Markup) { if (File.Exists(inspectorObject.name + ".xml")) { if (!ObjectLoaded(inspectorObject)) { loadedObject = LoadMarkup(inspectorObject); markupCleared = false; } } else { if (!markupCleared) { InitNewMarkup(); loadedObject = new Voxeme(); } } inspectorStyle = GUI.skin.box; inspectorStyle.wordWrap = true; inspectorStyle.alignment = TextAnchor.MiddleLeft; GUILayout.BeginVertical (inspectorStyle); GUILayout.Label("LEX"); GUILayout.BeginHorizontal (inspectorStyle); GUILayout.Label("Pred"); mlPred = GUILayout.TextField (mlPred, 25, GUILayout.Width(100)); GUILayout.EndHorizontal (); GUILayout.BeginVertical (inspectorStyle); GUILayout.BeginHorizontal (); GUILayout.Label("Type"); GUILayout.BeginVertical (); for (int i = 0; i < mlTypeCount; i++) { GUILayout.BeginHorizontal (); if (mlTypeSelectVisible[i] == 0) { GUILayout.BeginVertical (inspectorStyle); mlTypeSelected[i] = -1; mlTypeSelected[i] = GUILayout.SelectionGrid(mlTypeSelected[i], mlTypeOptions, 1, listStyle, GUILayout.Width(70), GUILayout.ExpandWidth(true)); if (mlTypeSelected[i] != -1) { mlTypes[i] = mlTypeOptions[mlTypeSelected[i]]; mlTypeSelectVisible[i] = -1; } GUILayout.EndVertical (); } else { mlTypeSelectVisible[i] = GUILayout.SelectionGrid(mlTypeSelectVisible[i], new string[]{mlTypes[i]}, 1, GUI.skin.button, GUILayout.Width(70), GUILayout.ExpandWidth(true)); } if (i != 0) { // can't remove first type mlRemoveType[i] = GUILayout.SelectionGrid(mlRemoveType[i], new string[]{"-"}, 1, GUI.skin.button, GUILayout.ExpandWidth(true)); } GUILayout.EndHorizontal (); } GUILayout.EndVertical (); GUILayout.EndHorizontal (); mlAddType = GUILayout.SelectionGrid(mlAddType, new string[]{"+"}, 1, GUI.skin.button, GUILayout.ExpandWidth(true)); if (mlAddType == 0) { // add new type mlTypeCount++; mlTypes.Add (""); mlTypeSelectVisible.Add (-1); mlTypeSelected.Add (-1); mlRemoveType.Add(-1); mlAddType = -1; } for (int i = 0; i < mlTypeCount; i++) { if (mlRemoveType[i] == 0) { mlRemoveType[i] = -1; mlTypes.RemoveAt(i); mlRemoveType.RemoveAt(i); mlTypeCount--; } } GUILayout.EndVertical (); GUILayout.EndVertical (); GUILayout.BeginVertical (inspectorStyle); GUILayout.Label("TYPE"); GUILayout.BeginHorizontal (inspectorStyle); GUILayout.Label("Head"); if (mlHeadSelectVisible == 0) { GUILayout.BeginVertical (inspectorStyle); mlHeadSelected = -1; mlHeadSelected = GUILayout.SelectionGrid(mlHeadSelected, mlHeadOptions, 1, listStyle, GUILayout.Width(70), GUILayout.ExpandWidth(true)); if (mlHeadSelected != -1) { mlHead = mlHeadOptions[mlHeadSelected]; mlHeadSelectVisible = -1; } GUILayout.EndVertical (); } else { mlHeadSelectVisible = GUILayout.SelectionGrid(mlHeadSelectVisible, new string[]{mlHead}, 1, GUI.skin.button, GUILayout.Width(70), GUILayout.ExpandWidth(true)); } GUILayout.EndHorizontal (); GUILayout.BeginVertical (inspectorStyle); GUILayout.BeginHorizontal (); GUILayout.Label("Components"); mlAddComponent = GUILayout.SelectionGrid(mlAddComponent, new string[]{"+"}, 1, GUI.skin.button, GUILayout.ExpandWidth(true)); GUILayout.EndHorizontal (); if (mlAddComponent == 0) { // add new component mlComponentCount++; mlComponents.Add (""); mlAddComponent = -1; } for (int i = 0; i < mlComponentCount; i++) { GUILayout.BeginHorizontal (); mlComponents[i] = GUILayout.TextField (mlComponents[i], 25, GUILayout.Width(115)); mlRemoveComponent.Add (-1); mlRemoveComponent[i] = GUILayout.SelectionGrid(mlRemoveComponent[i], new string[]{"-"}, 1, GUI.skin.button, GUILayout.ExpandWidth(true)); GUILayout.EndHorizontal (); } for (int i = 0; i < mlComponentCount; i++) { if (mlRemoveComponent[i] == 0) { mlRemoveComponent[i] = -1; mlComponents.RemoveAt(i); mlRemoveComponent.RemoveAt(i); mlComponentCount--; } } GUILayout.EndVertical(); GUILayout.BeginHorizontal (inspectorStyle); GUILayout.Label("Concavity"); if (mlConcavitySelectVisible == 0) { GUILayout.BeginVertical (inspectorStyle); mlConcavitySelected = -1; mlConcavitySelected = GUILayout.SelectionGrid(mlConcavitySelected, mlConcavityOptions, 1, listStyle, GUILayout.Width(70), GUILayout.ExpandWidth(true)); if (mlConcavitySelected != -1) { mlConcavity = mlConcavityOptions[mlConcavitySelected]; mlConcavitySelectVisible = -1; } GUILayout.EndVertical (); } else { mlConcavitySelectVisible = GUILayout.SelectionGrid(mlConcavitySelectVisible, new string[]{mlConcavity}, 1, GUI.skin.button, GUILayout.Width(70), GUILayout.ExpandWidth(true)); } GUILayout.EndHorizontal (); GUILayout.BeginVertical (inspectorStyle); GUILayout.Label("Rotational Symmetry"); GUILayout.BeginHorizontal (); mlRotatSymX = GUILayout.Toggle(mlRotatSymX,"X"); mlRotatSymY = GUILayout.Toggle(mlRotatSymY,"Y"); mlRotatSymZ = GUILayout.Toggle(mlRotatSymZ,"Z"); GUILayout.EndHorizontal (); GUILayout.EndVertical (); GUILayout.BeginVertical (inspectorStyle); GUILayout.Label("Reflectional Symmetry"); GUILayout.BeginHorizontal (); mlReflSymXY = GUILayout.Toggle(mlReflSymXY,"XY"); mlReflSymXZ = GUILayout.Toggle(mlReflSymXZ,"XZ"); mlReflSymYZ = GUILayout.Toggle(mlReflSymYZ,"YZ"); GUILayout.EndHorizontal (); GUILayout.EndVertical (); GUILayout.EndVertical (); GUILayout.BeginVertical (inspectorStyle); GUILayout.Label("HABITAT"); GUILayout.BeginVertical (inspectorStyle); GUILayout.BeginHorizontal (); GUILayout.Label("Intrinsic"); mlAddIntrHabitat = GUILayout.SelectionGrid(mlAddIntrHabitat, new string[]{"+"}, 1, GUI.skin.button, GUILayout.ExpandWidth(true)); if (mlAddIntrHabitat == 0) { // add new intrinsic habitat formula mlIntrHabitatCount++; mlIntrHabitats.Add ("Name=Formula"); mlAddIntrHabitat = -1; } GUILayout.EndHorizontal (); for (int i = 0; i < mlIntrHabitatCount; i++) { GUILayout.BeginHorizontal (); mlIntrHabitats[i] = GUILayout.TextField (mlIntrHabitats[i].Split(new char[]{'='})[0], 25, GUILayout.Width(50)) + "=" + GUILayout.TextField (mlIntrHabitats[i].Split(new char[]{'='})[1], 25, GUILayout.Width(60)); mlRemoveIntrHabitat.Add (-1); mlRemoveIntrHabitat[i] = GUILayout.SelectionGrid(mlRemoveIntrHabitat[i], new string[]{"-"}, 1, GUI.skin.button, GUILayout.ExpandWidth(true)); GUILayout.EndHorizontal (); } for (int i = 0; i < mlIntrHabitatCount; i++) { if (mlRemoveIntrHabitat[i] == 0) { mlRemoveIntrHabitat[i] = -1; mlIntrHabitats.RemoveAt(i); mlRemoveIntrHabitat.RemoveAt(i); mlIntrHabitatCount--; } } GUILayout.EndVertical (); GUILayout.BeginVertical (inspectorStyle); GUILayout.BeginHorizontal (); GUILayout.Label("Extrinsic"); mlAddExtrHabitat = GUILayout.SelectionGrid(mlAddExtrHabitat, new string[]{"+"}, 1, GUI.skin.button, GUILayout.ExpandWidth(true)); if (mlAddExtrHabitat == 0) { // add new extrinsic habitat formula mlExtrHabitatCount++; mlExtrHabitats.Add ("Name=Formula"); mlAddExtrHabitat = -1; } GUILayout.EndHorizontal (); for (int i = 0; i < mlExtrHabitatCount; i++) { GUILayout.BeginHorizontal (); mlExtrHabitats[i] = GUILayout.TextField (mlExtrHabitats[i].Split(new char[]{'='})[0], 25, GUILayout.Width(50)) + "=" + GUILayout.TextField (mlExtrHabitats[i].Split(new char[]{'='})[1], 25, GUILayout.Width(60)); mlRemoveExtrHabitat.Add (-1); mlRemoveExtrHabitat[i] = GUILayout.SelectionGrid(mlRemoveExtrHabitat[i], new string[]{"-"}, 1, GUI.skin.button, GUILayout.ExpandWidth(true)); GUILayout.EndHorizontal (); } for (int i = 0; i < mlExtrHabitatCount; i++) { if (mlRemoveExtrHabitat[i] == 0) { mlRemoveExtrHabitat[i] = -1; mlExtrHabitats.RemoveAt(i); mlRemoveExtrHabitat.RemoveAt(i); mlExtrHabitatCount--; } } GUILayout.EndVertical (); GUILayout.EndVertical (); GUILayout.BeginVertical (inspectorStyle); GUILayout.Label("AFFORD_STR"); GUILayout.BeginVertical (inspectorStyle); for (int i = 0; i < mlAffordanceCount; i++) { GUILayout.BeginHorizontal (); mlAffordances[i] = GUILayout.TextField (mlAffordances[i], 25, GUILayout.Width(115)); mlRemoveAffordance.Add (-1); mlRemoveAffordance[i] = GUILayout.SelectionGrid(mlRemoveAffordance[i], new string[]{"-"}, 1, GUI.skin.button, GUILayout.ExpandWidth(true)); GUILayout.EndHorizontal (); } for (int i = 0; i < mlAffordanceCount; i++) { if (mlRemoveAffordance[i] == 0) { mlRemoveAffordance[i] = -1; mlAffordances.RemoveAt(i); mlRemoveAffordance.RemoveAt(i); mlAffordanceCount--; } } mlAddAffordance = GUILayout.SelectionGrid(mlAddAffordance, new string[]{"+"}, 1, GUI.skin.button, GUILayout.ExpandWidth(true)); if (mlAddAffordance == 0) { // add new affordance mlAffordanceCount++; mlAffordances.Add (""); mlAddAffordance = -1; } GUILayout.EndVertical (); GUILayout.EndVertical (); GUILayout.BeginVertical (inspectorStyle); GUILayout.Label("EMBODIMENT"); GUILayout.BeginHorizontal (inspectorStyle); GUILayout.Label("Scale"); if (mlScaleSelectVisible == 0) { GUILayout.BeginVertical (inspectorStyle); mlScaleSelected = -1; mlScaleSelected = GUILayout.SelectionGrid(mlScaleSelected, mlScaleOptions, 1, listStyle, GUILayout.Width(70), GUILayout.ExpandWidth(true)); if (mlScaleSelected != -1) { mlScale = mlScaleOptions[mlScaleSelected]; mlScaleSelectVisible = -1; } GUILayout.EndVertical (); } else { mlScaleSelectVisible = GUILayout.SelectionGrid(mlScaleSelectVisible, new string[]{mlScale}, 1, GUI.skin.button, GUILayout.Width(70), GUILayout.ExpandWidth(true)); } GUILayout.EndHorizontal (); GUILayout.BeginHorizontal (inspectorStyle); GUILayout.Label("Movable"); mlMovable = GUILayout.Toggle(mlMovable,""); GUILayout.EndHorizontal (); GUILayout.EndVertical (); GUILayout.BeginVertical (GUI.skin.box); inspectorStyle = GUI.skin.button; inspectorChoice = GUILayout.SelectionGrid(inspectorChoice, new string[]{"Save"}, 1, GUI.skin.button, GUILayout.ExpandWidth(true)); GUILayout.EndVertical (); if (inspectorChoice == (int)InspectorMarkupOptions.Save) { // Save inspectorChoice = -1; SaveMarkup(inspectorObject); DrawInspector = false; } } else if (inspectorState == InspectorState.Modify) { inspectorStyle = GUI.skin.box; GUILayout.BeginVertical (inspectorStyle); GUILayout.Label("Scale"); GUILayout.BeginHorizontal (inspectorStyle); GUILayout.BeginHorizontal (inspectorStyle); GUILayout.Label("X"); xScale = GUILayout.TextField (xScale, 25, GUILayout.Width(28)); GUILayout.EndHorizontal (); GUILayout.BeginHorizontal (inspectorStyle); GUILayout.Label("Y"); yScale = GUILayout.TextField (yScale, 25, GUILayout.Width(28)); GUILayout.EndHorizontal (); GUILayout.BeginHorizontal (inspectorStyle); GUILayout.Label("Z"); zScale = GUILayout.TextField (zScale, 25, GUILayout.Width(28)); GUILayout.EndHorizontal (); GUILayout.EndHorizontal (); inspectorChoice = GUILayout.SelectionGrid(inspectorChoice, new string[]{"Apply"}, 1, GUI.skin.button, GUILayout.ExpandWidth(true)); GUILayout.EndVertical (); if (inspectorChoice == (int)InspectorModifyOptions.Apply) { // Apply inspectorObject.transform.localScale = new Vector3(inspectorObject.transform.localScale.x*System.Convert.ToSingle(xScale), inspectorObject.transform.localScale.y*System.Convert.ToSingle(yScale), inspectorObject.transform.localScale.z*System.Convert.ToSingle(zScale)); xScale = "1"; yScale = "1"; zScale = "1"; DrawInspector = false; } } else if (inspectorState == InspectorState.Delete) { objectSelector.selectedObjects.Remove(inspectorObject); inspectorObject.SetActive(false); inspectorObject = null; DrawInspector = false; } GUILayout.EndScrollView (); GUILayout.EndArea (); if (inspectorState == InspectorState.Markup) { Vector2 textDimensions = GUI.skin.label.CalcSize (new GUIContent (inspectorObject.name)); GUI.Label (new Rect (((2 * inspectorPositionAdjX + inspectorWidth) / 2) - textDimensions.x / 2, inspectorPositionAdjY, textDimensions.x, 25), inspectorObject.name); } } }
// A plan path that run faster and more smooth public void PlanPath2(Vector3 startPos, Vector3 goalPos, out List <Vector3> path, GameObject obj, params object[] constraints) { Debug.Log("========== In plan ========= " + goalPos); cameFrom = new Dictionary <Vector3, Vector3>(); gScore = new Dictionary <Vector3, float>(); hScore = new Dictionary <Vector3, float>(); specialNodes = new HashSet <Vector3>(); // init empty path path = new List <Vector3>(); MinHeap <Vector3> openSet = new MinHeap <Vector3>(new BetterHeuristic(gScore, hScore)); var openSetForCheck = new HashSet <Vector3>(); // Closed set can be used because euclidean distance is monotonic var closedSet = new HashSet <Vector3>(); var objectBound = Helper.GetObjectWorldSize(obj); Vector3 size = Helper.GetObjectWorldSize(obj).size; Vector3 increment = defaultIncrement; foreach (object constraint in constraints) { if (constraint is string) { if ((constraint as string).Contains('X')) { increment = new Vector3(0.0f, increment.y, increment.z); } if ((constraint as string).Contains('Y')) { increment = new Vector3(increment.x, 0.0f, increment.z); } if ((constraint as string).Contains('Z')) { increment = new Vector3(increment.x, increment.y, 0.0f); } } } int step = 1; Debug.Log(" ======== size.magnitude ====== " + size.magnitude); Debug.Log(" ======== defaultIncrement.magnitude ====== " + defaultIncrement.magnitude); // if (size.magnitude > defaultIncrement.magnitude) { // step = (int) (size.magnitude / defaultIncrement.magnitude) + 1; // // increment = new Vector3 (size.x / step, size.y / step, size.z / step); // } Debug.Log(" ======== increment ====== " + increment); Debug.Log(" ======== step ====== " + step); openSet.Add(startPos); openSetForCheck.Add(startPos); Vector3 endPos = new Vector3(); // if constraints contain a voxeme Voxeme testTarget = constraints.OfType <Voxeme>().FirstOrDefault(); if (testTarget != null) { Debug.Log(testTarget); // if that object is concave (e.g. cup) // if goalPos is within the bounds of target (e.g. in cup) if (testTarget.voxml.Type.Concavity.Contains("Concave") && Helper.GetObjectWorldSize(testTarget.gameObject).Contains(goalPos)) { // This endPos is special, and requires a special handling to avoid path not found var specialPos = new Vector3(goalPos.x, Helper.GetObjectWorldSize(testTarget.gameObject).max.y + size.y, goalPos.z); endPos = specialPos; specialNodes.Add(specialPos); Debug.Log(" ======== special ====== " + Helper.VectorToParsable(specialPos)); } else { endPos = LookForClosest(goalPos, obj, increment); } } else { endPos = LookForClosest(goalPos, obj, increment); } gScore[startPos] = 0; //hScore [startPos] = new Vector3 (endPos.x - startPos.x, endPos.y - startPos.y, endPos.z - startPos.z).magnitude; hScore[startPos] = GetHScoreErgonomic(startPos, goalPos); Debug.Log(" ========= obj.transform.position ======== " + Helper.VectorToParsable(obj.transform.position)); Debug.Log(" ======== start ====== " + Helper.VectorToParsable(startPos)); Debug.Log(" ======== goal ====== " + Helper.VectorToParsable(goalPos)); Debug.Log(" ======== end ====== " + Helper.VectorToParsable(endPos)); // starting with startNode, for each neighborhood node of last node, assess A* heuristic // using best node found until endNode reached int counter = 0; Vector3 curPos = new Vector3(); float bestMagnitude = Mathf.Infinity; Vector3 bestLastPos = new Vector3(); if ((goalPos - startPos).magnitude > (goalPos - endPos).magnitude) { Debug.Log(string.Format("{0}-{1}={2}", Helper.VectorToParsable(goalPos), Helper.VectorToParsable(startPos), (goalPos - startPos).magnitude)); Debug.Log(string.Format("{0}-{1}={2}", Helper.VectorToParsable(goalPos), Helper.VectorToParsable(endPos), (goalPos - endPos).magnitude)); while (openSet.Count > 0 && counter < counterMax) { // O(1) curPos = openSet.TakeMin(); Debug.Log(counter + " ======== curNode ====== (" + Helper.VectorToParsable(curPos) + ") " + gScore[curPos] + " " + hScore[curPos] + " " + (gScore[curPos] + hScore[curPos])); float currentDistance = (curPos - endPos).magnitude; if (currentDistance < bestMagnitude) { bestMagnitude = currentDistance; bestLastPos = curPos; } // short cut // if reached end node if ((curPos - endPos).magnitude < Constants.EPSILON) { Debug.Log("=== counter === " + counter); // extend path to goal node (goal position) cameFrom[goalPos] = curPos; path = ReconstructPath2(startPos, goalPos); Debug.Log("====== path ===== "); foreach (var point in path) { Debug.Log(Helper.VectorToParsable(point)); } return; } closedSet.Add(curPos); var neighbors = GetNeighborNodes(obj, curPos, increment, step); foreach (var neighbor in neighbors) { if (!closedSet.Contains(neighbor) && !IsBlocked(objectBound, curPos, neighbor)) { float tentativeGScore = GetGScoreErgonomic(curPos, neighbor); if (gScore.ContainsKey(neighbor) && tentativeGScore > gScore[neighbor]) { continue; } cameFrom[neighbor] = curPos; gScore[neighbor] = tentativeGScore; hScore[neighbor] = GetHScoreErgonomic(neighbor, goalPos); // Debug.Log ("=== candidate === (" + neighbor + ") " + gScore [neighbor] + " " + hScore [neighbor] + " " + (gScore [neighbor] + hScore [neighbor])); // If neighbor is not yet in openset // Add it // Heap is automatically rearranged if (!openSet.Has(neighbor)) { Debug.Log("=== Add candidate === (" + Helper.VectorToParsable(neighbor) + ")"); openSet.Add(neighbor); } else { // If neighbor is already there, update the heap Debug.Log("=== Update candidate === (" + Helper.VectorToParsable(neighbor) + ")"); openSet.Update(neighbor); } } } counter += 1; } } else // if the dist from startPos to goalPos < dist from goalPos to endPos (aka closest non-start node to endPos) { cameFrom[goalPos] = startPos; bestLastPos = goalPos; } path = ReconstructPath2(startPos, bestLastPos); Debug.Log("====== path ===== "); foreach (var point in path) { Debug.Log(point); } }
public static void ReasonFromAffordances(String program, Voxeme obj) { Regex reentrancyForm = new Regex (@"\[[0-9]+\]"); List<string> supportedRelations = new List<string> ( new string[]{ @"on\(.*\)", // list of supported relations @"in\(.*\)" }); // TODO: move externally, draw from voxeme database List<string> genericRelations = new List<string> ( new string[]{ @"behind\(.*\)", // list of habitat-independent relations @"in_front\(.*\)", @"left\(.*\)", @"right\(.*\)", @"touching\(.*\)" }); // TODO: move externally, draw from voxeme database // get relation tracker RelationTracker relationTracker = (RelationTracker)GameObject.Find ("BehaviorController").GetComponent("RelationTracker"); // get bounds of theme object of program Bounds objBounds = Helper.GetObjectWorldSize(obj.gameObject); // get list of all voxeme entities Voxeme[] allVoxemes = UnityEngine.Object.FindObjectsOfType<Voxeme>(); // reactivate physics by default bool reactivatePhysics = true; obj.minYBound = objBounds.min.y; // reasoning from affordances foreach (Voxeme test in allVoxemes) { if (test.gameObject != obj.gameObject) { // foreach voxeme // get bounds of object being tested against Bounds testBounds = Helper.GetObjectWorldSize (test.gameObject); if (!test.gameObject.name.Contains ("*")) { // hacky fix to filter out unparented objects w/ disabled voxeme components //if (test.enabled) { // if voxeme is active OperationalVox.OpAfford_Str affStr = test.opVox.Affordance; foreach (int h in affStr.Affordances.Keys) { for (int i = 0; i < affStr.Affordances[h].Count; i++) { // condition/event/result list for this habitat index //if (test.opVox.Habitat condition blah blah) // ignore habitat conditionals for now string ev = affStr.Affordances[h][i].Item2.Item1; if (ev.Contains (program)) { //Debug.Log (test.opVox.Lex.Pred); //Debug.Log (program); foreach (string rel in supportedRelations) { Regex r = new Regex (rel); if (r.Match (ev).Length > 0) { // found a relation that might apply between these objects string relation = r.Match(ev).Groups[0].Value.Split('(')[0]; MatchCollection matches = reentrancyForm.Matches(ev); foreach (Match m in matches) { foreach (Group g in m.Groups) { int componentIndex = Helper.StringToInt ( g.Value.Replace (g.Value, g.Value.Trim (new char[]{ '[', ']' }))); //Debug.Log (componentIndex); if (test.opVox.Type.Components.FindIndex (c => c.Item3 == componentIndex) != -1) { Triple<string, GameObject, int> component = test.opVox.Type.Components.First (c => c.Item3 == componentIndex); //Debug.Log (ev.Replace(g.Value,component.Item2.name)); Debug.Log (string.Format ("Is {0} {1} {2}?", obj.gameObject.name, relation, component.Item2.name)); if (TestRelation (obj.gameObject, relation, test.gameObject)) { string result = affStr.Affordances[h][i].Item2.Item2; // things are getting a little ad hoc here if (relation == "on") { if (!((Helper.GetMostImmediateParentVoxeme (test.gameObject).GetComponent<Voxeme> ().voxml.Type.Concavity == "Concave") && (Helper.FitsIn (objBounds, testBounds)))) { //if (obj.enabled) { // obj.gameObject.GetComponent<Rigging> ().ActivatePhysics (true); //} obj.minYBound = testBounds.max.y; } } else if (relation == "in") { reactivatePhysics = false; obj.minYBound = objBounds.min.y; } if (result != "") { result = result.Replace ("x", obj.gameObject.name); // any component reentrancy ultimately inherits from the parent voxeme itself result = reentrancyForm.Replace (result, test.gameObject.name); result = Helper.GetTopPredicate (result); Debug.Log (string.Format ("{0}: {1} {2}s {3}", affStr.Affordances [h] [i].Item2.Item1, test.gameObject.name, result, obj.gameObject.name)); // TODO: maybe switch object order here below => passivize relation? relationTracker.AddNewRelation (new List<GameObject>{ test.gameObject, obj.gameObject }, result); if (result == "support") { RiggingHelper.RigTo (obj.gameObject, test.gameObject); } else if (result == "contain") { RiggingHelper.RigTo (obj.gameObject, test.gameObject); } } } } } } } } // habitat-independent relation handling foreach (string rel in genericRelations) { string relation = rel.Split('\\')[0]; // not using relation as regex here Debug.Log (string.Format ("Is {0} {1} {2}?", obj.gameObject.name, relation, test.gameObject.name)); if (TestRelation (obj.gameObject, relation, test.gameObject)) { relationTracker.AddNewRelation (new List<GameObject>{ obj.gameObject, test.gameObject }, relation); } } } } } } } } if (reactivatePhysics) { if (obj.enabled) { obj.gameObject.GetComponent<Rigging> ().ActivatePhysics (true); } } }
public bool IsVisible(Voxeme voxeme) { return(visibleObjects.Contains(voxeme)); }
public static void ResolvePhysicsRotationDiscrepancies(GameObject obj, bool macroEventSatisfied) { Voxeme voxComponent = obj.GetComponent <Voxeme>(); // find the smallest displacement angle between an axis on the main body and an axis on this rigidbody float displacementAngle = 360.0f; Quaternion rigidbodyRotation = Quaternion.identity; Rigidbody[] rigidbodies = obj.GetComponentsInChildren <Rigidbody>(); foreach (Rigidbody rigidbody in rigidbodies) { foreach (Vector3 mainBodyAxis in Constants.Axes.Values) { foreach (Vector3 rigidbodyAxis in Constants.Axes.Values) { if (Vector3.Angle(obj.transform.rotation * mainBodyAxis, rigidbody.rotation * rigidbodyAxis) < displacementAngle) { displacementAngle = Vector3.Angle(obj.transform.rotation * mainBodyAxis, rigidbody.rotation * rigidbodyAxis); rigidbodyRotation = rigidbody.rotation; } } } } if (displacementAngle == 360.0f) { displacementAngle = 0.0f; } if (displacementAngle > Mathf.Rad2Deg * Constants.EPSILON) { //Debug.Break (); //Debug.Log (obj.name); //Debug.Log (displacementAngle); Quaternion resolve = Quaternion.identity; Quaternion resolveInv = Quaternion.identity; if (voxComponent != null) { if (rigidbodies.Length > 0) { // foreach (Rigidbody rigidbody in rigidbodies) { // if (voxComponent.rotationalDisplacement.ContainsKey (rigidbody.gameObject)) { // Debug.Log (rigidbody.name); // // initial = initial rotational displacement // Quaternion initial = Quaternion.Euler (voxComponent.rotationalDisplacement [rigidbody.gameObject]); // Debug.Log (initial.eulerAngles); // // current = current rotational displacement due to physics // Quaternion current = rigidbody.transform.localRotation;// * Quaternion.Inverse ((args [0] as GameObject).transform.rotation)); // Debug.Log (current.eulerAngles); // // resolve = rotation to get from initial rotational displacement to current rotational displacement // resolve = current * Quaternion.Inverse (initial); // Debug.Log (resolve.eulerAngles); // Debug.Log ((initial * resolve).eulerAngles); // Debug.Log ((resolve * initial).eulerAngles); // // resolveInv = rotation to get from final (current rigidbody) rotation back to initial (aligned with main obj) rotation // resolveInv = initial * Quaternion.Inverse (current); // //Debug.Log (resolveInv.eulerAngles); // //rigidbody.transform.rotation = obj.transform.rotation * initial; // //rigidbody.transform.localRotation = initial;// * (args [0] as GameObject).transform.rotation; // //Debug.Log (rigidbody.transform.rotation.eulerAngles); // // //rigidbody.transform.localPosition = voxComponent.displacement [rigidbody.name]; // //rigidbody.transform.position = (args [0] as GameObject).transform.position + voxComponent.displacement [rigidbody.name]; // } // } //Debug.Break (); //Debug.Log (obj.transform.rotation.eulerAngles); //foreach (Rigidbody rigidbody in rigidbodies) { //Debug.Log (Helper.VectorToParsable (rigidbody.transform.localPosition)); //} // obj.transform.rotation = obj.transform.rotation * // (rigidbodies [0].transform.localRotation * // Quaternion.Inverse (Quaternion.Euler (voxComponent.rotationalDisplacement [rigidbodies [0].gameObject]))); //(rigidbodies [0].transform.localRotation * // obj.transform.rotation * Quaternion.Inverse (Quaternion.Euler (voxComponent.rotationalDisplacement [rigidbodies [0].gameObject]))); obj.transform.rotation = rigidbodies[0].transform.rotation * Quaternion.Inverse(Quaternion.Euler( voxComponent.rotationalDisplacement[rigidbodies[0].gameObject])); voxComponent.targetRotation = obj.transform.rotation.eulerAngles; //Debug.Log (obj.transform.rotation.eulerAngles); foreach (Rigidbody rigidbody in rigidbodies) { if (voxComponent.rotationalDisplacement.ContainsKey(rigidbody.gameObject)) { //Debug.Log (rigidbody.name); rigidbody.transform.localEulerAngles = voxComponent.rotationalDisplacement[rigidbody.gameObject]; } } // rigidbodyRotation = Quaternion.identity; // rigidbodies = obj.GetComponentsInChildren<Rigidbody> (); // foreach (Rigidbody rigidbody in rigidbodies) { // foreach (Vector3 mainBodyAxis in Constants.Axes.Values) { // foreach (Vector3 rigidbodyAxis in Constants.Axes.Values) { // if (Vector3.Angle (obj.transform.rotation * mainBodyAxis, rigidbody.rotation * rigidbodyAxis) < displacementAngle) { // displacementAngle = Vector3.Angle (obj.transform.rotation * mainBodyAxis, rigidbody.rotation * rigidbodyAxis); // rigidbodyRotation = rigidbody.rotation; // } // } // } // } } } } // TODO: Abstract away if (voxComponent != null) { if (voxComponent.children != null) { foreach (Voxeme child in voxComponent.children) { if (child.isActiveAndEnabled) { if (child.gameObject != voxComponent.gameObject) { // ResolvePhysicsPositionDiscepancies (child.gameObject); // ResolvePhysicsRotationDiscepancies (child.gameObject); if (macroEventSatisfied) { child.transform.localRotation = voxComponent.parentToChildRotationOffset[child.gameObject]; //voxComponent.parentToChildRotationOffset [child.gameObject] = child.transform.localRotation; child.transform.rotation = voxComponent.gameObject.transform.rotation * child.transform.localRotation; } else { voxComponent.parentToChildRotationOffset[child.gameObject] = child.transform.localRotation; child.targetRotation = child.transform.rotation.eulerAngles; } child.transform.localPosition = Helper.RotatePointAroundPivot( voxComponent.parentToChildPositionOffset[child.gameObject], Vector3.zero, voxComponent.gameObject.transform.eulerAngles); //child.transform.localPosition = Helper.RotatePointAroundPivot (child.transform.localEulerAngles, // Vector3.zero, voxComponent.gameObject.transform.eulerAngles); child.transform.position = voxComponent.gameObject.transform.position + child.transform.localPosition; child.targetPosition = child.transform.position; } } } } } }
public static void ResolvePhysicsPositionDiscrepancies(GameObject obj, bool macroEventSatisfied) { Voxeme voxComponent = obj.GetComponent <Voxeme>(); //Debug.Break (); // find the displacement between the main body and this rigidbody float displacement = float.MaxValue; Rigidbody[] rigidbodies = obj.GetComponentsInChildren <Rigidbody>(); //Debug.Log (obj.name); foreach (Rigidbody rigidbody in rigidbodies) { if (voxComponent.displacement.ContainsKey(rigidbody.gameObject)) { // if (rigidbody.transform.localPosition.magnitude > voxComponent.displacement [rigidbody.gameObject].magnitude+Constants.EPSILON) { if (rigidbody.transform.localPosition.magnitude - voxComponent.displacement[rigidbody.gameObject].magnitude < displacement) { // Debug.Log (rigidbody.name); // Debug.Log (Helper.VectorToParsable (obj.transform.position)); // Debug.Log (Helper.VectorToParsable (rigidbody.transform.position)); displacement = rigidbody.transform.localPosition.magnitude - voxComponent.displacement[rigidbody.gameObject].magnitude; } // } } } if (displacement == float.MaxValue) { displacement = 0.0f; } if (displacement > Constants.EPSILON) { // Debug.Log (obj.name); // Debug.Log (displacement); if (voxComponent != null) { if (rigidbodies.Length > 0) { // Debug.Log (rigidbodies [0].name); // Debug.Log (rigidbodies [0].transform.position); // Debug.Log (Helper.VectorToParsable(voxComponent.displacement [rigidbodies[0].gameObject])); obj.transform.position = rigidbodies[0].transform.position - (obj.transform.rotation * voxComponent.displacement[rigidbodies[0].gameObject]); //Debug.Log (obj.name); //Debug.Log (obj.transform.position); //obj.transform.position = rigidbodies [0].transform.localPosition - voxComponent.displacement [rigidbodies[0].gameObject] + // obj.transform.position; voxComponent.targetPosition = obj.transform.position; // Debug.Log (Helper.VectorToParsable (rigidbodies [0].transform.position)); // Debug.Log (Helper.VectorToParsable (rigidbodies [0].transform.localPosition)); // Debug.Log (Helper.VectorToParsable (obj.transform.position)); //Debug.Log (Helper.VectorToParsable (rigidbodies [0].transform.position)); //Debug.Log (Helper.VectorToParsable (voxComponent.displacement [rigidbodies[0].name])); foreach (Rigidbody rigidbody in rigidbodies) { if (voxComponent.displacement.ContainsKey(rigidbody.gameObject)) { // Debug.Log (rigidbody.name); rigidbody.transform.localPosition = voxComponent.displacement[rigidbody.gameObject]; } } } } } // TODO: Abstract away if (voxComponent != null) { if (voxComponent.children != null) { foreach (Voxeme child in voxComponent.children) { if (child.isActiveAndEnabled) { if (child.gameObject != voxComponent.gameObject) { // ResolvePhysicsPositionDiscepancies (child.gameObject); // ResolvePhysicsRotationDiscepancies (child.gameObject); //Debug.Log ("Moving child: " + gameObject.name); child.transform.localPosition = voxComponent.parentToChildPositionOffset[child.gameObject]; child.targetPosition = child.transform.position; } } } } } }
void SaveMarkup(GameObject obj) { Voxeme voxml = new Voxeme (); // assign VoxML values // PRED voxml.Lex.Pred = mlPred; voxml.Lex.Type = System.String.Join("*",mlTypes.ToArray()); // TYPE voxml.Type.Head = mlHead; for (int i = 0; i < mlComponentCount; i++) { voxml.Type.Components.Add (new Component()); voxml.Type.Components[i].Value = mlComponents[i]; } voxml.Type.Concavity = mlConcavity; List<string> rotatSyms = new List<string> (); if (mlRotatSymX) { rotatSyms.Add ("X"); } if (mlRotatSymY) { rotatSyms.Add ("Y"); } if (mlRotatSymZ) { rotatSyms.Add ("Z"); } voxml.Type.RotatSym = System.String.Join(",", rotatSyms.ToArray()); List<string> reflSyms = new List<string> (); if (mlReflSymXY) { reflSyms.Add ("XY"); } if (mlReflSymXZ) { reflSyms.Add ("XZ"); } if (mlReflSymYZ) { reflSyms.Add ("YZ"); } voxml.Type.ReflSym = System.String.Join(",", reflSyms.ToArray()); // HABITAT for (int i = 0; i < mlIntrHabitatCount; i++) { voxml.Habitat.Intrinsic.Add (new Intr()); voxml.Habitat.Intrinsic[i].Name = mlIntrHabitats[i].Split(new char[]{'='})[0]; voxml.Habitat.Intrinsic[i].Value = mlIntrHabitats[i].Split(new char[]{'='})[1]; } for (int i = 0; i < mlExtrHabitatCount; i++) { voxml.Habitat.Extrinsic.Add (new Extr()); voxml.Habitat.Extrinsic[i].Name = mlExtrHabitats[i].Split(new char[]{'='})[0]; voxml.Habitat.Extrinsic[i].Value = mlExtrHabitats[i].Split(new char[]{'='})[1]; } // AFFORD_STR for (int i = 0; i < mlAffordanceCount; i++) { voxml.Afford_Str.Affordances.Add (new Affordance()); voxml.Afford_Str.Affordances[i].Formula = mlAffordances[i]; } // EMBODIMENT voxml.Embodiment.Scale = mlScale; voxml.Embodiment.Movable = mlMovable; voxml.Save (obj.name+".xml"); // voxml.SaveToServer (obj.name + ".xml"); }
// Update is called once per frame void Update() { if (sandboxSurface != Helper.GetMostImmediateParentVoxeme(sandboxSurface)) { sandboxSurface = Helper.GetMostImmediateParentVoxeme(sandboxSurface); } if (placementState == PlacementState.Delete) { if (Input.GetMouseButtonDown(0)) { if (Helper.PointOutsideMaskedAreas( new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y), new Rect[] { new Rect(Screen.width - (15 + (int)(110 * fontSizeModifier / 3)) + 38 * fontSizeModifier - 60, Screen.height - (35 + (int)(20 * fontSizeModifier)), 60, 20 * fontSizeModifier) })) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // Casts the ray and get the first game object hit Physics.Raycast(ray, out selectRayhit); if (selectRayhit.collider != null) { if (selectRayhit.collider.gameObject.transform.root.gameObject == selectedObject) { DeleteVoxeme(selectedObject); actionButtonText = "Add Object"; placementState = PlacementState.Add; selected = -1; cameraControl.allowRotation = true; } } } } } else if (placementState == PlacementState.Place) { if (Input.GetMouseButton(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // Casts the ray and get the first game object hit Physics.Raycast(ray, out selectRayhit); if (selectRayhit.collider != null) { if (selectRayhit.collider.gameObject.transform.root.gameObject == sandboxSurface) { Debug.Log(selectRayhit.point.y); if (Mathf.Abs(selectRayhit.point.y - preds.ON(new object[] { sandboxSurface }).y) <= Constants.EPSILON) { if ((Mathf.Abs(selectRayhit.point.x - Helper.GetObjectWorldSize(sandboxSurface).min.x) >= Helper.GetObjectWorldSize(selectedObject).extents.x) && (Mathf.Abs(selectRayhit.point.x - Helper.GetObjectWorldSize(sandboxSurface).max.x) >= Helper.GetObjectWorldSize(selectedObject).extents.x) && (Mathf.Abs(selectRayhit.point.z - Helper.GetObjectWorldSize(sandboxSurface).min.z) >= Helper.GetObjectWorldSize(selectedObject).extents.z) && (Mathf.Abs(selectRayhit.point.z - Helper.GetObjectWorldSize(sandboxSurface).max.z) >= Helper.GetObjectWorldSize(selectedObject).extents.z)) { selectedObject.transform.position = new Vector3(selectRayhit.point.x, preds.ON(new object[] { sandboxSurface }).y + surfacePlacementOffset, selectRayhit.point.z); Voxeme voxComponent = selectedObject.GetComponent <Voxeme>(); voxComponent.targetPosition = selectedObject.transform.position; foreach (Voxeme child in voxComponent.children) { if (child.isActiveAndEnabled) { if (child.gameObject != voxComponent.gameObject) { child.transform.localPosition = voxComponent.parentToChildPositionOffset[child.gameObject]; child.targetPosition = child.transform.position; } } } } } } } } if (Input.GetKeyDown(KeyCode.Return)) { actionButtonText = "Add Object"; placementState = PlacementState.Add; selected = -1; cameraControl.allowRotation = true; selectedObject.GetComponent <Rigging>().ActivatePhysics(true); SetShader(selectedObject, ShaderType.Default); } } else if (placementState == PlacementState.Add) { if (Input.GetMouseButton(0)) { if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // Casts the ray and get the first game object hit Physics.Raycast(ray, out selectRayhit); if (selectRayhit.collider != null) { if (Helper.IsSupportedBy(selectRayhit.collider.gameObject.transform.root.gameObject, sandboxSurface)) { if (selectRayhit.collider.gameObject.transform.root.gameObject.GetComponent <Voxeme>() != null) { selectedObject = selectRayhit.collider.gameObject.transform.root.gameObject; surfacePlacementOffset = (Helper.GetObjectWorldSize(selectedObject.gameObject).center.y - Helper.GetObjectWorldSize(selectedObject.gameObject).min.y) + (selectedObject.gameObject.transform.position.y - Helper.GetObjectWorldSize(selectedObject.gameObject).center.y); SetShader(selectedObject, ShaderType.Highlight); actionButtonText = "Place"; placementState = PlacementState.Place; cameraControl.allowRotation = false; if (selectedObject != null) { selectedObject.GetComponent <Rigging>().ActivatePhysics(false); } } } } } } } }
// Update is called once per frame. FixedUpdate is 50 times a second regardless of framerate // If anything seems slow, it's probably because of dead weight somewhere in here :) void FixedUpdate() { Vector3 Point; float zDistance; List <Phrase> to_destroy = new List <Phrase>(); // To avoid errors deleting in the for loop // Tell each of the objects to look at the camera foreach (Phrase child in precious_children.Values) { if (child.obj.name.EndsWith("*")) { //child.obj.transform.parent.SetParent(transform); child.asterisk = child.obj; child.obj = child.obj.transform.parent.gameObject; // point exclusively to the top-level. } if (child.asterisk == null) { // Set that yo child.asterisk = child.obj.transform.Find(child.term + "*").gameObject; } if (child.obj.transform.parent != transform) { // Someone has stolen my child :o // Quick check if its parent is in our list of highlight spots if (child.obj.transform.parent != null && highlight_points.Contains(child.obj.transform.parent.gameObject)) { child.is_highlighted = true; Debug.LogWarning("Got " + child.term + " highlighted."); } child.obj.transform.SetParent(transform); } Voxeme vx = child.obj.transform.GetComponent <Voxeme>(); // Kinda awkward to do this here. //vx.is_phrase = true; //Every frame, like taking a sledghammer to a banana vx.moveSpeed = 0.5f; // // Look at the camera Quaternion toRotation1; toRotation1 = Quaternion.LookRotation(child.asterisk.transform.position - camera1.position); float speed = 0.7f; if (Quaternion.Angle(toRotation1, child.asterisk.transform.rotation) > 5) { child.asterisk.transform.rotation = Quaternion.Lerp(child.asterisk.transform.rotation, toRotation1, speed * Time.deltaTime); } if ((child.asterisk.transform.localScale - child.size).magnitude > 0.001) { child.asterisk.transform.localScale = Vector3.Lerp(child.asterisk.transform.localScale, child.size, speed * Time.deltaTime); } // If you're not where you're supposed to be, let the voxphrase physics know that. // Make it so it does not override movement. if (!child.is_happy && vx.targetPosition != child.ideal_position) { // Increment to new location. Only do if position is not set manually by user. vx.targetPosition = child.ideal_position; child.is_happy = true; // Kinda papering over the problem right now. Should probably specify when things should override preexisting locations. } if (child.asterisk.transform.localScale.magnitude < 0.005) // Explode the heckin tiny ones that shrunk the heck away { to_destroy.Add(child); } } ObjectSelector objSelector = GameObject.Find("VoxWorld").GetComponent <ObjectSelector>(); foreach (Phrase child in to_destroy) { // DELETE DELETE DELETE // Add steps to this until no errors remain precious_children.Remove(child.term); // A list of 'all voxemes' needs to know if one goes bye bye I guess objSelector.allVoxemes.Remove(child.obj.transform.GetComponent <Voxeme>()); DestroyImmediate(transform.Find(child.term).gameObject); } }
void ReferenceObject(object sender, EventArgs e) { Debug.Log(string.Format("Referring to {0}", focusObj.name)); //List<string> descriptors = new List<string>(); descriptorString = string.Empty; if (world.interactionPrefs.gesturalReference) { distanceDistinction = false; GameObject hand = InteractionHelper.GetCloserHand(agent, focusObj); world.PointAt(focusObj.transform.position, hand); if (world.interactionPrefs.linguisticReference) { // G + L // variables: bool proximal/distal distinction (this/that) // int 0-3 relational descriptors distanceDistinction = Convert.ToBoolean( RandomHelper.RandomInt(0, 1, (int)(RandomHelper.RangeFlags.MinInclusive) | (int)(RandomHelper.RangeFlags.MaxInclusive))); relativeDistance = Convert.ToBoolean( RandomHelper.RandomInt(0, 1, (int)(RandomHelper.RangeFlags.MinInclusive) | (int)(RandomHelper.RangeFlags.MaxInclusive))); int relationalDescriptors = RandomHelper.RandomInt(0, 4); Debug.Log(string.Format( "Use distance distinction: {0}, relative distance: {1}, {2} relational descriptors", distanceDistinction, relativeDistance, relationalDescriptors)); Voxeme objVox = focusObj.GetComponent <Voxeme>(); string demonstrative = "That"; if (distanceDistinction) { if (relativeDistance) { // !relative distance -> absolute distance (near region = this, far region = that) // is focusObj closer to the agent than the other block of the same color? string color = string.Empty; color = objVox.voxml.Attributes.Attrs[0].Value; // just grab the first one for now List <GameObject> otherObjs = world.availableObjs.Where(b => b.GetComponent <Voxeme>().voxml.Attributes.Attrs[0].Value == color && b != focusObj).ToList(); if (otherObjs.Count > 0) { if (Vector3.Distance(agent.transform.position, focusObj.transform.position) < Vector3.Distance(agent.transform.position, otherObjs[0].transform.position)) { demonstrative = "This"; } } else { // default to absolute distance if (world.frontRegion.Contains(new Vector3( focusObj.transform.position.x, world.frontRegion.center.y, focusObj.transform.position.z))) { demonstrative = "This"; } } } else { if (world.frontRegion.Contains(new Vector3( focusObj.transform.position.x, world.frontRegion.center.y, focusObj.transform.position.z))) { demonstrative = "This"; } } } descriptorString = FindFocusObjRelations(relationalDescriptors); if (objVox != null) { string color = string.Empty; color = objVox.voxml.Attributes.Attrs[0].Value; // just grab the first one for now fullDesc = string.Format("{0} {1} {2}{3}.", demonstrative, color, objVox.opVox.Lex.Pred, descriptorString); world.RespondAndUpdate(fullDesc); } } } else if (world.interactionPrefs.linguisticReference) { // variables: int 1-3 relational descriptors distanceDistinction = false; int relationalDescriptors = RandomHelper.RandomInt(1, 4); descriptorString = FindFocusObjRelations(relationalDescriptors); Voxeme objVox = focusObj.GetComponent <Voxeme>(); if (objVox != null) { string color = string.Empty; color = objVox.voxml.Attributes.Attrs[0].Value; // just grab the first one for now fullDesc = string.Format("The {0} {1}{2}.", color, objVox.opVox.Lex.Pred, descriptorString); world.RespondAndUpdate(fullDesc); } } }
// constraints should be the target object! // Plan path uses a heuristic function h(n) of manhattan distance // Just change to the Euclidian distance for better performance public void PlanPath(Vector3 startPos, Vector3 goalPos, out List <Vector3> path, GameObject obj, params object[] constraints) { Debug.Log("====== startPos ===== " + startPos); Debug.Log("====== goalPos ===== " + goalPos); // clear nodes nodes.Clear(); // init empty path List <PathNode> plannedPath = new List <PathNode>(); //List<PathNode> openSet = new List<PathNode> (); MinHeap <PathNode> openSet = new MinHeap <PathNode>(new BetterHeuristicOld()); List <PathNode> closedSet = new List <PathNode>(); PathNode endNode = null; path = new List <Vector3>(); Vector3 size = Helper.GetObjectWorldSize(obj).size; //increment = size.magnitude/2 > defaultIncrement.magnitude ? new Vector3(size.x/2, size.y/2, size.z/2) : defaultIncrement; increment = size.magnitude > defaultIncrement.magnitude ? size : defaultIncrement; var watch = Stopwatch.StartNew(); PathNode startNode = new PathNode(startPos); startNode.scoreFromStart = 0; // Manhattan distance startNode.heuristicScore = Mathf.Abs(goalPos.x - startNode.position.x) + Mathf.Abs(goalPos.y - startNode.position.y) + Mathf.Abs(goalPos.z - startNode.position.z); // Euclidan distance // startNode.heuristicScore = new Vector3 (goalPos.x - startNode.position.x, goalPos.y - startNode.position.y, goalPos.z - startNode.position.z).magnitude; nodes.Add(startNode); openSet.Add(startNode); QuantizeSpace(obj, embeddingSpaceBounds, increment, constraints); // set increment to moving object size, clean up after each run watch.Stop(); Debug.Log("========= Time to quantize space " + watch.ElapsedMilliseconds); // find closest node to goal // TODO: if goal is inside concave object (concave voxeme provided as constraint) // find closest node to goal such that arc from testNode to goal // does not intersect non-concave component of object // if constraints contain a voxeme Voxeme testTarget = constraints.OfType <Voxeme>().FirstOrDefault(); if (testTarget != null) { // if that object is concave (e.g. cup) // if goalPos is within the bounds of target (e.g. in cup) if (testTarget.voxml.Type.Concavity.Contains("Concave") && Helper.GetObjectWorldSize(testTarget.gameObject).Contains(goalPos)) { endNode = new PathNode(new Vector3(goalPos.x, Helper.GetObjectWorldSize(testTarget.gameObject).max.y + size.y, goalPos.z)); nodes.Add(endNode); //Debug.Break(); } else { float dist = Mathf.Infinity; foreach (PathNode node in nodes) { if ((node.position - goalPos).magnitude < dist) { // if dist from this node to goal < dstance from previous node in list to goal dist = (node.position - goalPos).magnitude; endNode = node; } } } } else { float dist = Mathf.Infinity; foreach (PathNode node in nodes) { if ((node.position - goalPos).magnitude < dist) { // if dist from this node to goal < dstance from previous node in list to goal dist = (node.position - goalPos).magnitude; endNode = node; } } } Debug.Log("========= endNode ========== " + endNode); //PathNode endNode = new PathNode(goalPos); //nodes.Add (endNode); watch = Stopwatch.StartNew(); PlotArcs(Helper.GetObjectWorldSize(obj)); watch.Stop(); Debug.Log("========= Time to plot arcs " + watch.ElapsedMilliseconds); //return; //path.Add(startPos); PathNode nextNode = new PathNode(embeddingSpaceBounds.max + Vector3.one); plannedPath.Add(new PathNode(startPos)); // starting with startNode, for each neighborhood node of last node, assess A* heuristic // using best node found until endNode reached while (openSet.Count > 0) { Debug.Log(" ======== openSet.Count ====== " + openSet.Count); // O(1) PathNode curNode = openSet.TakeMin(); // O(n) // PathNode curNode = null; // // float testHeuristicScore = Mathf.Infinity; // foreach (PathNode node in openSet) { // if (node.heuristicScore < testHeuristicScore) { // testHeuristicScore = node.heuristicScore; // curNode = node; // } // } //nextNode = embeddingSpaceBounds.max + Vector3.one; //dist = (nextNode - endNode).magnitude; //float dist = ((embeddingSpaceBounds.max + Vector3.one)-endNode.position).magnitude; // if reached end node if ((curNode.position - endNode.position).magnitude < Constants.EPSILON) { // extend path to goal node (goal position) PathNode goalNode = new PathNode(goalPos); goalNode.cameFrom = curNode; path = ReconstructPath(startNode, goalNode); Debug.Log("====== path ===== "); foreach (var point in path) { Debug.Log(point); } break; } closedSet.Add(curNode); var arcList = arcs.Where(n => ((n.Item1.position - curNode.position).magnitude < Constants.EPSILON) || (n.Item2.position - curNode.position).magnitude < Constants.EPSILON).ToList(); foreach (var arc in arcList) { float testScore; if ((arc.Item1.position - curNode.position).magnitude < Constants.EPSILON) { if (!closedSet.Contains(arc.Item2)) { testScore = curNode.scoreFromStart + (arc.Item2.position - curNode.position).magnitude; if (testScore < arc.Item2.scoreFromStart) { nextNode = arc.Item2; arc.Item2.cameFrom = curNode; arc.Item2.scoreFromStart = testScore; // Manhattan distance // arc.Item2.heuristicScore = arc.Item2.scoreFromStart + // (Mathf.Abs(goalPos.x - arc.Item2.position.x) + Mathf.Abs(goalPos.y - arc.Item2.position.y) + // Mathf.Abs(goalPos.z - arc.Item2.position.z)); // Euclidian distance arc.Item2.heuristicScore = arc.Item2.scoreFromStart + new Vector3(goalPos.x - arc.Item2.position.x, goalPos.y - arc.Item2.position.y, goalPos.z - arc.Item2.position.z).magnitude; if (!openSet.Contains(arc.Item2)) { openSet.Add(arc.Item2); } } } } else if ((arc.Item2.position - curNode.position).magnitude < Constants.EPSILON) { if (!closedSet.Contains(arc.Item1)) { testScore = curNode.scoreFromStart + (arc.Item1.position - curNode.position).magnitude; if (testScore < arc.Item1.scoreFromStart) { nextNode = arc.Item1; arc.Item1.cameFrom = curNode; arc.Item1.scoreFromStart = testScore; // Manhattan distance // arc.Item1.heuristicScore = arc.Item1.scoreFromStart + // (Mathf.Abs(goalPos.x - arc.Item1.position.x) + Mathf.Abs(goalPos.y - arc.Item1.position.y) + // Mathf.Abs(goalPos.z - arc.Item1.position.z)); // Euclidian distance arc.Item1.heuristicScore = arc.Item1.scoreFromStart + new Vector3(goalPos.x - arc.Item1.position.x, goalPos.y - arc.Item1.position.y, goalPos.z - arc.Item1.position.z).magnitude; if (!openSet.Contains(arc.Item1)) { openSet.Add(arc.Item1); } } } } } } }
string FindFocusObjRelations(int relationalDescriptors) { descriptors = new List <string>(); descriptorString = string.Empty; // find relations involving focusObj List <Pair <GameObject, string> > focusObjRelations = new List <Pair <GameObject, string> >(); foreach (DictionaryEntry dictEntry in relationTracker.relations) { if (((dictEntry.Key as List <GameObject>)[0] == focusObj) && (landmarks.Contains((dictEntry.Key as List <GameObject>)[1]))) { focusObjRelations.Add(new Pair <GameObject, string>( (dictEntry.Key as List <GameObject>).Where(o => o != focusObj).ToList()[0], dictEntry.Value as string)); } } foreach (DictionaryEntry dictEntry in relationTracker.relations) { if (((dictEntry.Key as List <GameObject>)[0] == focusObj) && (!landmarks.Contains((dictEntry.Key as List <GameObject>)[1])) && ((dictEntry.Key as List <GameObject>)[1] != Helper.GetMostImmediateParentVoxeme(world.demoSurface))) { focusObjRelations.Add(new Pair <GameObject, string>( (dictEntry.Key as List <GameObject>).Where(o => o != focusObj).ToList()[0], dictEntry.Value as string)); } } // shuffle relation list int count = focusObjRelations.Count; int last = count - 1; for (int i = 0; i < last; ++i) { int r = RandomHelper.RandomInt(i, count); var tmp = focusObjRelations[i]; focusObjRelations[i] = focusObjRelations[r]; focusObjRelations[r] = tmp; } foreach (Pair <GameObject, string> relation in focusObjRelations) { Debug.Log(string.Format("{0} {1} {2}", focusObj.name, relation.Item2, relation.Item1.name)); } for (int i = 0; i < Math.Min(relationalDescriptors, focusObjRelations.Count); i++) { string color = string.Empty; Voxeme descriptorObjVox = (focusObjRelations[i].Item1 as GameObject).GetComponent <Voxeme>(); color = (descriptorObjVox.voxml.Attributes.Attrs.Count > 0) ? descriptorObjVox.voxml.Attributes.Attrs[0].Value : string.Empty; // just grab the first one for now color = (color == focusObj.GetComponent <Voxeme>().voxml.Attributes.Attrs[0].Value) ? "other " + color : color; string descriptorObj = string.Format("{0}{1} {2}", "the", (color == string.Empty) ? string.Empty : " " + color, descriptorObjVox.opVox.Lex.Pred); descriptors.Add(string.Format("{0} {1}", predToString[focusObjRelations[i].Item2], descriptorObj)); if (descriptors.Count > 1) { if (descriptors.Count > 2) { descriptorString = string.Format("{0} and {1}", string.Join(", ", descriptors.GetRange(0, descriptors.Count - 1).ToArray()), descriptors[descriptors.Count - 1]); } else { descriptorString = string.Join(" and ", descriptors.ToArray()); } } else { descriptorString = descriptors[0]; } } return(((descriptors.Count > 0) ? " " : "") + descriptorString); }
public bool IsKnown(Voxeme v) { return(_memorized.ContainsKey(v)); }
Voxeme LoadMarkup(GameObject obj) { Voxeme voxml = new Voxeme(); string text = ""; try { /*using(WWW www = WWW("http://www.voxicon.net/cwc/voxml/" + obj.name + ".xml")){ yield return www; if (www.error != null) throw new Exception("WWW download had an error:" + www.error); text = www.text; }*/ if (text.Length == 0) { voxml = Voxeme.Load (obj.name + ".xml"); } // assign VoxML values // PRED mlPred = voxml.Lex.Pred; mlTypes = new List<string>(voxml.Lex.Type.Split (new char[]{'*'})); mlTypeCount = mlTypes.Count; mlTypeSelectVisible = new List<int>(new int[]{-1}); mlTypeSelected = new List<int>(new int[]{-1}); mlRemoveType = new List<int>(new int[]{-1}); for (int i = 0; i < mlTypeCount; i++) { mlTypeSelectVisible.Add (-1); mlTypeSelected.Add (-1); mlRemoveType.Add (-1); } // TYPE mlHead = voxml.Type.Head; mlComponents = new List<string>(); foreach (Component c in voxml.Type.Components) { mlComponents.Add (c.Value); } mlComponentCount = mlComponents.Count; mlConcavity = voxml.Type.Concavity; List <string> rotatSyms = new List<string>(voxml.Type.RotatSym.Split (new char[]{','})); mlRotatSymX = (rotatSyms.Contains("X")); mlRotatSymY = (rotatSyms.Contains("Y")); mlRotatSymZ = (rotatSyms.Contains("Z")); List<string> reflSyms = new List<string>(voxml.Type.ReflSym.Split (new char[]{','})); mlReflSymXY = (reflSyms.Contains ("XY")); mlReflSymXZ = (reflSyms.Contains ("XZ")); mlReflSymYZ = (reflSyms.Contains ("YZ")); // HABITAT mlIntrHabitats = new List<string>(); foreach (Intr i in voxml.Habitat.Intrinsic) { mlIntrHabitats.Add (i.Name + "=" + i.Value); } mlIntrHabitatCount = mlIntrHabitats.Count; mlExtrHabitats = new List<string>(); foreach (Extr e in voxml.Habitat.Extrinsic) { mlExtrHabitats.Add (e.Name + "=" + e.Value); } mlExtrHabitatCount = mlExtrHabitats.Count; // AFFORD_STR mlAffordances = new List<string>(); foreach (Affordance a in voxml.Afford_Str.Affordances) { mlAffordances.Add (a.Formula); } mlAffordanceCount = mlAffordances.Count; // EMBODIMENT mlScale = voxml.Embodiment.Scale; mlMovable = voxml.Embodiment.Movable; } catch (FileNotFoundException ex) { } return voxml; }