Skip to content
Snippets Groups Projects
Fact.cs 82.3 KiB
Newer Older
  • Learn to ignore specific revisions
  • using System;
    using System.Collections.Generic;
    
    using UnityEngine;
    
    using UnityEngine.Networking;
    
    using Newtonsoft.Json;
    
    MaZiFAU's avatar
    MaZiFAU committed
    using System.Linq;
    
    using REST_JSON_API;
    
    public static class ParsingDictionary
    
        //TODO? get rid of this, use reflection? instead, if possible
        //TODO: docu
    
    ki7077's avatar
    ki7077 committed
    
    
        public static Dictionary<string, Func<MMTFact, Fact>> parseFactDictionary = new() {
            { MMTConstants.Point,
    
            { MMTConstants.Metric,
    
            { MMTConstants.Angle,
    
            { MMTConstants.Eq,
    
            { MMTConstants.RightAngle,
    
            { MMTConstants.LineType,
    
            { MMTConstants.LineOf,
    
            { MMTConstants.OnLine,
    
            { MMTConstants.ParallelLine,
    
                ParallelLineFact.parseFact },
    
            { MMTConstants.CircleType3d,
    
            { MMTConstants.OnCircle,
    
            { MMTConstants.AnglePlaneLine,
    
                AngleCircleLineFact.parseFact },
    
            { MMTConstants.RadiusCircleMetric,
    
            { MMTConstants.AreaCircle,
    
            { MMTConstants.OrthoCircleLine,
    
                OrthogonalCircleLineFact.parseFact },
    
            { MMTConstants.VolumeCone,
    
            { MMTConstants.TruncatedVolumeCone,
    
                TruncatedConeVolumeFact.parseFact },
    
            { MMTConstants.CylinderVolume,
    
                CylinderVolumeFact.parseFact },
    
            { MMTConstants.TestType,
    
            { MMTConstants.EqualityCircles,
    
                EqualCirclesFact.parseFact },
    
            { MMTConstants.UnEqualityCircles,
    
    MaZiFAU's avatar
    MaZiFAU committed
                UnEqualCirclesFact.parseFact },
    
            { MMTConstants.ListLiteral,
    
    MaZiFAU's avatar
    MaZiFAU committed
                ListFact.parseFact },
    
        // TODO: get rid of this
        public static Dictionary<string, string> parseTermsToId = new();
    
    /// <summary>
    /// %Fact representation of Unity; mostly mirrors Facts of MMT.
    /// </summary>
    
    [JsonConverter(typeof(JsonSubtypes), "s_type")]
    
    [JsonSubtypes.KnownSubType(typeof(PointFact), nameof(PointFact))]
    [JsonSubtypes.KnownSubType(typeof(LineFact), nameof(LineFact))]
    [JsonSubtypes.KnownSubType(typeof(RayFact), nameof(RayFact))]
    [JsonSubtypes.KnownSubType(typeof(OnLineFact), nameof(OnLineFact))]
    [JsonSubtypes.KnownSubType(typeof(AngleFact), nameof(AngleFact))]
    [JsonSubtypes.KnownSubType(typeof(CircleFact), nameof(CircleFact))]
    [JsonSubtypes.KnownSubType(typeof(ParallelLineFact), nameof(ParallelLineFact))]
    [JsonSubtypes.KnownSubType(typeof(OnCircleFact), nameof(OnCircleFact))]
    [JsonSubtypes.KnownSubType(typeof(AngleCircleLineFact), nameof(AngleCircleLineFact))]
    
    MaZiFAU's avatar
    MaZiFAU committed
    [JsonSubtypes.KnownSubType(typeof(OrthogonalCircleLineFact), nameof(OrthogonalCircleLineFact))]
    
    [JsonSubtypes.KnownSubType(typeof(AreaCircleFact), nameof(AreaCircleFact))]
    [JsonSubtypes.KnownSubType(typeof(RadiusFact), nameof(RadiusFact))]
    [JsonSubtypes.KnownSubType(typeof(ConeVolumeFact), nameof(ConeVolumeFact))]
    [JsonSubtypes.KnownSubType(typeof(TruncatedConeVolumeFact), nameof(TruncatedConeVolumeFact))]
    [JsonSubtypes.KnownSubType(typeof(RightAngleFact), nameof(RightAngleFact))]
    [JsonSubtypes.KnownSubType(typeof(CylinderVolumeFact), nameof(CylinderVolumeFact))]
    [JsonSubtypes.KnownSubType(typeof(TestFact), nameof(TestFact))]
    [JsonSubtypes.KnownSubType(typeof(EqualCirclesFact), nameof(EqualCirclesFact))]
    [JsonSubtypes.KnownSubType(typeof(UnEqualCirclesFact), nameof(UnEqualCirclesFact))]
    [JsonSubtypes.KnownSubType(typeof(AttachedPositionFunction), nameof(AttachedPositionFunction))]
    
    MaZiFAU's avatar
    MaZiFAU committed
    [JsonSubtypes.KnownSubType(typeof(FunctionFact), nameof(FunctionFact))]
    [JsonSubtypes.KnownSubType(typeof(FunctionCallFact), nameof(FunctionCallFact))]
    
    MaZiFAU's avatar
    MaZiFAU committed
    [JsonSubtypes.KnownSubType(typeof(ListFact), nameof(ListFact))]
    
    MaZiFAU's avatar
    MaZiFAU committed
    [JsonSubtypes.KnownSubType(typeof(TupelFact), nameof(TupelFact))]
    
    //[JsonSubtypes.KnownSubType(typeof(FunctionFact<T0, TResult>), "FunctionFact<T0, TResult>")] //TODO: generics? => nameof does not work (generic agnostic)
    
    MaZiFAU's avatar
    MaZiFAU committed
    //[JsonSubtypes.KnownSubType(typeof(FunctionFactFloat<Vector3>), "FunctionFact<System.Single, UnityEngine.Vector3>")]
    
    public abstract class Fact
    
        /// <summary>
        /// Reference to <c>GameObject</c> that represents this Fact in the GameWorld.
        /// </summary>
    
    MaZiFAU's avatar
    MaZiFAU committed
        /// <seealso cref="FactObject3D"/>
    
        public FactWrapper WorldRepresentation;
    
        /// <summary>
        /// Collection of <c>Type</c>s of *all* available <see cref="Fact"/>s to choose from.
        /// </summary>
        [JsonIgnore]
    
    MaZiFAU's avatar
    MaZiFAU committed
        public static readonly Type[] Types = TypeExtensions<Fact>.UAssemblyInheritenceTypes;
    
        /// [ClassName] for JSON de-/serialization.
    
        /// Automatically set in <see cref="Fact()"/> for <b>NON-Generiy-Types</b>!
    
        /// Also add JsonSubtypes.KnownSubType decorator for deserialization to Fact!
    
        [JsonProperty]
    
        /// <returns><see langword="true"/> if Fact depends on other \ref Fact "Facts"; equivalent to <see cref="getDependentFactIds"/> returns non empty array</returns>
        [JsonIgnore]
    
    MaZiFAU's avatar
    MaZiFAU committed
        public virtual bool HasDependentFacts => DependentFactIds.Length > 0;
    
    
        /// <returns> array of Fact <see cref="Id"> Ids </see> on which this Fact depends.</returns>
        /// <example><see cref="AngleFact"/> needs 3 <see cref="PointFact"/>s to be defined.</example>
    
        public string[] DependentFactIds => _DependentFactIds ??= GetGetDependentFactIds();
        private string[] _DependentFactIds;
    
        /// <returns> array of Fact <see cref="Id"> Ids </see> on which this Fact depends.</returns>
        /// <example><see cref="AngleFact"/> needs 3 <see cref="PointFact"/>s to be defined.</example>
        protected abstract string[] GetGetDependentFactIds();
    
    
        /// <value>
        /// Unique Id. e.g.: MMT URI
        /// </value>
    
    MaZiFAU's avatar
    MaZiFAU committed
        [JsonIgnore]
    
        public string Id
        {
    
    MaZiFAU's avatar
    MaZiFAU committed
            get
            {
    
                //while (FetchURICoroutine.MoveNext()) ; //active wait for server
    
    MaZiFAU's avatar
    MaZiFAU committed
                return _URI;
            }
    
        //private IEnumerator FetchURICoroutine = IEnumeratorExtensions.yield_break;
    
    MaZiFAU's avatar
    MaZiFAU committed
        [JsonProperty]
    
        protected string _URI;
    
        /// <value>
        /// <c>get</c> initiates and subsequently updates a human readable name. <remarks>Should be called once a constructor call to be initiated.</remarks>
        /// <c>set</c> calls <see cref="rename(string)"/>
        /// </value>
    
        public string Label
        {
            get
            { // in case of renamed dependables
    
    MaZiFAU's avatar
    MaZiFAU committed
                return _Facts == null // JsonSerialization toggle (_Facts.GetNumberOfFacts() == 0 && this is not PointFact) // JsonSerialization toggle && allow first (Point)Fact to be created
    
                    || (hasCustomLabel && _CustomLabel != null)
    
            set
            {
                if (_Facts == null) // JsonSerialization toggle)
    
    MaZiFAU's avatar
    MaZiFAU committed
                {
                    _CustomLabel = value;
                    LabelId = -LabelId;
                    return;
                }
    
                rename(value);
    
    
        /// <value>
        /// Is true if Fact has a custom <see cref="Label"/> which is not <c>null</c> or <c>""</c>.
        /// </value>
    
        public bool hasCustomLabel => LabelId < 0;
    
    
        /// <summary>
        /// Stores custom <see cref="Label"/> if set.
        /// </summary>
    
        /// <summary>
        /// Counter to organize auto generated <see cref="Label"/>.
        /// Set to negative, if custom \ref Label is assigned.
        /// </summary>
        // property for JSON to set AFTER Label => declare AFTER Label
    
        public int LabelId { get; set; }
    
        /// <summary>
        /// Reference to <see cref="FactOrganizer"/> in which this Fact and all its <see cref="getDependentFactIds">depending Facts</see> are beeing organized.
        /// </summary>
    
    BenniHome's avatar
    BenniHome committed
    
    
    MaZiFAU's avatar
    MaZiFAU committed
        [JsonIgnore]
    
    MaZiFAU's avatar
    MaZiFAU committed
        bool ForceRecalculateTransform = true;
    
    
    MaZiFAU's avatar
    MaZiFAU committed
        [JsonIgnore]
    
    MaZiFAU's avatar
    MaZiFAU committed
        public Vector3 Position
        {
            get
            {
                if (ForceRecalculateTransform)
                    RecalculateTransform();
                return _Position;
            }
            protected set
            {
                ForceRecalculateTransform = false;
                _Position = value;
            }
        }
    
    MaZiFAU's avatar
    MaZiFAU committed
        private Vector3 _Position = Vector3.zero;
    
    MaZiFAU's avatar
    MaZiFAU committed
    
        [JsonIgnore]
        public Quaternion Rotation
        {
            get
            {
                if (ForceRecalculateTransform)
                    RecalculateTransform();
                return _Rotation;
            }
            protected set
            {
                ForceRecalculateTransform = false;
                _Rotation = value;
            }
        }
    
    MaZiFAU's avatar
    MaZiFAU committed
        private Quaternion _Rotation = Quaternion.identity;
    
    MaZiFAU's avatar
    MaZiFAU committed
        [JsonIgnore]
    
    MaZiFAU's avatar
    MaZiFAU committed
        public Vector3 LocalScale
        {
            get
            {
                if (ForceRecalculateTransform)
                    RecalculateTransform();
                return _LocalScale;
            }
            protected set
            {
                ForceRecalculateTransform = false;
                _LocalScale = value;
            }
        }
    
    MaZiFAU's avatar
    MaZiFAU committed
        private Vector3 _LocalScale = Vector3.one;
    
    MaZiFAU's avatar
    MaZiFAU committed
    
    
        /// <summary>
        /// Only being used by [JsonReader](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonReader.htm) to initiate empty \ref Fact "Facts".
    
    MaZiFAU's avatar
    MaZiFAU committed
            this._Facts = null; // new FactOrganizer();
    
        /// <summary>
        /// Standard base-constructor.
        /// </summary>
        /// <param name="organizer"><see cref="_Facts"/></param>
    
        protected Fact(FactOrganizer organizer) : this()
    
        /// <summary>
        /// Copies <paramref name="fact"/> by initiating new MMT %Fact.
        /// </summary>
        /// <param name="fact">Fact to be copied</param>
    
    MaZiFAU's avatar
    MaZiFAU committed
        /// <param name="old_to_new"><c>Dictionary</c> mapping <paramref name="fact"/>.<see cref="getDependentFactIds"/> in <paramref name="fact"/>.<see cref="Fact._Facts"/> to corresponding <see cref="Fact.Id"/> in <paramref name="organizer"/> </param>
    
        /// <param name="organizer"><see cref="_Facts"/></param>
    
    MaZiFAU's avatar
    MaZiFAU committed
        public Fact ReInitializeMe(Dictionary<string, string> old_to_new, FactOrganizer organizer)
    
    BenniHome's avatar
    BenniHome committed
        {
    
    MaZiFAU's avatar
    MaZiFAU committed
            Fact ret = _ReInitializeMe(old_to_new, organizer);
    
    MaZiFAU's avatar
    MaZiFAU committed
            ret.LabelId = this.LabelId;
            if (ret.hasCustomLabel)
                ret._CustomLabel = this.Label;
    
            return ret;
    
    MaZiFAU's avatar
    MaZiFAU committed
        protected abstract Fact _ReInitializeMe(Dictionary<string, string> old_to_new, FactOrganizer organizer);
    
        /// <summary>
        /// Assignes a custom <see cref="Label"/>, if <paramref name="newLabel"/> is not yet taken;
        /// or clears custom <see cref="Label"/>.
        /// </summary>
        /// <param name="newLabel">To be new <see cref="Label"/>. To reset to auto-generation set to <c>null</c> or <c>""</c>.</param>
        /// <returns></returns>
    
    
        //TODO: notify about updated dependable Labelnames for UI
        //TODO: check for colissions with not yet generated names
        public bool rename(string newLabel)
        // returns true if succeded
        {
    
    MaZiFAU's avatar
    MaZiFAU committed
            if (string.IsNullOrEmpty(newLabel) && _Facts.GetNumberOfFacts() != 0)
    
            // switch back to autogenerated
            {
                generateLabel();
                _CustomLabel = null;
                return true;
            }
            else
            // set CustomLabel if available
            {
                if (_Facts.ContainsLabel(newLabel))
                    return false;
    
                freeAutoLabel();
                _CustomLabel = newLabel;
    
    BenniHome's avatar
    BenniHome committed
        }
    
    MaZiFAU's avatar
    MaZiFAU committed
        protected abstract void RecalculateTransform();
    
    MaZiFAU's avatar
    MaZiFAU committed
    
    
        public abstract MMTFact MakeMMTDeclaration();
    
        /// <summary>
        /// Frees ressources e.g. <see cref="Label"/> and will eventually delete %Fact Server-Side in far-near future when feature is supported.
        /// </summary>
    
            //TODO: MMT: delete over there
    
            if (CommunicationEvents.VerboseURI)
    
                Debug.Log("Server removed Fact:\n" + this.Id);
    
        /// <summary>
        /// Compares \ref Fact "this" against <paramref name="f2"/>.
        /// </summary>
        /// <param name="f2">Fact to compare to</param>
        /// <returns><c>true</c> if <paramref name="f2"/> is semantical very similar to \ref Fact "this"</returns>
    
        public abstract bool Equivalent(Fact f2);
    
    
        /// <summary>
        /// Compares <paramref name="f1"/> against <paramref name="f2"/>.
        /// </summary>
        /// <param name="f1">Fact to compare to</param>
        /// <param name="f2">Fact to compare to</param>
        /// <returns><c>true</c> if <paramref name="f2"/> is semantical very similar to <paramref name="f1"/></returns>
    
        public abstract bool Equivalent(Fact f1, Fact f2);
    
        /// <summary>
        /// canonical
        /// </summary>
        /// <returns>unique-ish Hash</returns>
    
    MaZiFAU's avatar
    MaZiFAU committed
        public new virtual int GetHashCode()
    
    MaZiFAU's avatar
    MaZiFAU committed
                .Select(id => id.GetHashCode())
                .Aggregate((hash1, hash2) => hash1 ^ hash2);
    
        /// <summary>
        /// auto-generates <see cref="Label"/> using generation variable(s) e.g. <see cref="LabelId"/>;
        /// if custom <see cref="Label"/> is set, tries to restore original generated <see cref="Label"/> **without** resetting <see cref="_CustomLabel"/>. If original <see cref="Label"/> is already taken, a new one will be generated.
        /// </summary>
        /// <returns>auto-generated <see cref="Label"/></returns>
    
                // reload Label if possible
    
                LabelId = _Facts.UnusedLabelIds.Remove(-LabelId) ? -LabelId : 0;
    
    
                if (_Facts.UnusedLabelIds.Count == 0)
                    LabelId = ++_Facts.MaxLabelId;
    
                    LabelId = _Facts.UnusedLabelIds.Min;
                    _Facts.UnusedLabelIds.Remove(LabelId);
    
            return ((char)(64 + LabelId)).ToString();
        }
    
    
        /// Parses <see cref="MMTFact"/> to actual Fact
    
        /// </summary>
        /// <param name="fact">instance to be parsed</param>
        /// <returns>parsed Fact</returns>
    
        public static Fact parseFact(MMTFact fact)
    
    
        /// <summary>
        /// Tells <see cref="_Facts"/> that \ref Fact "this" no longer uses auto-generated <see cref="Label"/>, but remembers current generation variable(s).
        /// </summary>
    
    
        // TODO? only get _Fact to freeLabel/
        public /*protected internal*/ void freeAutoLabel()
        {
            if (LabelId > 0)
    
                _Facts.UnusedLabelIds.Add(LabelId);
    
                // store Label for name-persistance
    
    MaZiFAU's avatar
    MaZiFAU committed
    
    
        protected void SendToMMT()
            => _URI = SendToMMT(MakeMMTDeclaration());
    
    
        /// <summary>
        /// 
        /// </summary>
        /// <remarks>Asynchron version has proofen inefficent, since <see cref="Fact.Id"/> is usually called in close proximity.</remarks>
        // Asynchron version in comments
    
        public static string SendToMMT(MMTFact mmtDecl)
    
    MaZiFAU's avatar
    MaZiFAU committed
        {
    
            //GlobalBehaviour.Instance.StartCoroutine(
            //    FetchURICoroutine = 
    
            //_URI =
            string uri =
    
                _SendAdd(
    
    MaZiFAU's avatar
    MaZiFAU committed
                    CommunicationEvents.ServerAdress + "/fact/add",
    
                    mmtDecl.ToJson()
    
    MaZiFAU's avatar
    MaZiFAU committed
            //,(string uri) => _SendURICallback(mmtDecl, uri)
    
    MaZiFAU's avatar
    MaZiFAU committed
    
    
            //return;
    
    MaZiFAU's avatar
    MaZiFAU committed
    
    
            //void _SendURICallback(MMTDeclaration mmtDecl, string uri)
            //{
            //    _URI = uri;
    
    MaZiFAU's avatar
    MaZiFAU committed
    
    
            if (mmtDecl is MMTGeneralFact mMTSymbol && mMTSymbol.defines != null)
    
                ParsingDictionary.parseTermsToId[mMTSymbol.defines.ToString()] = uri;// _URI;
    
    MaZiFAU's avatar
    MaZiFAU committed
    
    
            /*IEnumerator*/
    
            static string _SendAdd(string path, string body)//, Action<string> uriCallback)
    
    MaZiFAU's avatar
    MaZiFAU committed
            {
                if (!CommunicationEvents.ServerRunning)
                {
                    Debug.LogWarning("Server not running");
    
                    //uriCallback(null);
                    return null; // yield break;
    
    MaZiFAU's avatar
    MaZiFAU committed
                }
    
                if (CommunicationEvents.VerboseURI)
                    Debug.Log("Sending to Server:\n" + body);
    
                //Put constructor parses stringbody to byteArray internally  (goofy workaround)
                using UnityWebRequest www = UnityWebRequest.Put(path, body);
                www.method = UnityWebRequest.kHttpVerbPOST;
                www.SetRequestHeader("Content-Type", "application/json");
                www.timeout = 1;
    
    
                //yield return 
                UnityWebRequestAsyncOperation web =
                    www.SendWebRequest();
    
                while (!web.isDone) ;
    
    MaZiFAU's avatar
    MaZiFAU committed
    
                if (www.result == UnityWebRequest.Result.ConnectionError
                 || www.result == UnityWebRequest.Result.ProtocolError)
                {
                    Debug.LogWarning(www.error);
    
                    //uriCallback(null);
                    return null; // yield break;
    
    MaZiFAU's avatar
    MaZiFAU committed
                }
                else
                {
    
                    while (!www.downloadHandler.isDone)
                        //yield return null
                        ;
    
    MaZiFAU's avatar
    MaZiFAU committed
    
    
                    FactReference res = JsonUtility.FromJson<FactReference>(www.downloadHandler.text);
    
    MaZiFAU's avatar
    MaZiFAU committed
    
                    if (CommunicationEvents.VerboseURI)
                        Debug.Log("Server added Fact:\n" + res.uri);
    
    
                    //uriCallback(res.uri);
                    return res.uri; // yield break;
    
    /// <summary>
    /// Implements CRTP for <see cref="Fact"/>; Escalates constructors;
    /// </summary>
    /// <typeparam name="T">class, which inherits from FactWrappedCRTP</typeparam>
    
    public abstract class FactWrappedCRTP<T> : Fact where T : FactWrappedCRTP<T>
    
    BenniHome's avatar
    BenniHome committed
    {
    
        /// <summary>\copydoc Fact.Fact()</summary>
    
        protected FactWrappedCRTP() : base() { }
    
    
        /// <summary>\copydoc Fact.Fact(FactOrganizer)</summary>
    
        protected FactWrappedCRTP(FactOrganizer organizer) : base(organizer) { }
    
    
        public override bool Equivalent(Fact f2)
    
            => Equivalent(this, f2);
    
        /// \copydoc Fact.Equivalent(Fact, Fact)
    
        public override bool Equivalent(Fact f1, Fact f2)
    
            => f1.GetType() == f2.GetType() && EquivalentWrapped((T)f1, (T)f2);
    
        /// <summary>CRTP step of <see cref="Equivalent(Fact)"/> and <see cref="Equivalent(Fact, Fact)"/></summary>
    
        protected abstract bool EquivalentWrapped(T f1, T f2);
    
    MaZiFAU's avatar
    MaZiFAU committed
    
        protected bool DependentFactsEquivalent(T f1, T f2)
    
            => f1.DependentFactIds
                .Zip(f2.DependentFactIds,
    
    MaZiFAU's avatar
    MaZiFAU committed
                    (id1, id2) =>
    
    MaZiFAU's avatar
    MaZiFAU committed
                        id1 == id2
    
    MaZiFAU's avatar
    MaZiFAU committed
                        || FactOrganizer.AllFacts[id1].Equivalent(FactOrganizer.AllFacts[id2])
                )
                .All(b => b);
    
    /// <summary>
    /// Point in 3D Space
    /// </summary>
    
    public class PointFact : FactWrappedCRTP<PointFact>
    
        public Vector3 Point;
    
        /// <summary> Orientation for <see cref="Fact.WorldRepresentation"/> </summary>
    
        /// <summary> \copydoc Fact.Fact </summary>
    
        public PointFact() : base()
        {
            this.Point = Vector3.zero;
    
        /// Standard Constructor:
        /// Initiates <see cref="Point"/>, <see cref="Normal"/>, <see cref="Fact._URI"/> and creates MMT %Fact Server-Side
    
        /// </summary>
        /// <param name="P">sets <see cref="Point"/></param>
        /// <param name="N">sets <see cref="Normal"/></param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
    
        public PointFact(Vector3 P, Vector3 N, FactOrganizer organizer) : base(organizer)
    
    BenniHome's avatar
    BenniHome committed
        {
    
            this.Point = P;
            this.Normal = N;
    
    
    MaZiFAU's avatar
    MaZiFAU committed
            SendToMMT();
    
    MaZiFAU's avatar
    MaZiFAU committed
        protected override void RecalculateTransform()
    
    MaZiFAU's avatar
    MaZiFAU committed
        {
            Position = Point;
    
            { // Rotation
                Vector3 notNormal = Vector3.forward != Normal ? Vector3.forward : Vector3.up;
                Rotation = Quaternion.LookRotation(
                    Vector3.Cross(Normal, notNormal),
                    Normal
                );
            }
    
    MaZiFAU's avatar
    MaZiFAU committed
        }
    
    
        /// <summary>
        /// Bypasses initialization of new MMT %Fact by using existend URI, _which is not checked for existence_.
        /// <see cref="Normal"/> set to <c>Vector3.up</c>
        /// </summary>
    
        /// <param name="point">sets <see cref="Point"/></param>
    
        /// <param name="uri">MMT URI</param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
    
        public PointFact(Vector3 point, string uri, FactOrganizer organizer) : base(organizer)
    
            this._URI = uri;
    
        /// \copydoc Fact.parseFact(ScrollFact)
    
        public new static PointFact parseFact(MMTFact fact)
    
            if (((MMTGeneralFact)fact).defines is not OMA defines)
    
    MaZiFAU's avatar
    MaZiFAU committed
            ParsingDictionary.parseTermsToId.TryAdd(defines.ToString(), fact.@ref.uri);
    
            Vector3 point = (defines.GetLambdaExpression().Compile() as Func<Vector3>)();
            return new PointFact(point, fact.@ref.uri, StageStatic.stage.factState);
    
    BenniHome's avatar
    BenniHome committed
    
    
        public override bool HasDependentFacts => false;
    
        /// \copydoc Fact.getDependentFactIds
    
    MaZiFAU's avatar
    MaZiFAU committed
        protected override string[] GetGetDependentFactIds()
    
        /// \copydoc Fact.Equivalent(Fact, Fact)
    
        protected override bool EquivalentWrapped(PointFact f1, PointFact f2)
    
            => Math3d.IsApproximatelyEqual(f1.Point, f2.Point);
    
    MaZiFAU's avatar
    MaZiFAU committed
    
        protected override Fact _ReInitializeMe(Dictionary<string, string> old_to_new, FactOrganizer organizer)
            => new PointFact(this.Point, this.Normal, organizer);
    
        public override MMTFact MakeMMTDeclaration()
    
            SOMDoc tp = new OMS(MMTConstants.Point);
    
            SOMDoc df = new OMA(
    
                    new OMS(MMTConstants.Tuple),
    
    MaZiFAU's avatar
    MaZiFAU committed
                    new[] {
    
                            new OMF(Point.x),
                            new OMF(Point.y),
                            new OMF(Point.z),
                    }
                );
    
    
            return new MMTGeneralFact(Label, tp, df);
    
    /// <summary>
    /// A <see cref="PointFact"/> on a <see cref="AbstractLineFact"/>
    /// </summary>
    
    public class OnLineFact : FactWrappedCRTP<OnLineFact>
    
        /// <summary> <see cref="PointFact"/>.<see cref="Fact.Id">Id</see> </summary>
        public string Pid;
        [JsonIgnore]
    
    MaZiFAU's avatar
    MaZiFAU committed
        public PointFact Point { get => (PointFact)FactOrganizer.AllFacts[Pid]; }
    
    
        /// <summary> <see cref="AbstractLineFact"/>.<see cref="Fact.Id">Id</see> </summary>
        public string Rid;
        [JsonIgnore]
    
    MaZiFAU's avatar
    MaZiFAU committed
        public AbstractLineFact Ray { get => (AbstractLineFact)FactOrganizer.AllFacts[Rid]; }
    
        /// <summary> \copydoc Fact.Fact </summary>
    
        public OnLineFact() : base()
        {
            this.Pid = null;
            this.Rid = null;
        }
    
    
        /// Standard Constructor:
        /// Initiates <see cref="Pid"/>, <see cref="Rid"/>, <see cref="Fact._URI"/> and creates MMT %Fact Server-Side
    
        /// </summary>
        /// <param name="pid">sets <see cref="Pid"/></param>
        /// <param name="rid">sets <see cref="Rid"/></param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
    
        public OnLineFact(string pid, string rid, FactOrganizer organizer) : base(organizer)
    
    MaZiFAU's avatar
    MaZiFAU committed
            SendToMMT();
    
    MaZiFAU's avatar
    MaZiFAU committed
        protected override void RecalculateTransform()
    
    MaZiFAU's avatar
    MaZiFAU committed
        {
            Position = Point.Position;
            { //Rotation
    
    MaZiFAU's avatar
    MaZiFAU committed
                Vector3 forward = Ray.Dir;
    
                if (Math3d.IsApproximatelyEqual(up, forward))
                {
                    Vector3 arbitary = Math3d.IsApproximatelyEqual(forward, Vector3.forward)
                        ? Vector3.right
                        : Vector3.forward;
    
                    up = Vector3.Cross(arbitary, forward);
                }
    
                Rotation = Quaternion.LookRotation(forward, up);
            }
        }
    
    
        /// <summary>
        /// Bypasses initialization of new MMT %Fact by using existend URI, _which is not checked for existence_.
        /// </summary>
        /// <param name="pid">sets <see cref="Pid"/></param>
        /// <param name="rid">sets <see cref="Rid"/></param>
        /// <param name="uri">MMT URI</param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
    
        public OnLineFact(string pid, string rid, string uri, FactOrganizer organizer) : base(organizer)
    
            this._URI = uri;
    
        /// \copydoc Fact.parseFact(ScrollFact)
    
        public new static OnLineFact parseFact(MMTFact fact)
    
            string pointUri = ((OMS)((OMA)((OMA)((MMTGeneralFact)fact).type).arguments[0]).arguments[1]).uri;
            string lineUri = ((OMA)((OMA)((MMTGeneralFact)fact).type).arguments[0]).arguments[0] is OMS
    
                ? ((OMS)((OMA)((OMA)((MMTGeneralFact)fact).type).arguments[0]).arguments[0]).uri
    
                // case when line Uri has a projl on the line Argument 
    
                : ((OMS)((OMA)((OMA)((OMA)((MMTGeneralFact)fact).type).arguments[0]).arguments[0]).arguments[0]).uri;
    
    MaZiFAU's avatar
    MaZiFAU committed
            if (!FactOrganizer.AllFacts.ContainsKey(pointUri)
             || !FactOrganizer.AllFacts.ContainsKey(lineUri))
                return null;
    
    MaZiFAU's avatar
    MaZiFAU committed
            return new OnLineFact(pointUri, lineUri, fact.@ref.uri, StageStatic.stage.factState);
    
        protected override string generateLabel()
    
    MaZiFAU's avatar
    MaZiFAU committed
            => Point.Label + "∈" + Ray.Label;
    
    BenniHome's avatar
    BenniHome committed
    
    
        public override bool HasDependentFacts => true;
    
        /// \copydoc Fact.getDependentFactIds
    
    MaZiFAU's avatar
    MaZiFAU committed
        protected override string[] GetGetDependentFactIds()
    
        protected override bool EquivalentWrapped(OnLineFact f1, OnLineFact f2)
    
    MaZiFAU's avatar
    MaZiFAU committed
            => DependentFactsEquivalent(f1, f2);
    
    MaZiFAU's avatar
    MaZiFAU committed
    
        protected override Fact _ReInitializeMe(Dictionary<string, string> old_to_new, FactOrganizer organizer)
            => new OnLineFact(old_to_new[this.Pid], old_to_new[this.Rid], organizer);
    
        public override MMTFact MakeMMTDeclaration()
    
        {
            SOMDoc tp = new OMA(
    
                new OMS(MMTConstants.Ded),
    
    MaZiFAU's avatar
    MaZiFAU committed
                new[] {
    
                        new OMS(MMTConstants.OnLine),
    
    MaZiFAU's avatar
    MaZiFAU committed
                        new[]  {
    
                            new OMS(Rid),
                            new OMS(Pid)
            }),});
    
            SOMDoc df = null;
    
    
            return new MMTGeneralFact(this.Label, tp, df);
    
    /// <summary>
    /// Two parallel Lines comprised of two <see cref="LineFact">LineFacts</see> 
    /// </summary>
    public class ParallelLineFact : FactWrappedCRTP<ParallelLineFact>
    {
        /// @{ <summary>
    
        /// One <see cref="Fact.Id">Id</see> of two <see cref="LineFact"/> that are parallel [<see cref="Lid1"/>, <see cref="Lid2"/>].
    
        /// </summary>
        public string Lid1, Lid2;
        /// @}
    
    
    MaZiFAU's avatar
    MaZiFAU committed
        public AbstractLineFact Ray1 { get => (AbstractLineFact)FactOrganizer.AllFacts[Lid1]; }
    
    MaZiFAU's avatar
    MaZiFAU committed
        public AbstractLineFact Ray2 { get => (AbstractLineFact)FactOrganizer.AllFacts[Lid2]; }
    
    
        /// <summary> \copydoc Fact.Fact </summary>
        public ParallelLineFact() : base()
        {
            this.Lid1 = null;
            this.Lid2 = null;
        }
    
        /// <summary>
        /// Standard Constructor
        /// </summary>
        /// <param name="lid1">sets <see cref="Lid1"/></param>
        /// <param name="lid2">sets <see cref="Lid2"/></param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
        public ParallelLineFact(string lid1, string lid2, FactOrganizer organizer) : base(organizer)
        {
            this.Lid1 = lid1;
            this.Lid2 = lid2;
    
    
    MaZiFAU's avatar
    MaZiFAU committed
            SendToMMT();
    
    MaZiFAU's avatar
    MaZiFAU committed
        protected override void RecalculateTransform() { }
    
    MaZiFAU's avatar
    MaZiFAU committed
    
    
        /// <summary>
        /// Bypasses initialization of new MMT %Fact by using existend URI, _which is not checked for existence_.
        /// </summary>
        /// <param name="Lid1">sets <see cref="Lid1"/></param>
        /// <param name="Lid2">sets <see cref="Lid2"/></param>
        /// <param name="backendURI">MMT URI</param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
        public ParallelLineFact(string Lid1, string Lid2, string backendURI, FactOrganizer organizer) : base(organizer)
        {
            this.Lid1 = Lid1;
            this.Lid2 = Lid2;
    
            this._URI = backendURI;
            _ = this.Label;
        }
    
    
        /// \copydoc Fact.parseFact(ScrollFact)
    
        public new static ParallelLineFact parseFact(MMTFact fact)
    
            if (((MMTGeneralFact)fact).type is not OMA type) // proof DED
    
    MaZiFAU's avatar
    MaZiFAU committed
            OMA parallel_lines_OMA = (OMA)type.arguments[0]; // parallel
    
    MaZiFAU's avatar
    MaZiFAU committed
            string lineAUri = ((OMS)parallel_lines_OMA.arguments[0]).uri;
            string lineBUri = ((OMS)parallel_lines_OMA.arguments[1]).uri;
    
    MaZiFAU's avatar
    MaZiFAU committed
            if (!FactOrganizer.AllFacts.ContainsKey(lineAUri)
             || !FactOrganizer.AllFacts.ContainsKey(lineBUri))
    
    MaZiFAU's avatar
    MaZiFAU committed
    
            return new ParallelLineFact(lineAUri, lineBUri, fact.@ref.uri, StageStatic.stage.factState);
    
        }
    
        /// \copydoc Fact.generateLabel
    
        protected override string generateLabel()
    
    MaZiFAU's avatar
    MaZiFAU committed
            => Ray1.Label + "||" + Ray2.Label;
    
        public override MMTFact MakeMMTDeclaration()
    
                new OMS(MMTConstants.Ded),
    
    MaZiFAU's avatar
    MaZiFAU committed
                new[] {
    
                        new OMS(MMTConstants.ParallelLine),
    
    MaZiFAU's avatar
    MaZiFAU committed
                        new[]  {
    
                            new OMS(Lid1),
                            new OMS(Lid2),
    
            return new MMTGeneralFact(this.Label, tp, df);
    
        }
    
        /// \copydoc Fact.hasDependentFacts
    
        public override bool HasDependentFacts => true;
    
    
        /// \copydoc Fact.getDependentFactIds
    
    MaZiFAU's avatar
    MaZiFAU committed
        protected override string[] GetGetDependentFactIds()
    
            => new string[] { Lid1, Lid2 };
    
    
        /// \copydoc Fact.Equivalent(Fact, Fact)
    
    MaZiFAU's avatar
    MaZiFAU committed
        protected override bool EquivalentWrapped(ParallelLineFact f1, ParallelLineFact f2)
    
    MaZiFAU's avatar
    MaZiFAU committed
            => DependentFactsEquivalent(f1, f2);
    
    MaZiFAU's avatar
    MaZiFAU committed
    
        protected override Fact _ReInitializeMe(Dictionary<string, string> old_to_new, FactOrganizer organizer)
            => new ParallelLineFact(old_to_new[this.Lid1], old_to_new[this.Lid2], organizer);
    
    /// A Circle that is made out of a middle point, a plane and a radius
    
    /// </summary>
    public class CircleFact : FactWrappedCRTP<CircleFact>
    {
        /// <summary> defining the middle point of the circle  </summary>
        public string Pid1;
        /// <summary>  defining the base point of the circle plane </summary>
        public string Pid2;
    
    MaZiFAU's avatar
    MaZiFAU committed
        public PointFact Point1 { get => (PointFact)FactOrganizer.AllFacts[Pid1]; }
    
    MaZiFAU's avatar
    MaZiFAU committed
        public PointFact Point2 { get => (PointFact)FactOrganizer.AllFacts[Pid2]; }
    
        /// <summary>  radius of the circle </summary>
        public float radius;
        /// <summary> normal vector of the plane </summary>
        public Vector3 normal;
    
        /// <summary> \copydoc Fact.Fact </summary>
        public CircleFact() : base()
        {
            this.normal = Vector3.zero;
            this.Pid1 = null;
            this.Pid2 = null;
            this.radius = 0;
        }
    
        /// <summary>
    
        /// Standard Constructor:
        /// Initiates <see cref="Pid1"/>, <see cref="Pid2"/>, <see cref="radius"/>,<see cref="dir1"/>,<see cref="dir2"/>, <see cref="Fact._URI"/> and creates MMT %Fact Server-Side
    
        /// </summary>
        /// <param name="pid1">sets <see cref="Pid1"/></param>
        /// <param name="pid2">sets <see cref="Pid2"/></param>
        /// <param name="radius">sets <see cref="radius"/></param>
        /// <param name="normal">sets <see cref="normal"/></param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
        public CircleFact(string pid1, string pid2, float radius, Vector3 normal, FactOrganizer organizer) : base(organizer)
        {
            this.Pid1 = pid1;
            this.Pid2 = pid2;
    
            this.radius = radius;
            this.normal = normal;
    
    
    MaZiFAU's avatar
    MaZiFAU committed
            SendToMMT();
    
    MaZiFAU's avatar
    MaZiFAU committed
        protected override void RecalculateTransform()
    
    MaZiFAU's avatar
    MaZiFAU committed
        {
            Position = Point1.Position;
    
            { //Rotation
                Vector3 arbitary_not_normal = normal == Vector3.forward ? Vector3.right : Vector3.forward;
                Vector3 forwoard = Vector3.Cross(arbitary_not_normal, normal);
    
                Rotation = Quaternion.LookRotation(forwoard, normal);
            }
    
    MaZiFAU's avatar
    MaZiFAU committed
            LocalScale = new Vector3(radius, 1, radius);
        }
    
    
        /// <summary>
        /// Bypasses initialization of new MMT %Fact by using existend URI, _which is not checked for existence_.
        /// </summary>
        /// <param name="Pid1">sets <see cref="Pid1"/></param>
        /// <param name="Pid2">sets <see cref="Pid2"/></param>
        /// <param name="radius">sets <see cref="radius"/></param>
        /// <param name="normal">sets <see cref="normal"/></param>
        /// <param name="backendURI">MMT URI</param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
        public CircleFact(string Pid1, string Pid2, float radius, Vector3 normal, string backendURI, FactOrganizer organizer) : base(organizer)
        {
            this.Pid1 = Pid1;
            this.Pid2 = Pid2;
    
            this.radius = radius;
            this.normal = normal;
    
            this._URI = backendURI;
            _ = this.Label;
        }
    
        /// <summary>
        /// parses the Circlefact response of the MMT-Server
        /// </summary>
    
        /// \copydoc Fact.parseFact(ScrollFact) 
    
        public new static CircleFact parseFact(MMTFact fact)
    
            if (((MMTGeneralFact)fact).defines is not OMA df)
    
    MaZiFAU's avatar
    MaZiFAU committed
            OMA planeOMA = (OMA)df.arguments[0];
    
    Marcel Dreier's avatar
    Marcel Dreier committed
            string planeApplicant = ((OMS)planeOMA.applicant).uri;
    
    
            Vector3 normal;
    
    Marcel Dreier's avatar
    Marcel Dreier committed
            // Getting the plane
            // IN case of a normale plane
    
            if (planeApplicant.Equals(MMTConstants.pointNormalPlane))
    
    Marcel Dreier's avatar
    Marcel Dreier committed
            {
    
                //OMA pointAOMA = (OMA)planeOMA.arguments[0];
    
    MaZiFAU's avatar
    MaZiFAU committed
                normal = (planeOMA.arguments[1].GetLambdaExpression().Compile() as Func<Vector3>)();
    
    Marcel Dreier's avatar
    Marcel Dreier committed
            }
            // In case of parametrized plane
    
            else if (planeApplicant.Equals(MMTConstants.ParametrizedPlane))
    
    Marcel Dreier's avatar
    Marcel Dreier committed
            {
    
    MaZiFAU's avatar
    MaZiFAU committed
                Vector3 v = (planeOMA.arguments[1].GetLambdaExpression().Compile() as Func<Vector3>)();
                Vector3 w = (planeOMA.arguments[2].GetLambdaExpression().Compile() as Func<Vector3>)();
    
    Marcel Dreier's avatar
    Marcel Dreier committed
    
                normal = Vector3.Cross(v, w).normalized;
            }
    
    ki7077's avatar
    ki7077 committed
            // incase of smth else. Shouldn't hapepen unless there is an error
    
            else throw new ArgumentException("Invalid planeApplicant: " + planeApplicant);
    
            // get the mid point uri
    
    MaZiFAU's avatar
    MaZiFAU committed
            string parse_id_M = df.arguments[1].ToString();
    
            string M_uri = ParsingDictionary.parseTermsToId[parse_id_M];
    
    MaZiFAU's avatar
    MaZiFAU committed
            string A_uri = ParsingDictionary.parseTermsToId[planeOMA.arguments[0].ToString()];
            float radius = ((OMF)df.arguments[2]).@float;
    
    MaZiFAU's avatar
    MaZiFAU committed
            if (!FactOrganizer.AllFacts.ContainsKey(M_uri)
             || !FactOrganizer.AllFacts.ContainsKey(A_uri))
                return null; //If dependent facts do not exist return null
    
    MaZiFAU's avatar
    MaZiFAU committed
            return new CircleFact(M_uri, A_uri, radius, normal, fact.@ref.uri, StageStatic.stage.factState);
    
        }
    
        /// \copydoc Fact.generateLabel
        protected override string generateLabel()
    
    MaZiFAU's avatar
    MaZiFAU committed
            => "○" + Point1.Label;