Inheritance: MonoBehaviour
Beispiel #1
1
        /// <summary>
        /// Checks if curve is flipped to a plane.
        /// </summary>
        /// <param name="plane">
        /// The plane.
        /// </param>
        /// <param name="curve">
        /// The curve.
        /// </param>
        /// <returns>
        /// True if the curve is flipped to the plane, false otherwise.
        /// </returns>
        public static bool MustFlipCurve(Plane plane, Curve curve)
        {
            XYZ xVector = null;
            XYZ yVector = null;
            if (curve is Arc)
            {
                Arc arc = curve as Arc;
                xVector = arc.XDirection;
                yVector = arc.YDirection;
            }
            else if (curve is Ellipse)
            {
                Ellipse ellipse = curve as Ellipse;
                xVector = ellipse.XDirection;
                yVector = ellipse.YDirection;
            }
            else
                return false;

            List<double> realListX = ConvertVectorToLocalCoordinates(plane, xVector);
            List<double> realListY = ConvertVectorToLocalCoordinates(plane, yVector);

            double dot = realListY[0] * (-realListX[1]) + realListY[1] * (realListX[0]);
            if (dot < -MathUtil.Eps())
                return true;

            return false;
        }
Beispiel #2
0
 public void StartAndEnd () {
     var c = new Curve<double>();
     c[-2] = 1;
     c[7] = 2;
     Assert.AreEqual(c.Start, -2);
     Assert.AreEqual(c.End, 7);
 }
Beispiel #3
0
        protected static void setCurveMethod(Autodesk.Revit.DB.CurveElement ce, Curve c)
        {
            bool foundMethod = false;

            if (hasMethodSetCurve)
            {
                Type CurveElementType = typeof(Autodesk.Revit.DB.CurveElement);
                MethodInfo[] curveElementMethods = CurveElementType.GetMethods(BindingFlags.Instance | BindingFlags.Public);
                String nameOfMethodSetCurve = "SetGeometryCurveOverridingJoins";

                foreach (MethodInfo m in curveElementMethods)
                {
                    if (m.Name == nameOfMethodSetCurve)
                    {
                        object[] argsM = new object[1];
                        argsM[0] = c;

                        foundMethod = true;
                        m.Invoke(ce, argsM);
                        break;
                    }
                }
            }
            if (!foundMethod)
            {
                hasMethodSetCurve = false;
                ce.GeometryCurve = c;
            }
        }
Beispiel #4
0
        public void GetLowerIndexForPosition () {
            var c = new Curve<double>();
            c[-1] = 0;
            c[-0.5f] = 1;
            c[0] = 2;
            c[1] = 3;
            c[2] = 4;
            c[4] = 5;
            c[32] = 6;

            int i;

            i = c.GetLowerIndexForPosition(-2);
            Assert.AreEqual(i, 0);

            i = c.GetLowerIndexForPosition(-1);
            Assert.AreEqual(i, 0);

            i = c.GetLowerIndexForPosition(-0.6f);
            Assert.AreEqual(i, 0);

            i = c.GetLowerIndexForPosition(-0.5f);
            Assert.AreEqual(i, 1);

            i = c.GetLowerIndexForPosition(0.5f);
            Assert.AreEqual(i, 2);

            i = c.GetLowerIndexForPosition(5);
            Assert.AreEqual(i, 5);

            i = c.GetLowerIndexForPosition(36);
            Assert.AreEqual(i, 6);
        }
Beispiel #5
0
 public void SingleValue () {
     var c = new Curve<double>();
     c[0] = 5.0;
     Assert.AreEqual(5.0, c[-1]);
     Assert.AreEqual(5.0, c[0]);
     Assert.AreEqual(5.0, c[1]);
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsCallback)
        {
            //http://www.codeproject.com/articles/432860/asp-net-plotter-toolkit-html5-charting-for-all
            AlsiDBDataContext dc = new AlsiDBDataContext();
            var data = dc.OHLC_5_Minutes.Take(25000).ToList();
            Label1.Text = data.Count.ToString();
            Curve curve = new Curve();
            var points = new Point[data.Count];

            for (int x = 0; x < data.Count; x++)
            {
                var p = new Point(data[x].Stamp, data[x].C);
                points[x] = p;
            }


            BindingList<Curve> Curves = new BindingList<Curve> { curve };

            curve.Points = points;
            curve.Label = "Dfdfdfdff";

            Dygraph1.Curves = Curves;
         
            Dygraph1.YLowRange = data.Min(z => z.C);//if error check db
            Dygraph1.YHighRange = data.Max(z => z.C);
        }
        
    }
        public RetroBloomFilter()
            : base()
        {
            Name = "Bloom";
            ShortDescription = "Bloom";

            _levelFilter = new LevelsFilter(0.9, 0.6, 0.0);

            _curvesFilter = new CurvesFilter();
            Curve red = new Curve();
            red.SetPoint(127, 100);
            red.SetPoint(235, 255);

            Curve green = new Curve();
            green.SetPoint(97, 72);
            green.SetPoint(177, 189);

            Curve blue = new Curve();
            blue.SetPoint(0, 34);
            blue.SetPoint(255, 220);

            _curvesFilter.Red = red;
            _curvesFilter.Green = green;
            _curvesFilter.Blue = blue;

            _vignettingFilter = new VignettingFilter(0.5, new Windows.UI.Color { R = 104, G = 103, B = 71 });
            //_vignettingFilter = new VignettingFilter(0.3, new Windows.UI.Color { R = 255, G = 0, B = 0 });

            _hueSaturationFilter = new HueSaturationFilter(5.0 / 255.0, -40.0 / 255.0);
            _colorAdjustFilter = new ColorAdjustFilter(45.0 / 255.0, -41.0 / 255.0, -89.0 / 255.0);
        }
        public FantasticEffect()
        {
            var globalCurve = new Curve(CurveInterpolation.NaturalCubicSpline)
            {
                Points = new[]
                {
                    new Point(0, 0),
                    new Point(68, 60),                    
                    new Point(144, 163),                    
                    new Point(255, 255),            
                }
            };

            var overlayFactory1 = new OverlayFactory(
                "ms-appx:///images/Filters_Landscape_Overlay_Fantastic1.jpg",
                "ms-appx:///images/Filters_Portrait_Overlay_Fantastic1.jpg",
                "ms-appx:///images/Filters_Square_Overlay_Fantastic1.jpg");

            var overlayFactory2 = new OverlayFactory(
                "ms-appx:///images/Filters_Landscape_Overlay_Fantastic2.png",
                "ms-appx:///images/Filters_Portrait_Overlay_Fantastic2.png",
                "ms-appx:///images/Filters_Square_Overlay_Fantastic2.png");
            
            LayerList = new LayerList()
            {
                new AdjustmentLayer(LayerStyle.Normal(), new ContrastEffect(1.0)),
                new AdjustmentLayer(LayerStyle.Normal(), new CurvesEffect(globalCurve)),
                new AdjustmentLayer(LayerStyle.Normal(), new GrayscaleEffect(0.54, 0.64, 0.0, -0.1)),
                new Layer(LayerStyle.Softlight(), context => overlayFactory1.CreateAsync(context.BackgroundLayer.ImageSize)),
                new Layer(LayerStyle.Normal(), context => overlayFactory2.CreateAsync(context.BackgroundLayer.ImageSize))
            };
        }
Beispiel #9
0
    //<Custom additional code>
    //Calculates the Depth for each curve on a list of Curves
    private int CalculateDepth(Curve x, List<Curve> y)
    {
        foreach (Curve crv in y)
        {
          crv.SetUserString("D", "nil");
        }

        int depth = 0;

        Queue<Curve> Q = new Queue<Curve>();
        int d = 0;
        x.SetUserString("D", d.ToString());
        Q.Enqueue(x);

        while (Q.Count > 0)
        {
          Curve c = Q.Dequeue();
          int val = Convert.ToInt32(c.GetUserString("D"));
          depth = depth + val;
          Print(depth.ToString());

          List<Curve> connected = FindIntersectingCurves(c, y);
          foreach (Curve crv in connected)
          {
        if (c.GetUserString("D") == "nil")
        {
          d = val + 1;
          crv.SetUserString("D", d.ToString());
          Q.Enqueue(crv);
        }
          }
        }

        return depth;
    }
    /// <summary>
    /// Create a new curve with the same 
    /// geometry in the reverse direction.
    /// </summary>
    /// <param name="orig">The original curve.</param>
    /// <returns>The reversed curve.</returns>
    /// <throws cref="NotImplementedException">If the 
    /// curve type is not supported by this utility.</throws>
    static Curve CreateReversedCurve(
      Autodesk.Revit.Creation.Application creapp,
      Curve orig )
    {
      if( !IsSupported( orig ) )
      {
        throw new NotImplementedException(
          "CreateReversedCurve for type "
          + orig.GetType().Name );
      }

      if( orig is Line )
      {
        return Line.CreateBound( 
          orig.GetEndPoint( 1 ),
          orig.GetEndPoint( 0 ) );
      }
      else if( orig is Arc )
      {
        return Arc.Create( orig.GetEndPoint( 1 ), 
          orig.GetEndPoint( 0 ), 
          orig.Evaluate( 0.5, true ) );
      }
      else
      {
        throw new Exception(
          "CreateReversedCurve - Unreachable" );
      }
    }
Beispiel #11
0
        internal static void AddCurves(ScenarioGeneratorModel context)
        {
            DateTime now = context.AsOfDate;

            var curve1 = new Curve() { StartTime = now.AddDays(-100), EndTime = DateTime.MaxValue, CreatedAt = now, CreatedBy = "A", ApprovedAt = now.AddDays(-100), ApprovedBy = "B", Latest = true };
            var curveDetail1 = new CurveDetail() { Name = "SWAPSOIS", StartTime = now.AddDays(-100), EndTime = DateTime.MaxValue, CreatedAt = now, CreatedBy = "A", ApprovedAt = now.AddDays(-100), ApprovedBy = "B", Latest = true };
            curve1.CurveDetails.Add(curveDetail1);

            var curve2 = new Curve() { StartTime = now.AddDays(-100), EndTime = DateTime.MaxValue, CreatedAt = now, CreatedBy = "A", ApprovedAt = now.AddDays(-100), ApprovedBy = "B", Latest = true };
            var curveDetail2 = new CurveDetail() { Name = "SWAPSOISRISK", StartTime = now.AddDays(-100), EndTime = DateTime.MaxValue, CreatedAt = now, CreatedBy = "A", ApprovedAt = now.AddDays(-100), ApprovedBy = "B", Latest = true };
            curve2.CurveDetails.Add(curveDetail2);

            CurveFamily item = context.CurveFamilies.Where(x => x.Name == "SWAPS").First();

            curveDetail1.CurveFamily = item;
            curveDetail2.CurveFamily = item;

            TargetSystem system = context.TargetSystems.Where(x => x.Name == "Simra").First();
            curveDetail1.TargetSystem = system;
            curveDetail2.TargetSystem = system;

            context.Curves.Add(curve1);
            context.Curves.Add(curve2);

            context.SaveChanges();
        }
        private static async Task<Curve[]> LoadRgbLookupCurves(string path, double outputGain, int outputOffset)
        {
            var storageFile = await Package.Current.InstalledLocation.GetFileAsync(path).AsTask().ConfigureAwait(false);
            using (var storageFileImageSource = new StorageFileImageSource(storageFile))
            using (var renderer = new BitmapRenderer(storageFileImageSource) { OutputOption = OutputOption.PreserveAspectRatio })
            using (var tableBitmap = await renderer.RenderAsync().AsTask().ConfigureAwait(false))
            {
                var redCurve = new Curve();
                var greenCurve = new Curve();
                var blueCurve = new Curve();

                var redValues = new Point[256];
                var greenValues = new Point[256];
                var blueValues = new Point[256];

                var table = tableBitmap.Buffers[0].Buffer.ToArray();
                
                for (int i = 0; i < 256; ++i)
                {
                    redValues[i] = new Point(i,Math.Min(255, Math.Max(0, (int)(table[i * 4 + 2] * outputGain + outputOffset))));
                    greenValues[i] = new Point(i,Math.Min(255, Math.Max(0, (int)(table[i * 4 + 1] * outputGain + outputOffset))));
                    blueValues[i] = new Point(i,Math.Min(255, Math.Max(0, (int)(table[i * 4 + 0] * outputGain + outputOffset))));
                }

                redCurve.Points = redValues;
                greenCurve.Points = greenValues;
                blueCurve.Points = blueValues;

                return new[] { redCurve, greenCurve, blueCurve };
            }
        }
		/// <summary>
		/// Creates an <see cref="ITokenSigner"/> instance which saves public keys to the provided <see cref="IPublicKeyDataProvider"/>
		/// </summary>
		/// <param name="publicKeyDataProvider">The <see cref="IPublicKeyDataProvider"/> for the local service</param>
		/// <param name="curve">The curve to use</param>
		/// <param name="keyLifetime">The max time a private key and its tokens may be used for</param>
		/// <param name="keyRotationPeriod">How often to switch to signing with a new private key. The difference between this and <paramref name="keyLifetime"/> is the maximum token lifetime.</param>
		/// <returns>A new <see cref="ITokenSigner"/></returns>
		public static ITokenSigner Create(
			IPublicKeyDataProvider publicKeyDataProvider,
			Curve curve,
			TimeSpan keyLifetime,
			TimeSpan keyRotationPeriod
		) {
			CngAlgorithm algorithm;
			switch( curve ) {
				case Curve.P521: {
					algorithm = CngAlgorithm.ECDsaP521;
					break;
				}
				case Curve.P384: {
					algorithm = CngAlgorithm.ECDsaP384;
					break;
				}
				case Curve.P256:
				default: {
					algorithm = CngAlgorithm.ECDsaP256;
					break;
				}
			}

			IPrivateKeyProvider privateKeyProvider = EcDsaPrivateKeyProvider
				.Factory
				.Create(
					publicKeyDataProvider,
					keyLifetime,
					keyRotationPeriod,
					algorithm
				);

			var tokenSigner = new TokenSigner( privateKeyProvider );
			return tokenSigner;
		}
        public OldPosterEffect()
        {
            // Curves
            var globalCurve = new Curve(CurveInterpolation.NaturalCubicSpline)
            {
                Points = new[]
                {
                    new Point(0, 0),                  
                    new Point(38, 17),
                    new Point(160, 210),                    
                    new Point(231, 250),
                    new Point(255, 255)                   
                }
            };

            var overlayFactory = new OverlayFactory(
                "ms-appx:///images/Filters_Landscape_Overlay_Poster2.png",
                "ms-appx:///images/Filters_Portrait_Overlay_Poster2.png",
                "ms-appx:///images/Filters_Square_Overlay_Poster2.png");

            LayerList = new LayerList(
                new AdjustmentLayer(LayerStyle.Normal(), new GrayscaleEffect(0.54, 0.64, 0.0, -0.1)),
                new AdjustmentLayer(LayerStyle.Normal(), new CurvesEffect(globalCurve)),
                new Layer(LayerStyle.Multiply(), context => new ColorImageSource(context.BackgroundLayer.ImageSize, Color.FromArgb(255, 255, 167, 151))),
                new Layer(LayerStyle.Normal(), context => overlayFactory.CreateAsync(context.BackgroundLayer.ImageSize))
            );
        }
Beispiel #15
0
        public void Clamp()
        {
            var c = new Curve<float>();
            c.DefaultInterpolator = Interpolators<float>.Linear;
            c[0] = 1.0f;
            c[10] = 2.0f;
            c[20] = 3.0f;
            c[30] = 4.0f;

            c.Clamp(5, 25);

            AssertEqualFloat(1.5f, c[0]);
            AssertEqualFloat(2.0f, c[10]);
            AssertEqualFloat(3.0f, c[20]);
            AssertEqualFloat(3.5f, c[30]);

            c.Clamp(10, 20);

            AssertEqualFloat(2.0f, c[0]);
            AssertEqualFloat(2.0f, c[10]);
            AssertEqualFloat(3.0f, c[20]);
            AssertEqualFloat(3.0f, c[30]);

            c.Clamp(15, 15);

            AssertEqualFloat(2.5f, c[0]);
            AssertEqualFloat(2.5f, c[10]);
            AssertEqualFloat(2.5f, c[20]);
            AssertEqualFloat(2.5f, c[30]);
        }
        public SeaShellEffect()
        {
            m_hueSaturationEffect = new HueSaturationEffect() { Saturation = 0.6 -1 };
            m_vibranceEffect = new VibranceEffect() { Level = .6 };
            m_splitToningEffect = new SplitToneEffect
            {
                ShadowsHue = 230, 
                ShadowsSaturation = 37, 
                HighlightsHue = 50, 
                HighlightsSaturation = 20
            };

            var globalCurve = new Curve(CurveInterpolation.Linear, new[]
            {
                new Point(0, 10),
                new Point(32, 68),
                new Point(64, 119),
                new Point(96, 158),
                new Point(128, 187),
                new Point(160, 209),
                new Point(192, 226),
                new Point(255, 248)                
            });

            var curve = new Curve(CurveInterpolation.Linear, new[]
            {
                new Point(10, 0),
                new Point(32, 27),
                new Point(70, 70)                
            });

            var redCurve = globalCurve;
            var greenCurve = Curve.Compose(curve, globalCurve, null);
            var blueCurve = globalCurve;

            var curvesEffect = new CurvesEffect(redCurve, greenCurve, blueCurve);

            var colorizationLayerList = new LayerList(
					new AdjustmentLayer(LayerStyle.Normal(), new GrayscaleEffect()),
					new Layer(LayerStyle.Multiply(), context => new ColorImageSource(context.HintedRenderSize, Color.FromArgb(0xff, 0xff, 0xe6, 0x99)))
                );

            LayerList.AddRange(
                new AdjustmentLayer(LayerStyle.Normal(0.2), context => colorizationLayerList.ToImageProvider(context.BackgroundImage, context.HintedRenderSize, context.HintedRenderSize)),

                new AdjustmentLayer(LayerStyle.Normal(), new ContrastEffect(-0.15)),
                new AdjustmentLayer(LayerStyle.Normal(), curvesEffect),
                new AdjustmentLayer(LayerStyle.Normal(), m_hueSaturationEffect),
                new AdjustmentLayer(LayerStyle.Normal(), m_vibranceEffect),
                new AdjustmentLayer(LayerStyle.Normal(), m_splitToningEffect)               
           );

            Editors.Add(new RangeEditorViewModel<SeaShellEffect>("SaturationLevel", -1.0, 1.0, this, filter => filter.SaturationLevel, (filter, value) => filter.SaturationLevel = value));
        //    Editors.Add(new RangeEditorViewModel<SeaShellEffect>("ContrastLevel", -1.0, 1.0, this, filter => filter.ContrastLevel, (filter, value) => filter.ContrastLevel = value));
            Editors.Add(new RangeEditorViewModel<SeaShellEffect>("VibranceLevel", 0, 1.0, this, filter => filter.VibranceLevel, (filter, value) => filter.VibranceLevel = value));
			Editors.Add(new RangeEditorViewModel<SeaShellEffect>("ShadowsHue", 0, 365, this, filter => filter.ShadowsHue, (filter, value) => filter.ShadowsHue = (int)value));
			Editors.Add(new RangeEditorViewModel<SeaShellEffect>("ShadowsSaturation", 0, 100, this, filter => filter.ShadowsSaturation, (filter, value) => filter.ShadowsSaturation = (int)value));
			Editors.Add(new RangeEditorViewModel<SeaShellEffect>("HighlightsHue", 0, 365, this, filter => filter.HighlightsHue, (filter, value) => filter.HighlightsHue = (int)value));
			Editors.Add(new RangeEditorViewModel<SeaShellEffect>("HighlightsSaturation", 0, 100, this, filter => filter.HighlightsSaturation, (filter, value) => filter.HighlightsSaturation = (int)value));          
        }
Beispiel #17
0
        public CurveDetail Add(CurveDetail parent)
        {
            // there is no hierarchy so parent can be safely ignored
            CurveDetail detail = new CurveDetail();
            detail.Default(Context.UserName);

            Curve curve = new Curve();
            curve.Default(Context.UserName);

            if (Context.Curves.Local.Count() > 0)
            {
                curve.CurveID = Context.Curves.Local.Max(x => x.CurveID) + 1;
            }
            else
            {
                curve.CurveID = 1;
            }

            detail.Curve = curve;
            detail.CurveID = curve.CurveID;
            detail.Name = "Curve Name";
            Context.Curves.Add(curve);
            Context.CurveDetails.Add(detail);

            return detail;
        }
        public void AddCurve(Curve c)
        {
            curveList.Add(c);

            maxx = 0;
            minx = 0;
            maxy = 0;
            miny = Double.MaxValue;

            foreach (Curve cu in curveList)
            {
                foreach (double a in cu.Data)
                {
                    if (a > maxy)
                        maxy = a;
                    if (a < miny)
                        miny = a;
                }

                if (cu.Data.Length > maxx)
                    maxx = cu.Data.Length;

                maxy = Math.Ceiling(maxy);
            }

            foreach (Curve cu in curveList)
            {
                EnsureCurve(cu);
            }

            panel1.Invalidate();
        }
        public void Map()
        {
            // Arrange
            var start = new DateTime(2010, 1, 1);
            var end = DateUtility.MaxDate;
            var range = new DateRange(start, end);

            var id = new MDM.Contracts.NexusId { SystemName = "Test", Identifier = "A" };
            var contractDetails = new MDM.Contracts.CurveDetails();
            var contract = new MDM.Contracts.Curve
            {
                Identifiers = new MDM.Contracts.NexusIdList { id },
                Details = contractDetails,
                Nexus = new MDM.Contracts.SystemData { StartDate = start, EndDate = end }
            };

            // NB Don't assign validity here, want to prove SUT sets it
            var details = new Curve();

            var mapping = new CurveMapping();

            var mappingEngine = new Mock<IMappingEngine>();
            mappingEngine.Setup(x => x.Map<MDM.Contracts.NexusId, CurveMapping>(id)).Returns(mapping);
            mappingEngine.Setup(x => x.Map<MDM.Contracts.CurveDetails, Curve>(contractDetails)).Returns(details);

            var mapper = new CurveMapper(mappingEngine.Object);

            // Act
            var candidate = mapper.Map(contract);

            // Assert
            //Assert.AreEqual(1, candidate.Details.Count, "Detail count differs");
            Assert.AreEqual(1, candidate.Mappings.Count, "Mapping count differs");
            Check(range, details.Validity, "Validity differs");
        }
        /// <summary>
        /// Return the transformed curve
        /// </summary>
        /// <param name="transformation"></param>
        /// <returns>the transformed curve</returns>
        public ICurve Transform(PlaneTransformation transformation) {
            Curve c = new Curve(segs.Count);
            foreach (ICurve s in segs)
                c.AddSegment(s.Transform(transformation));

            return c;
        }
Beispiel #21
0
 public Curve CreateFCurve()
 {
     Curve fCurve = new Curve(DefaultValue);
     fCurve.AddKeyframe(new Keyframe(1f, 0f));
     fCurve.AddKeyframe(new Keyframe(6f, 10f));
     return fCurve;
 }
        public PopEffect()
        {
            var globalCurve = new Curve(CurveInterpolation.NaturalCubicSpline)
            {
                Points = new[]
                {
                    new Point(0, 0),
                    new Point(68, 60),                    
                    new Point(144, 163),                    
                    new Point(255, 255),            
                }
            };

            var overlayFactory = new OverlayFactory(
                "ms-appx:///images/Filters_Landscape_Overlay_Pop3.png",
                "ms-appx:///images/Filters_Portrait_Overlay_Pop3.png",
                "ms-appx:///images/Filters_Square_Overlay_Pop3.png");

            LayerList = new LayerList()
            {
                new AdjustmentLayer(LayerStyle.Normal(), new ContrastEffect(1.0)),
                new AdjustmentLayer(LayerStyle.Normal(),  new CurvesEffect(globalCurve)),
                new AdjustmentLayer(LayerStyle.Normal(), new GrayscaleEffect(0.54, 0.64, 0.0, -0.1)),
                new AdjustmentLayer(LayerStyle.Normal(), new LevelsEffect(0.7, 0.7 / 2, 0)),
                new Layer(LayerStyle.Screen(1.0), context => new ColorImageSource(context.HintedRenderSize, Color.FromArgb(255, 108, 0, 148))),
                new Layer(LayerStyle.Lighten(), context => overlayFactory.CreateAsync(context.HintedRenderSize))
            };
        }
	void OnDrawGizmosSelected()
	{
		if(start == null || end == null)
		{
			return;
		}

		Vector3 s = start.transform.position, e = end.transform.position;

		Gizmos.color = new Color(1f, 1f, 1f, 1f);
		Gizmos.DrawLine(s, s + a);
		Gizmos.DrawLine(e, e + b);

		Curve curve = new Curve(s, s + a, e + b, e);
		float lenght = curve.lenght;

		CurveData ccd = curve.getDataAt(0f);
		CurveData ncd;

		Gizmos.color = new Color(1f, 0.3f, 0.3f, 1f);
		for(int i = 0; i < 20; i++)
		{
			ncd = curve.getDataAt((i / 20f) * lenght);
			Gizmos.DrawLine(ccd.pos, ncd.pos);
			ccd = ncd;
		}

		Gizmos.DrawLine(ccd.pos, e);
	}
Beispiel #24
0
 public override Widget ConfigurationWidget()
 {
     VBox h = new VBox ();
     r = new HScale (0, 100, 1);
     r.ModifyBg (StateType.Selected, new Color (0xff, 0, 0));
     r.Value = 80;
     r.ValueChanged += SettingsChanged;
     h.Add (r);
     g = new HScale (0, 100, 1);
     g.ModifyBg (StateType.Selected, new Color (0, 0xff, 0));
     g.Value = 10;
     g.ValueChanged += SettingsChanged;
     h.Add (g);
     b = new HScale (0, 100, 1);
     b.ModifyBg (StateType.Selected, new Color (0, 0, 0xff));
     b.Value = 10;
     b.ValueChanged += SettingsChanged;
     h.Add (b);
     c = new Curve ();
     c.CurveType = CurveType.Spline;
     c.SetRange (0, 255, 0, 255);
     h.Add (c);
     Button btn = new Button (Gtk.Stock.Refresh);
     btn.Clicked += delegate {UpdatePreview ();};
     h.Add (btn);
     return h;
 }
            public LineSource(Curve SrcPath, String Code, int el_m, int SrcID, Phase_Regime ph)
                : base(new double[8]{60, 49, 41, 35, 31, 28, 26, 24}, new Point3d(0,0,0), ph, SrcID)
            {
                string type = SrcPath.GetUserString("SourceType");
                string v = SrcPath.GetUserString("Velocity");
                double velocity = double.Parse(v);
                double delta = double.Parse(SrcPath.GetUserString("delta"));

                if (type == "Aircraft (ANCON derived)")
                {
                    D = new ANCON(delta, velocity);
                }
                else D = new Simple();

                samplespermeter = el_m;
                Curve = SrcPath;

                //Divide curve up in ~equal length segments.
                Samples = Curve.DivideEquidistant(1.0 / (double)samplespermeter);

                Level = Utilities.PachTools.DecodeSourcePower(Code);
                Power = new double[8];

                double PowerMod = Curve.GetLength() / (double)Samples.Length;
                for (int oct = 0; oct < 8; oct++) Power[oct] = 1E-12 * Math.Pow(10, .1 * Level[oct]) * PowerMod;
            }
    // Use this for initialization
    void Start()
    {
        curve = new Curve();

        graphics = new Graphics();
        graphics.verticesDrawer = verticesDrawer;
    }
Beispiel #27
0
		public TransformedCurve(Curve curve, Vector2 offset, float size, float rotation, Vector2 rotationCenter, bool reversed = false) {
			this.curve = curve;
			this.offset = offset;
			this.size = size;
			this.rotation = rotation;
			this.rotationCenter = rotationCenter;
			this.reversed = reversed;
		}
Beispiel #28
0
 public void CanGetLineIntersectionsInf()
 {
     var line1 = new Curve(new Point(0, 0), new Point(1, 1));
     var line2 = new Curve(new Point(4, 0), new Point(3, 1));
     var intersection = (Point)line1.FindIntersectionInf(line2);
     Assert.That(intersection.X, Is.EqualTo(2));
     Assert.That(intersection.Y, Is.EqualTo(2));
 }
Beispiel #29
0
 public void CanGetLineLength()
 {
     var line = new Curve(new Point(3, 4), new Point(7, 7));
     var len = line.Length;
     var cachedLen = line.Length;
     Assert.AreEqual(len, 5.0);
     Assert.AreEqual(cachedLen, 5.0);
 }
        /// <summary>
        /// Returns the curved scaled by x and y
        /// </summary>
        /// <param name="xScale"></param>
        /// <param name="yScale"></param>
        /// <returns></returns>     
        public ICurve ScaleFromOrigin(double xScale, double yScale)
        {
            Curve c = new Curve(segs.Count);
            foreach (ICurve s in segs)
                c.AddSegment(s.ScaleFromOrigin(xScale, yScale));

            return c;
        }
        private void StartBtnClick(object sender, RoutedEventArgs e)
        {
            if (_batchEmulation != null)
            {
                _batchEmulation.Resume();
                return;
            }

            if (HistoryPath.Folder.IsEmpty() || !Directory.Exists(HistoryPath.Folder))
            {
                MessageBox.Show(this, LocalizedStrings.Str3014);
                return;
            }

            TestingProcess.Value = 0;
            Curve.Clear();
            Stat.Clear();

            var logManager      = new LogManager();
            var fileLogListener = new FileLogListener("sample.log");

            logManager.Listeners.Add(fileLogListener);

            // SMA periods
            var periods = new List <Tuple <int, int, Color> >();

            for (var l = 100; l >= 50; l -= 10)
            {
                for (var s = 10; s >= 5; s -= 1)
                {
                    periods.Add(Tuple.Create(l, s, Color.FromRgb((byte)RandomGen.GetInt(255), (byte)RandomGen.GetInt(255), (byte)RandomGen.GetInt(255))));
                }
            }

            // storage to historical data
            var storageRegistry = new StorageRegistry
            {
                // set historical path
                DefaultDrive = new LocalMarketDataDrive(HistoryPath.Folder)
            };

            var timeFrame = TimeSpan.FromMinutes(1);

            // create test security
            var security = new Security
            {
                Id    = "SBER@TQBR",              // sec id has the same name as folder with historical data
                Code  = "SBER",
                Name  = "SBER",
                Board = ExchangeBoard.Micex,
            };

            var startTime = new DateTime(2020, 4, 1);
            var stopTime  = new DateTime(2020, 4, 20);

            var level1Info = new Level1ChangeMessage
            {
                SecurityId = security.ToSecurityId(),
                ServerTime = startTime,
            }
            .TryAdd(Level1Fields.PriceStep, 0.01m)
            .TryAdd(Level1Fields.StepPrice, 0.01m)
            .TryAdd(Level1Fields.MinPrice, 0.01m)
            .TryAdd(Level1Fields.MaxPrice, 1000000m)
            .TryAdd(Level1Fields.MarginBuy, 10000m)
            .TryAdd(Level1Fields.MarginSell, 10000m);

            // test portfolio
            var portfolio = Portfolio.CreateSimulator();

            // create backtesting connector
            _batchEmulation = new BatchEmulation(new[] { security }, new[] { portfolio }, storageRegistry)
            {
                EmulationSettings =
                {
                    MarketTimeChangedInterval = timeFrame,
                    StartTime = startTime,
                    StopTime  = stopTime,

                    // count of parallel testing strategies
                    // if not set, then CPU count * 2
                    //BatchSize = 3,
                }
            };

            // handle historical time for update ProgressBar
            _batchEmulation.ProgressChanged += (connector, single, total) => this.GuiAsync(() => TestingProcess.Value = total);

            _batchEmulation.StateChanged += (oldState, newState) =>
            {
                var isFinished = _batchEmulation.IsFinished;

                if (_batchEmulation.State == ChannelStates.Stopped)
                {
                    _batchEmulation = null;
                }

                this.GuiAsync(() =>
                {
                    switch (newState)
                    {
                    case ChannelStates.Stopping:
                    case ChannelStates.Starting:
                    case ChannelStates.Suspending:
                        SetIsEnabled(false, false, false);
                        break;

                    case ChannelStates.Stopped:
                        SetIsEnabled(true, false, false);

                        if (isFinished)
                        {
                            TestingProcess.Value = TestingProcess.Maximum;
                            MessageBox.Show(this, LocalizedStrings.Str3024.Put(DateTime.Now - _startEmulationTime));
                        }
                        else
                        {
                            MessageBox.Show(this, LocalizedStrings.cancelled);
                        }

                        break;

                    case ChannelStates.Started:
                        SetIsEnabled(false, true, true);
                        break;

                    case ChannelStates.Suspended:
                        SetIsEnabled(true, false, true);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(newState.ToString());
                    }
                });
            };

            _startEmulationTime = DateTime.Now;

            var strategies = periods
                             .Select(period =>
            {
                var series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame);

                // create strategy based SMA
                var strategy = new SampleHistoryTesting.SmaStrategy(series, new SimpleMovingAverage {
                    Length = period.Item1
                }, new SimpleMovingAverage {
                    Length = period.Item2
                }, null, null, null, null, null)
                {
                    Volume    = 1,
                    Security  = security,
                    Portfolio = portfolio,
                    //Connector = connector,

                    // by default interval is 1 min,
                    // it is excessively for time range with several months
                    UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To <TimeSpan>()
                };

                this.GuiSync(() =>
                {
                    var curveElem = Curve.CreateCurve(LocalizedStrings.Str3026Params.Put(period.Item1, period.Item2), period.Item3, ChartIndicatorDrawStyles.Line);

                    strategy.PnLChanged += () =>
                    {
                        var data = new ChartDrawData();

                        data
                        .Group(strategy.CurrentTime)
                        .Add(curveElem, strategy.PnL);

                        Curve.Draw(data);
                    };

                    Stat.AddStrategies(new[] { strategy });
                });

                return(strategy);
            });

            // start emulation
            _batchEmulation.Start(strategies, periods.Count);
        }
Beispiel #32
0
 public static Curve Average(Curve a, Curve b) => t => (a(t) + b(t)) / 2;
Beispiel #33
0
        public Brep buildHelicalRack(Line L, double M, double Teeth, double Angle, double HAngle, double H, double addendum, double dedendum)
        {
            double Pitch = Math.PI * M;
            int    time  = (int)(L.Length / Pitch);

            Vector3d dir  = L.Direction; dir.Unitize();
            Vector3d dirA = dir;

            dirA.Rotate(toRadian(90.0 - Angle), Vector3d.ZAxis);
            Vector3d dirB = dir;

            dirB.Rotate(toRadian(-90.0 + Angle), Vector3d.ZAxis);

            addendum = addendum * M;
            dedendum = dedendum * M;

            double slope  = (addendum + dedendum) / Math.Cos(toRadian(Angle));
            double tip    = (Pitch * 0.5) - Math.Tan(Angle) * addendum * 2;
            double buttom = (Pitch * 0.5) - Math.Tan(Angle) * dedendum;

            List <Curve> profiles = new List <Curve>();

            profiles.Add(new LineCurve(new Line(L.From, dirA * slope)));
            profiles.Add(new LineCurve(new Line(profiles[0].PointAtEnd, dir * tip)));
            profiles.Add(new LineCurve(new Line(profiles[1].PointAtEnd, dirB * slope)));
            profiles.Add(new LineCurve(new Line(profiles[2].PointAtEnd, dir * buttom)));

            Transform move = Transform.Translation(Vector3d.CrossProduct(dir, Vector3d.ZAxis) * dedendum);
            Curve     rack = Curve.JoinCurves(profiles, 0.01, true)[0];

            rack.Transform(move);

            //Display
            locations.Add(rack.PointAtNormalizedLength(0.5));
            texts.Add(Math.Round(tip, 2).ToString());
            sizes.Add(Pitch * 4);

            List <Curve> racks = new List <Curve>();

            for (int i = 0; i < time + 1; i++)
            {
                Transform duplicate = Transform.Translation(dir * Pitch * i);
                Curve     thisC     = rack.DuplicateCurve();
                thisC.Transform(duplicate);
                racks.Add(thisC);
            }

            //build helical
            double    hShift = H / (Math.Tan(toRadian(90.0 - HAngle)) * 2 * Math.PI); //helical shift
            double    hTime  = Math.Ceiling(hShift / Pitch);
            Transform shift  = Transform.Translation(dir * hShift);
            Transform zH     = Transform.Translation(Vector3d.ZAxis * H);

            List <Curve> helicals = new List <Curve>();

            if (hTime / Math.Abs(hTime) == 1)
            {
                for (int i = -1; i < time; i++)
                {
                    Transform duplicate = Transform.Translation(dir * Pitch * i);
                    Curve     thisC     = rack.DuplicateCurve();
                    thisC.Transform(duplicate);
                    helicals.Add(thisC);
                }
            }
            else
            {
                for (int i = 0; i < time + 1; i++)
                {
                    Transform duplicate = Transform.Translation(dir * Pitch * i);
                    Curve     thisC     = rack.DuplicateCurve();
                    thisC.Transform(duplicate);
                    helicals.Add(thisC);
                }
            }


            Curve helical = Curve.JoinCurves(helicals, 1, true)[0];

            rack = Curve.JoinCurves(racks, 1, true)[0];
            helical.Transform(shift);
            helical.Transform(zH);

            List <Curve> sections = new List <Curve> {
                rack, helical
            };
            Brep profile = Brep.CreateFromLoft(sections, Point3d.Unset, Point3d.Unset, LoftType.Normal, false)[0];

            return(profile);
        }
        /// <summary>
        /// Creates a facetation of a simple swept solid from a list of curve loops.
        /// </summary>
        /// <param name="exporterIFC">The exporter.</param>
        /// <param name="profileName">The profile name.</param>
        /// <param name="profileCurveLoops">The profile curve loops.</param>
        /// <param name="normal">The normal of the plane that the path lies on.</param>
        /// <param name="directrix">The path curve.</param>
        /// <returns>The list of facet handles.</returns>
        public static HashSet <IFCAnyHandle> CreateSimpleSweptSolidAsBRep(ExporterIFC exporterIFC, string profileName, IList <CurveLoop> profileCurveLoops,
                                                                          XYZ normal, Curve directrix)
        {
            // see definition of IfcSurfaceCurveSweptAreaSolid from
            // http://www.buildingsmart-tech.org/ifc/IFC2x4/rc4/html/schema/ifcgeometricmodelresource/lexical/ifcsurfacecurvesweptareasolid.htm

            HashSet <IFCAnyHandle> facetHnds = null;

            if (!CanCreateSimpleSweptSolid(profileCurveLoops, normal, directrix))
            {
                return(facetHnds);
            }

            // An extra requirement, as we can't tessellate an unbound curve.
            if (!directrix.IsBound)
            {
                return(facetHnds);
            }
            double originalStartParam = directrix.GetEndParameter(0);

            Plane axisPlane, profilePlane;

            CreateAxisAndProfileCurvePlanes(directrix, originalStartParam, out axisPlane, out profilePlane);

            IList <CurveLoop> curveLoops = null;

            try
            {
                // Check that curve loops are valid.
                curveLoops = ExporterIFCUtils.ValidateCurveLoops(profileCurveLoops, profilePlane.Normal);
            }
            catch (Exception)
            {
                return(null);
            }

            if (curveLoops == null || curveLoops.Count == 0)
            {
                return(facetHnds);
            }

            // Tessellate the curve loops.  We don't add the last point, as these should all be closed curves.
            IList <IList <XYZ> > tessellatedOutline = new List <IList <XYZ> >();

            foreach (CurveLoop curveLoop in curveLoops)
            {
                List <XYZ> tessellatedCurve = new List <XYZ>();
                foreach (Curve curve in curveLoop)
                {
                    if (curve is Line)
                    {
                        AddScaledPointToList(exporterIFC, tessellatedCurve, curve.GetEndPoint(0));
                    }
                    else
                    {
                        IList <XYZ> curveTessellation = CreateRoughTessellation(exporterIFC, curve);
                        tessellatedCurve.AddRange(curveTessellation);
                    }
                }

                if (tessellatedCurve.Count != 0)
                {
                    tessellatedOutline.Add(tessellatedCurve);
                }
            }

            IFCFile file = exporterIFC.GetFile();

            IList <IList <IList <IFCAnyHandle> > > facetVertexHandles = new List <IList <IList <IFCAnyHandle> > >();

            IList <IList <IFCAnyHandle> > tessellatedOutlineHandles = new List <IList <IFCAnyHandle> >();

            foreach (IList <XYZ> tessellatedOutlinePolygon in tessellatedOutline)
            {
                IList <IFCAnyHandle> tessellatedOutlinePolygonHandles = new List <IFCAnyHandle>();
                foreach (XYZ tessellatedOutlineXYZ in tessellatedOutlinePolygon)
                {
                    tessellatedOutlinePolygonHandles.Add(ExporterUtil.CreateCartesianPoint(file, tessellatedOutlineXYZ));
                }
                tessellatedOutlineHandles.Add(tessellatedOutlinePolygonHandles);
            }
            facetVertexHandles.Add(tessellatedOutlineHandles);

            // Tessellate the Directrix.  This only works for bound Directrix curves. Unfortunately, we get XYZ values, which we will have to convert
            // back to parameter values to get the local transform.
            IList <double> tessellatedDirectrixParameters = CreateRoughParametricTessellation(directrix);

            // Create all of the other outlines by transformng the first tessellated outline to the current transform.
            Transform profilePlaneTrf = Transform.CreateTranslation(ExporterIFCUtils.TransformAndScalePoint(exporterIFC, profilePlane.Origin));

            profilePlaneTrf.BasisX = ExporterIFCUtils.TransformAndScaleVector(exporterIFC, profilePlane.XVec);
            profilePlaneTrf.BasisY = ExporterIFCUtils.TransformAndScaleVector(exporterIFC, profilePlane.YVec);
            profilePlaneTrf.BasisZ = ExporterIFCUtils.TransformAndScaleVector(exporterIFC, profilePlane.Normal);

            // The inverse transform will be applied to generate the delta transform for the profile curves from the start of the directrix
            // to the current location.  This could be optimized in the case of a Line, but current usage is really only for a single arc.
            // If that changes, we should revisit optimization possibilities.
            Transform profilePlaneTrfInverse = profilePlaneTrf.Inverse;

            // Create the delta transforms and the offset tessellated profiles.
            foreach (double parameter in tessellatedDirectrixParameters)
            {
                Transform directrixDirs  = CreateProfileCurveTransform(exporterIFC, directrix, parameter);
                Transform deltaTransform = directrixDirs.Multiply(profilePlaneTrfInverse);

                IList <IList <IFCAnyHandle> > currTessellatedOutline = new List <IList <IFCAnyHandle> >();
                foreach (IList <XYZ> pointLoop in tessellatedOutline)
                {
                    IList <IFCAnyHandle> currTessellatedPoinLoop = new List <IFCAnyHandle>();
                    foreach (XYZ point in pointLoop)
                    {
                        XYZ          transformedPoint       = deltaTransform.OfPoint(point);
                        IFCAnyHandle transformedPointHandle = ExporterUtil.CreateCartesianPoint(file, transformedPoint);
                        currTessellatedPoinLoop.Add(transformedPointHandle);
                    }
                    currTessellatedOutline.Add(currTessellatedPoinLoop);
                }
                facetVertexHandles.Add(currTessellatedOutline);
            }

            // Create the side facets.
            facetHnds = new HashSet <IFCAnyHandle>();

            int numFacets = facetVertexHandles.Count - 1;

            for (int ii = 0; ii < numFacets; ii++)
            {
                IList <IList <IFCAnyHandle> > firstOutline  = facetVertexHandles[ii];
                IList <IList <IFCAnyHandle> > secondOutline = facetVertexHandles[ii + 1];

                int numLoops = firstOutline.Count;
                for (int jj = 0; jj < numLoops; jj++)
                {
                    IList <IFCAnyHandle> firstLoop  = firstOutline[jj];
                    IList <IFCAnyHandle> secondLoop = secondOutline[jj];

                    int numVertices = firstLoop.Count;

                    for (int kk = 0; kk < numVertices; kk++)
                    {
                        IList <IFCAnyHandle> polyLoopHandles = new List <IFCAnyHandle>(4);
                        polyLoopHandles.Add(secondLoop[kk]);
                        polyLoopHandles.Add(secondLoop[(kk + 1) % numVertices]);
                        polyLoopHandles.Add(firstLoop[(kk + 1) % numVertices]);
                        polyLoopHandles.Add(firstLoop[kk]);

                        IFCAnyHandle face = BodyExporter.CreateFaceFromVertexList(file, polyLoopHandles);
                        facetHnds.Add(face);
                    }
                }
            }

            // Create the end facets.
            for (int ii = 0; ii < 2; ii++)
            {
                int faceIndex = (ii == 0) ? 0 : facetVertexHandles.Count - 1;

                int numLoops = facetVertexHandles[faceIndex].Count;
                HashSet <IFCAnyHandle> faceBounds = new HashSet <IFCAnyHandle>();

                for (int jj = 0; jj < numLoops; jj++)
                {
                    IList <IFCAnyHandle> polyLoopHandles = null;
                    if (ii == 0)
                    {
                        polyLoopHandles = facetVertexHandles[faceIndex][jj];
                    }
                    else
                    {
                        int numHandles = facetVertexHandles[faceIndex][jj].Count;
                        polyLoopHandles = new List <IFCAnyHandle>(numHandles);
                        for (int kk = numHandles - 1; kk >= 0; kk--)
                        {
                            polyLoopHandles.Add(facetVertexHandles[faceIndex][jj][kk]);
                        }
                    }

                    IFCAnyHandle polyLoop  = IFCInstanceExporter.CreatePolyLoop(file, polyLoopHandles);
                    IFCAnyHandle faceBound = (jj == 0) ?
                                             IFCInstanceExporter.CreateFaceOuterBound(file, polyLoop, true) :
                                             IFCInstanceExporter.CreateFaceBound(file, polyLoop, true);
                    faceBounds.Add(faceBound);
                }

                IFCAnyHandle face = IFCInstanceExporter.CreateFace(file, faceBounds);
                facetHnds.Add(face);
            }

            return(facetHnds);
        }
        void Frame(Point3d pt, bool isBackSyntax, DataTree <Point3d> iAnchors)
        {
            //  Find closest point from anchor list
            Point3d closestPoint = new Point3d();
            double  distancePt   = double.MaxValue;

            for (int i = 0; i < iAnchors.BranchCount; i++)
            {
                foreach (Point3d anchorPt in iAnchors.Branch(i))
                {
                    double tempDist = anchorPt.DistanceTo(pt);
                    if (tempDist < distancePt)
                    {
                        distancePt   = tempDist;
                        closestPoint = anchorPt;
                    }
                }
            }


            //  Find Plane Based on Surface
            double u1;
            double v1;

            srf.ClosestPoint(closestPoint, out u1, out v1);
            srf.FrameAt(u1, v1, out basePlane);
            basePlane.Origin = closestPoint;


            //  Extract Edges
            List <Curve> surfaceEdges = new List <Curve>();
            Brep         srfBrep      = srf.ToBrep();

            surfaceEdges.AddRange(srfBrep.Curves3D);

            //  Find which Edge point is on
            double minDistance = double.MaxValue;
            double tFinal      = 0;

            for (var i = 0; i < surfaceEdges.Count; i++)
            {
                Curve crv = surfaceEdges[i];
                crv.Domain = new Interval(0, 1);
                double t;
                crv.ClosestPoint(pt, out t);
                double distance = pt.DistanceTo(crv.PointAt(t));
                if (distance < minDistance)
                {
                    edgeIndex   = i;
                    minDistance = distance;
                    tFinal      = t;
                }
            }

            //  Determine whether Frame lies on corner condition

            if (edgeIndex == 1 && tFinal > 0.99)
            {
                edgeIndex = 2;
            }
            else if (edgeIndex == 1 && tFinal < 0.01)
            {
                edgeIndex = 0;
            }
            else if (edgeIndex == 3 && tFinal > 0.99)
            {
                edgeIndex = 0;
            }
            else if (edgeIndex == 3 && tFinal < 0.01)
            {
                edgeIndex = 2;
            }



            //  Save location of plane on edge, and edge geometry
            surfaceEdges[edgeIndex].Domain = new Interval(0, 1);
            surfaceEdges[edgeIndex].ClosestPoint(basePlane.Origin, out edgeParam);
            edgeCurve = surfaceEdges[edgeIndex].ToNurbsCurve();

            //  Create IsoCurve for Debugging
            if (edgeIndex == 0 || edgeIndex == 2)
            {
                iso = srf.IsoCurve(1, u1);
            }
            else
            {
                iso = srf.IsoCurve(0, v1);
            }

            // Orient Base Plane to IsoCurve
            //double param;
            //iso.ClosestPoint(pt, out param);
            //double paramAdd = 0.01 + param;
            //// find closest vector of iso curve
            //Point3d iso_pt1 = iso.PointAt(paramAdd);
            //Vector3d vectPts = pt - iso_pt1;
            ////Determine the angle between plane and vector for correction
            //double angles = Vector3d.VectorAngle(basePlane.YAxis, vectPts);
            //basePlane.Rotate(angles, basePlane.ZAxis);
            //// Flip it if its pointing out
            //if (edgeIndex == 3 || edgeIndex == 0)
            //{
            //    basePlane.Rotate(RhinoMath.ToRadians(180), basePlane.ZAxis);
            //}
        }
Beispiel #36
0
 /// <summary>Modify the current fade to use the specified `curve` to calculate the weight.</summary>
 /// <example>See <see cref="CustomFade"/>.</example>
 /// <remarks>The `curve` should follow the <see cref="OptionalWarning.CustomFadeBounds"/> guideline.</remarks>
 public static void Apply(AnimancerState state, AnimationCurve curve)
 => Curve.Acquire(curve).Apply(state);
Beispiel #37
0
        public List <Curve> buildGear(List <Circle> C, double Teeth, double Angle, double profileShift, double addendum, double dedendum, out List <int> teethNumber)
        {
            List <Curve> curves = new List <Curve>();
            ArcCurve     sC     = new ArcCurve(C[0]);

            if (C.Count > 1)
            {
                sC = smallestCircle(C);
            }

            double m = (2 * sC.Radius) / Teeth;

            addendum = addendum * m;
            dedendum = dedendum * m;

            teethNumber = new List <int>();
            for (int i = 0; i < C.Count; i++)
            {
                List <Curve> profiles = new List <Curve>();
                Circle       baseCir  = new Circle(C[i].Plane, C[i].Radius * Math.Cos(toRadian(Angle)));
                Circle       addCir   = new Circle(C[i].Plane, C[i].Radius + addendum);
                Circle       dedCir   = new Circle(C[i].Plane, C[i].Radius - dedendum);
                Curve        profile  = involute(baseCir, Angle, addCir, dedCir);

                int teethCount = (int)(Teeth * (C[i].Radius / sC.Radius)); // teeth number
                teethNumber.Add(teethCount);
                //mirror profile
                Vector3d newX = C[i].Plane.XAxis;
                //the thickness of gear, should be halt of pitch angle
                if (profileShift != 0)
                {
                    newX.Rotate((Math.PI + profileShift * Math.PI * Math.Tan(Angle)) / (double)teethCount, C[i].Normal); //circular pitch
                }
                else
                {
                    newX.Rotate(Math.PI / teethCount, C[i].Normal);
                }
                Curve     mirProfile = profile.DuplicateCurve();
                Transform mirror     = Transform.Mirror(new Plane(C[i].Center, newX + C[i].Plane.XAxis, C[i].Normal));
                mirProfile.Transform(mirror);

                //align the profile
                var       ccx     = Rhino.Geometry.Intersect.Intersection.CurveCurve(profile, new ArcCurve(C[i]), 1, 1);
                Transform aligned = Transform.Rotation(ccx[0].PointA - C[i].Center, C[i].Plane.XAxis, C[i].Center);
                profile.Transform(aligned);
                mirProfile.Transform(aligned);

                //tip and buttom arc
                double   addAngle = Vector3d.VectorAngle(profile.PointAtEnd - C[i].Center, mirProfile.PointAtEnd - C[i].Center);
                double   dedAngle = (1.0 / (double)teethCount) * Math.PI * 2 - Vector3d.VectorAngle(profile.PointAtStart - C[i].Center, mirProfile.PointAtStart - C[i].Center);
                Plane    addPln   = new Plane(C[i].Center, profile.PointAtEnd - C[i].Center, C[i].Plane.YAxis);
                Plane    dedPln   = new Plane(C[i].Center, mirProfile.PointAtStart - C[i].Center, C[i].Plane.YAxis);
                ArcCurve tip      = new ArcCurve(new Arc(addPln, C[i].Radius + addendum, addAngle));
                ArcCurve buttom   = new ArcCurve(new Arc(dedPln, C[i].Radius - dedendum, dedAngle));

                //display
                locations.Add(tip.PointAtNormalizedLength(0.5)); //tip
                texts.Add(Math.Round(tip.GetLength(), 2).ToString());
                sizes.Add((addendum + dedendum) * 4);
                locations.Add(profile.PointAtStart); //profile
                texts.Add(Math.Round(profile.GetLength(), 2).ToString());
                sizes.Add((addendum + dedendum) * 4);

                //teeth
                mirProfile.Reverse();
                List <Curve> CS = new List <Curve> {
                    profile, tip, mirProfile, buttom
                };
                Curve teethC = Curve.JoinCurves(CS, 0.1, true)[0];
                for (int j = 0; j < teethCount; j++)
                {
                    Curve     presentProfile = teethC.DuplicateCurve();
                    double    step           = ((double)j / (double)teethCount) * Math.PI * 2;
                    Transform rotate         = Transform.Rotation(step, C[i].Normal, C[i].Center);
                    presentProfile.Transform(rotate);

                    profiles.Add(presentProfile);
                }

                curves.Add(Curve.JoinCurves(profiles, 0.01, true)[0]);
            }
            return(curves);
        }
        private static bool CanCreateSimpleSweptSolid(IList <CurveLoop> profileCurveLoops, XYZ normal, Curve directrix)
        {
            if (directrix == null || normal == null || profileCurveLoops == null || profileCurveLoops.Count == 0)
            {
                return(false);
            }

            if (directrix is Arc)
            {
                return(true);
            }

            // We don't handle unbound lines, or curves other than lines or arcs.  We'll extend to other curve types later.
            if (!(directrix is Line) || !directrix.IsBound)
            {
                return(false);
            }

            // All of the profileCurveLoops should be closed.
            foreach (CurveLoop profileCurveLoop in profileCurveLoops)
            {
                if (profileCurveLoop.IsOpen())
                {
                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        /// Creates a simple swept solid from a list of curve loops.
        /// </summary>
        /// <param name="exporterIFC">The exporter.</param>
        /// <param name="profileName">The profile name.</param>
        /// <param name="profileCurveLoops">The profile curve loops.</param>
        /// <param name="normal">The normal of the plane that the path lies on.</param>
        /// <param name="directrix">The path curve.</param>
        /// <returns>The swept solid handle.</returns>
        public static IFCAnyHandle CreateSimpleSweptSolid(ExporterIFC exporterIFC, string profileName, IList <CurveLoop> profileCurveLoops,
                                                          XYZ normal, Curve directrix)
        {
            // see definition of IfcSurfaceCurveSweptAreaSolid from
            // http://www.buildingsmart-tech.org/ifc/IFC2x4/rc4/html/schema/ifcgeometricmodelresource/lexical/ifcsurfacecurvesweptareasolid.htm

            IFCAnyHandle simpleSweptSolidHnd = null;

            if (!CanCreateSimpleSweptSolid(profileCurveLoops, normal, directrix))
            {
                return(simpleSweptSolidHnd);
            }

            bool   isBound            = directrix.IsBound;
            double originalStartParam = isBound ? directrix.GetEndParameter(0) : 0.0;

            Plane axisPlane, profilePlane;

            CreateAxisAndProfileCurvePlanes(directrix, originalStartParam, out axisPlane, out profilePlane);

            IList <CurveLoop> curveLoops = null;

            try
            {
                // Check that curve loops are valid.
                curveLoops = ExporterIFCUtils.ValidateCurveLoops(profileCurveLoops, profilePlane.Normal);
            }
            catch (Exception)
            {
                return(null);
            }

            if (curveLoops == null || curveLoops.Count == 0)
            {
                return(simpleSweptSolidHnd);
            }

            double startParam = 0.0, endParam = 1.0;

            if (directrix is Arc)
            {
                // This effectively resets the start parameter to 0.0, and end parameter = length of curve.
                if (isBound)
                {
                    endParam = UnitUtil.ScaleAngle(MathUtil.PutInRange(directrix.GetEndParameter(1), Math.PI, 2 * Math.PI) -
                                                   MathUtil.PutInRange(originalStartParam, Math.PI, 2 * Math.PI));
                }
                else
                {
                    endParam = 2.0 * Math.PI;
                }
            }

            // Start creating IFC entities.

            IFCAnyHandle sweptArea = ExtrusionExporter.CreateSweptArea(exporterIFC, profileName, curveLoops, profilePlane, profilePlane.Normal);

            if (IFCAnyHandleUtil.IsNullOrHasNoValue(sweptArea))
            {
                return(simpleSweptSolidHnd);
            }

            IFCAnyHandle curveHandle            = null;
            IFCAnyHandle referenceSurfaceHandle = ExtrusionExporter.CreateSurfaceOfLinearExtrusionFromCurve(exporterIFC, directrix, axisPlane, 1.0, 1.0,
                                                                                                            out curveHandle);

            // Should this be moved up?  Check.
            Plane scaledAxisPlane = GeometryUtil.GetScaledPlane(exporterIFC, axisPlane);

            IFCFile file = exporterIFC.GetFile();

            IFCAnyHandle solidAxis = ExporterUtil.CreateAxis(file, scaledAxisPlane.Origin, scaledAxisPlane.Normal, scaledAxisPlane.XVec);

            simpleSweptSolidHnd = IFCInstanceExporter.CreateSurfaceCurveSweptAreaSolid(file, sweptArea, solidAxis, curveHandle, startParam,
                                                                                       endParam, referenceSurfaceHandle);
            return(simpleSweptSolidHnd);
        }
Beispiel #40
0
 ///<summary>
 ///</summary>
 ///<param name="a"></param>
 ///<param name="b"></param>
 ///<returns>true if a is inside b</returns>
 static bool CurveInsideOther(ICurve a, ICurve b)
 {
     return(b.BoundingBox.Contains(a.BoundingBox) && TestPoints(a).All(p => Curve.PointRelativeToCurveLocation(p, b) != PointLocation.Outside));
 }
Beispiel #41
0
        public Brep buildHelicalRack(Line L, Circle C, double Teeth, double Angle, double HAngle, double H, double addendum, double dedendum)
        {
            double M     = (2 * C.Radius) / Teeth;
            double Pitch = Math.PI * M;
            int    time  = (int)(L.Length / Pitch);

            Vector3d dir  = L.Direction; dir.Unitize();
            Vector3d dirA = dir;

            dirA.Rotate(toRadian(90.0 - Angle), C.Normal);
            Vector3d dirB = dir;

            dirB.Rotate(toRadian(-90.0 + Angle), C.Normal);

            addendum = addendum * M;
            dedendum = dedendum * M;

            double slope  = (addendum + dedendum) / Math.Cos(toRadian(Angle));
            double tip    = (Pitch * 0.50) - Math.Tan(Angle) * addendum * 2.0;
            double buttom = (Pitch * 0.5) - Math.Tan(Angle) * dedendum;

            List <Curve> profiles = new List <Curve>();

            profiles.Add(new LineCurve(new Line(L.From, dir * buttom * 0.5)));
            profiles.Add(new LineCurve(new Line(profiles[0].PointAtEnd, dirA * slope)));
            profiles.Add(new LineCurve(new Line(profiles[1].PointAtEnd, dir * tip)));
            profiles.Add(new LineCurve(new Line(profiles[2].PointAtEnd, dirB * slope)));
            profiles.Add(new LineCurve(new Line(profiles[3].PointAtEnd, dir * buttom * 0.5)));

            Transform move = Transform.Translation(Vector3d.CrossProduct(dir, C.Normal) * dedendum);
            Curve     rack = Curve.JoinCurves(profiles, 0.01, true)[0];

            rack.Transform(move);

            //Display
            locations.Add(rack.PointAtNormalizedLength(0.5));
            texts.Add(Math.Round(tip, 2).ToString());
            sizes.Add(Pitch * 4);

            //build helical
            //(H / Math.Tan(toRadian(Deg))) / (C.Radius * 2 * Math.PI) / Math.PI *2 * (C.Radius * 2 * Math.PI)
            double    hShift = H / (Math.Tan(toRadian(90.0 - HAngle)) * 2 * Math.PI); //helical shift
            double    hTime  = Math.Ceiling(hShift / Pitch);
            Transform shift  = Transform.Translation(dir * hShift);
            Transform zH     = Transform.Translation(C.Normal * H);

            List <Curve> racks    = new List <Curve>();
            List <Curve> helicals = new List <Curve>();

            if (hTime / Math.Abs(hTime) == 1)
            {
                // base rack
                for (int i = -1; i < time + 1; i++)
                {
                    Transform duplicate = Transform.Translation(dir * Pitch * i);
                    Curve     thisC     = rack.DuplicateCurve();
                    thisC.Transform(duplicate);
                    racks.Add(thisC);
                }
                // helical
                for (int i = -1; i < time + 1; i++)
                {
                    Transform duplicate = Transform.Translation(dir * Pitch * i);
                    Curve     thisC     = rack.DuplicateCurve();
                    thisC.Transform(duplicate);
                    helicals.Add(thisC);
                }
            }
            else
            {
                // base rack
                for (int i = 0; i < time + 2; i++)
                {
                    Transform duplicate = Transform.Translation(dir * Pitch * i);
                    Curve     thisC     = rack.DuplicateCurve();
                    thisC.Transform(duplicate);
                    racks.Add(thisC);
                }
                //helical
                for (int i = 0; i < time + 2; i++)
                {
                    Transform duplicate = Transform.Translation(dir * Pitch * i);
                    Curve     thisC     = rack.DuplicateCurve();
                    thisC.Transform(duplicate);
                    helicals.Add(thisC);
                }
            }
            Curve helical = Curve.JoinCurves(helicals, 1, true)[0];

            //align
            var    ccx     = Rhino.Geometry.Intersect.Intersection.CurveCurve(new LineCurve(L), new ArcCurve(C), 0.1, 0.1);
            double align_d = dedendum * Math.Tan(toRadian(Angle)) + tip + addendum / Math.Tan(toRadian(90 - Angle)) * 2 + buttom * 0.5;

            align_d += Math.Floor(ccx[0].PointA.DistanceTo(L.From + dir * align_d) / Pitch) * Pitch;
            Point3d   closet = L.From + dir * align_d;
            Transform align  = Transform.Translation(ccx[0].PointA - closet);

            rack = Curve.JoinCurves(racks, 1, true)[0];
            rack.Transform(align);
            helical.Transform(align);
            helical.Transform(shift);
            helical.Transform(zH);

            List <Curve> sections = new List <Curve> {
                rack, helical
            };
            Brep profile = Brep.CreateFromLoft(sections, Point3d.Unset, Point3d.Unset, LoftType.Normal, false)[0];

            return(profile);
        }
Beispiel #42
0
        public override void BuildProcessing(MillingCommandGenerator generator)
        {
            const int CornerIndentIncrease = 5;
            var       curve        = ProcessingArea.GetCurve();
            var       thickness    = TechProcess.Thickness.Value + 2; // запил на 2мм ниже нижнего края
            var       toolDiameter = TechProcess.Tool.Diameter;
            var       engineSide   = Side.None;
            double    offsetArc    = 0;
            double    angleA       = 0;

            if (TechProcess.MachineType == MachineType.ScemaLogic)
            {
                AngleA = 0;
            }

            switch (curve)
            {
            case Arc arc:
                CalcArc(arc);
                break;

            case Line line:
                CalcLine(line);
                break;

            case Polyline polyline:
                CalcPolyline(polyline);
                break;

            default:
                throw new InvalidOperationException($"Кривая типа {curve.GetType()} не может быть обработана.");
            }

            var outerSideSign = OuterSide == Side.Left ^ curve is Line ? -1 : 1;
            var offsetCoeff   = Math.Tan(angleA) * outerSideSign;
            var depthCoeff    = 1 / Math.Cos(angleA);
            var toolThickness = TechProcess.Tool.Thickness.Value * depthCoeff;
            var compensation  = (offsetArc + (engineSide == OuterSide ^ TechProcess.MachineType == MachineType.Donatoni ? toolThickness : 0)) * outerSideSign;
            var shift         = angleA > 0 ? -thickness * offsetCoeff : 0;

            var sumIndent = CalcIndent(thickness) * (Convert.ToInt32(IsExactlyBegin) + Convert.ToInt32(IsExactlyEnd));

            if (sumIndent >= curve.Length())
            {
                if (AngleA != 0)
                {
                    throw new InvalidOperationException("Расчет намечания выполняется только при нулевом вертикальном угле.");
                }
                var point = Scheduling();
                var angle = BuilderUtils.CalcToolAngle((curve.EndPoint - curve.StartPoint).ToVector2d().Angle, engineSide);
                generator.Move(point.X, point.Y, angleC: angle);
                generator.Cutting(point.X, point.Y, point.Z, TechProcess.PenetrationFeed);
                return;
            }

            var modes = SawingModes.ConvertAll(p => new CuttingMode {
                Depth = p.Depth, DepthStep = p.DepthStep, Feed = p.Feed
            });
            var passList = BuilderUtils.GetPassList(modes, thickness, !ProcessingArea.ObjectId.IsLine()).ToList();

            Curve toolpathCurve = null;

            foreach (var item in passList)
            {
                CreateToolpath(item.Key, compensation + shift + item.Key * offsetCoeff);
                if (generator.IsUpperTool)
                {
                    var point  = engineSide == Side.Right ^ (passList.Count() % 2 == 1) ? toolpathCurve.EndPoint : toolpathCurve.StartPoint;
                    var vector = Vector3d.ZAxis * (item.Key + generator.ZSafety);
                    if (angleA != 0)
                    {
                        vector = vector.RotateBy(outerSideSign * angleA, ((Line)toolpathCurve).Delta) * depthCoeff;
                    }
                    var p0     = point + vector;
                    var angleC = BuilderUtils.CalcToolAngle(toolpathCurve, point, engineSide);
                    generator.Move(p0.X, p0.Y, angleC: angleC, angleA: Math.Abs(AngleA));
                    if (TechProcess.MachineType == MachineType.ScemaLogic)
                    {
                        generator.Command("28;;XYCZ;;;;;;", "Цикл");
                    }
                }
                generator.Cutting(toolpathCurve, item.Value, TechProcess.PenetrationFeed, engineSide);
            }
            generator.Uplifting(Vector3d.ZAxis.RotateBy(outerSideSign * angleA, toolpathCurve.EndPoint - toolpathCurve.StartPoint) * (thickness + generator.ZSafety) * depthCoeff);

            if ((!IsExactlyBegin || !IsExactlyEnd) && Departure == 0)
            {
                var gashCurve = curve.GetOffsetCurves(shift)[0] as Curve;
                var gashList  = new List <ObjectId>();
                if (!IsExactlyBegin)
                {
                    gashList.Add(Acad.CreateGash(gashCurve, gashCurve.StartPoint, OuterSide, thickness * depthCoeff, toolDiameter, toolThickness));
                }
                if (!IsExactlyEnd)
                {
                    gashList.Add(Acad.CreateGash(gashCurve, gashCurve.EndPoint, OuterSide, thickness * depthCoeff, toolDiameter, toolThickness));
                }
                if (gashList.Count > 0)
                {
                    Modify.AppendToGroup(base.TechProcess.ExtraObjectsGroup.Value, gashList.ToArray());
                }
                gashCurve.Dispose();
            }

            // Local func ------------------------

            void CalcArc(Arc arc)
            {
                AngleA = 0;
                var startSide      = Math.Sign(Math.Cos(arc.StartAngle.Round(3)));
                var endSide        = Math.Sign(Math.Cos(arc.EndAngle.Round(3)));
                var cornersOneSide = Math.Sign(startSide * endSide);

                if (arc.TotalAngle.Round(3) > Math.PI && cornersOneSide > 0)
                {
                    throw new InvalidOperationException("Обработка дуги невозможна - дуга пересекает углы 90 и 270 градусов.");
                }

                if (cornersOneSide < 0) //  дуга пересекает углы 90 или 270 градусов
                {
                    if (TechProcess.MachineType == MachineType.ScemaLogic)
                    {
                        throw new InvalidOperationException("Обработка дуги невозможна - дуга пересекает угол 90 или 270 градусов.");
                    }

                    engineSide = startSide > 0 ? Side.Left : Side.Right;
                }
                if (OuterSide == Side.Left)                                                         // внутренний рез дуги
                {
                    if (TechProcess.MachineType == MachineType.Donatoni && engineSide != Side.Left) // подворот диска при вн. резе дуги
                    {
                        engineSide = Side.Right;
                        //var comp = arc.Radius - Math.Sqrt(arc.Radius * arc.Radius - thickness * (toolDiameter - thickness));
                        //AngleA = Math.Atan2(comp, thickness).ToDeg();

                        var R    = arc.Radius;
                        var t    = thickness;
                        var d    = toolDiameter;
                        var comp = (2 * R * t * t - Math.Sqrt(-d * d * d * d * t * t + 4 * d * d * R * R * t * t + d * d * t * t * t * t)) / (d * d - 4 * R * R);
                        AngleA = -Math.Atan2(comp, thickness).ToDeg();
                    }
                    else
                    {
                        offsetArc = arc.Radius - Math.Sqrt(arc.Radius * arc.Radius - thickness * (toolDiameter - thickness));
                    }
                }
                if (engineSide == Side.None)
                {
                    engineSide = (startSide + endSide) > 0 ? Side.Right : Side.Left;
                }
            }

            void CalcLine(Line line)
            {
                angleA     = AngleA.ToRad();
                engineSide = AngleA == 0 ? BuilderUtils.CalcEngineSide(line.Angle) : AngleA > 0 ? OuterSide : OuterSide.Opposite();
            }

            void CalcPolyline(Polyline polyline)
            {
                int sign = 0;

                for (int i = 0; i < polyline.NumberOfVertices; i++)
                {
                    var point = polyline.GetPoint3dAt(i);
                    var s     = Math.Sign(Math.Sin(polyline.GetTangent(point).Angle.Round(6)));
                    if (s == 0)
                    {
                        continue;
                    }
                    if (sign == 0)
                    {
                        sign = s;
                        continue;
                    }
                    var bulge = polyline.GetBulgeAt(i - 1);
                    if (bulge == 0)
                    {
                        bulge = polyline.GetBulgeAt(i);
                    }

                    if (s != sign)
                    {
                        if (TechProcess.MachineType == MachineType.ScemaLogic)
                        {
                            throw new InvalidOperationException("Обработка полилинии невозможна - кривая пересекает углы 90 или 270 градусов.");
                        }
                        var side = sign > 0 ^ bulge < 0 ? Side.Left : Side.Right;
                        if (engineSide != Side.None)
                        {
                            if (engineSide != side)
                            {
                                throw new InvalidOperationException("Обработка полилинии невозможна.");
                            }
                        }
                        else
                        {
                            engineSide = side;
                        }
                        sign = s;
                    }
                    else
                    if (Math.Abs(bulge) > 1)
                    {
                        throw new InvalidOperationException("Обработка невозможна - дуга полилинии пересекает углы 90 и 270 градусов.");
                    }
                }
                if (engineSide == Side.None)
                {
                    engineSide = BuilderUtils.CalcEngineSide(polyline.GetTangent(polyline.StartPoint).Angle);
                }
            }

            void CreateToolpath(double depth, double offset)
            {
                toolpathCurve = curve.GetOffsetCurves(offset)[0] as Curve;
                toolpathCurve.TransformBy(Matrix3d.Displacement(-Vector3d.ZAxis * depth));

                if (Departure > 0 && toolpathCurve is Line line)
                {
                    if (!IsExactlyBegin)
                    {
                        toolpathCurve.StartPoint = line.ExpandStart(Departure);
                    }
                    if (!IsExactlyEnd)
                    {
                        toolpathCurve.EndPoint = line.ExpandEnd(Departure);
                    }
                }

                if (!IsExactlyBegin && !IsExactlyEnd)
                {
                    return;
                }
                var indent = CalcIndent(depth * depthCoeff);

                switch (toolpathCurve)
                {
                case Line l:
                    if (IsExactlyBegin)
                    {
                        l.StartPoint = l.GetPointAtDist(indent);
                    }
                    if (IsExactlyEnd)
                    {
                        l.EndPoint = l.GetPointAtDist(l.Length - indent);
                    }
                    break;

                case Arc a:
                    var indentAngle = indent / ((Arc)curve).Radius;
                    if (IsExactlyBegin)
                    {
                        a.StartAngle = a.StartAngle + indentAngle;
                    }
                    if (IsExactlyEnd)
                    {
                        a.EndAngle = a.EndAngle - indentAngle;
                    }
                    break;

                case Polyline p:
                    if (IsExactlyBegin)
                    {
                        p.SetPointAt(0, p.GetPointAtDist(indent).ToPoint2d());
                    }
                    //p.StartPoint = p.GetPointAtDist(indent);
                    if (IsExactlyEnd)
                    {
                        //p.EndPoint = p.GetPointAtDist(p.Length - indent);
                        p.SetPointAt(p.NumberOfVertices - 1, p.GetPointAtDist(p.Length - indent).ToPoint2d());
                    }
                    break;
                }
                ;
            }

            double CalcIndent(double depth) => Math.Sqrt(depth * (toolDiameter - depth)) + CornerIndentIncrease;

            /// <summary>
            /// Расчет точки намечания
            /// </summary>
            Point3d Scheduling()
            {
                var vector = curve.EndPoint - curve.StartPoint;
                var depth  = thickness;
                var point  = Point3d.Origin;

                if (IsExactlyBegin && IsExactlyEnd)
                {
                    var l = vector.Length - 2 * CornerIndentIncrease;
                    depth = (toolDiameter - Math.Sqrt(toolDiameter * toolDiameter - l * l)) / 2;
                    point = curve.StartPoint + vector / 2;
                }
                else
                {
                    var indentVector = vector.GetNormal() * (Math.Sqrt(depth * (toolDiameter - depth)) + CornerIndentIncrease);
                    point = IsExactlyBegin ? curve.StartPoint + indentVector : curve.EndPoint - indentVector;
                    Acad.CreateGash(curve, IsExactlyBegin ? curve.EndPoint : curve.StartPoint, OuterSide, depth, toolDiameter, toolThickness, point);
                }
                return(point + vector.GetPerpendicularVector().GetNormal() * compensation - Vector3d.ZAxis * depth);
            }
        }
Beispiel #43
0
        /// <summary>
        /// Creates or populates Revit elements based on the information contained in this class.
        /// </summary>
        /// <param name="doc">The document.</param>
        /// <param name="lcs">The local coordinate system transform.</param>
        public void Create(Document doc, Transform lcs)
        {
            if (!IsValidForCreation)
            {
                return;
            }

            // These are hardwired values to ensure that the Grid is visible in the
            // current view, in feet.  Note that there is an assumption that building stories
            // would not be placed too close to one another; if they are, and they use different
            // grid structures, then the plan views may have overlapping grid lines.  This seems
            // more likely in theory than practice.
            const double bottomOffset = 1.0 / 12.0; // 1" =   2.54 cm
            const double topOffset    = 4.0;        // 4' = 121.92 cm

            double originalZ = (lcs != null) ? lcs.Origin.Z : 0.0;

            if (CreatedElementId != ElementId.InvalidElementId)
            {
                Grid existingGrid = doc.GetElement(CreatedElementId) as Grid;
                if (existingGrid != null)
                {
                    Outline outline = existingGrid.GetExtents();
                    existingGrid.SetVerticalExtents(Math.Min(originalZ - bottomOffset, outline.MinimumPoint.Z),
                                                    Math.Max(originalZ + topOffset, outline.MaximumPoint.Z));
                }
                return;
            }

            Curve baseCurve = GetAxisCurve();

            if (baseCurve == null)
            {
                return;
            }

            Grid grid = null;

            Curve curve = baseCurve.CreateTransformed(lcs);

            if (curve == null)
            {
                Importer.TheLog.LogError(AxisCurve.Id, "Couldn't create transformed axis curve for grid line, ignoring.", false);
                IsValidForCreation = false;
                return;
            }

            if (!curve.IsBound)
            {
                curve.MakeBound(-100, 100);
                Importer.TheLog.LogWarning(AxisCurve.Id, "Creating arbitrary bounds for unbounded grid line.", false);
            }

            // Grid.create can throw, so catch the exception if it does.
            try
            {
                if (curve is Arc)
                {
                    // This will potentially make a small modification in the curve if it is unbounded,
                    // as Revit doesn't allow unbounded grid lines.
                    grid = CreateArcGridAxis(doc, curve as Arc);
                }
                else if (curve is Line)
                {
                    grid = CreateGridFromCurve(doc, curve as Line);
                }
                else
                {
                    Importer.TheLog.LogError(AxisCurve.Id, "Couldn't create grid line from curve of type " + curve.GetType().ToString() + ", expected line or arc.", false);
                    IsValidForCreation = false;
                    return;
                }
            }
            catch (Exception ex)
            {
                Importer.TheLog.LogError(AxisCurve.Id, ex.Message, false);
                IsValidForCreation = false;
                return;
            }

            if (grid != null)
            {
                SetAxisTagUnique(grid, AxisTag);

                // We will try to "grid match" as much as possible to avoid duplicate grid lines.  As such,
                // we want the remaining grid lines to extend to the current level.
                // A limitation here is that if a grid axis in the IFC file were visible on Level 1 and Level 3
                // but not Level 2, this will make it visibile on Level 2 also.  As above, this seems
                // more likely in theory than practice.
                grid.SetVerticalExtents(originalZ - bottomOffset, originalZ + topOffset);

                CreatedElementId = grid.Id;
            }
        }
Beispiel #44
0
        /************************************************************************************************************************/

        /// <summary>Modify the current fade to use the specified `curve` to calculate the weight.</summary>
        /// <example>See <see cref="CustomFade"/>.</example>
        /// <remarks>The `curve` should follow the <see cref="OptionalWarning.CustomFadeBounds"/> guideline.</remarks>
        public static void Apply(AnimancerPlayable animancer, AnimationCurve curve)
        => Curve.Acquire(curve).Apply(animancer);
Beispiel #45
0
        /// <summary>
        /// Processes IfcGridAxis attributes.
        /// </summary>
        /// <param name="ifcGridAxis">The IfcGridAxis handle.</param>
        protected override void Process(IFCAnyHandle ifcGridAxis)
        {
            base.Process(ifcGridAxis);

            AxisTag = IFCImportHandleUtil.GetOptionalStringAttribute(ifcGridAxis, "AxisTag", null);
            if (AxisTag == null)
            {
                AxisTag = "Z"; // arbitrary; all Revit Grids have names.
            }
            IFCAnyHandle axisCurve = IFCImportHandleUtil.GetRequiredInstanceAttribute(ifcGridAxis, "AxisCurve", true);

            AxisCurve = IFCCurve.ProcessIFCCurve(axisCurve);

            bool found     = false;
            bool sameSense = IFCImportHandleUtil.GetRequiredBooleanAttribute(ifcGridAxis, "SameSense", out found);

            SameSense = found ? sameSense : true;

            // We are going to check if this grid axis is a vertical duplicate of any existing axis.
            // If so, we will throw an exception so that we don't create duplicate grids.
            // We will only initialize these values if we actually intend to use them below.
            IList <Curve> curves     = null;
            int           curveCount = 0;

            ElementId gridId = ElementId.InvalidElementId;

            if (Importer.TheCache.GridNameToElementMap.TryGetValue(AxisTag, out gridId))
            {
                Grid grid = IFCImportFile.TheFile.Document.GetElement(gridId) as Grid;
                if (grid != null)
                {
                    IList <Curve> otherCurves = new List <Curve>();
                    Curve         gridCurve   = grid.Curve;
                    if (gridCurve != null)
                    {
                        otherCurves.Add(gridCurve);
                        long matchingGridId = FindMatchingGrid(otherCurves, grid.Id.IntegerValue, ref curves, ref curveCount);

                        if (matchingGridId != -1)
                        {
                            Importer.TheCache.UseGrid(grid);
                            CreatedElementId = grid.Id;
                            return;
                        }
                    }
                }
            }

            IDictionary <string, IFCGridAxis> gridAxes = IFCImportFile.TheFile.IFCProject.GridAxes;
            IFCGridAxis gridAxis = null;

            if (gridAxes.TryGetValue(AxisTag, out gridAxis))
            {
                long matchingGridId = FindMatchingGrid(gridAxis, ref curves, ref curveCount);
                if (matchingGridId != -1)
                {
                    DuplicateAxisId = matchingGridId;
                    return;
                }
                else
                {
                    // Revit doesn't allow grid lines to have the same name.  If it isn't a duplicate, rename it.
                    // Note that this will mean that we may miss some "duplicate" grid lines because of the renaming.
                    AxisTag = MakeAxisTagUnique(AxisTag);
                }
            }

            gridAxes.Add(new KeyValuePair <string, IFCGridAxis>(AxisTag, this));
        }
Beispiel #46
0
 internal override void SetXML(XmlElement xml, BaseClassIfc host, Dictionary <int, XmlElement> processed)
 {
     base.SetXML(xml, host, processed);
     xml.AppendChild(Curve.GetXML(xml.OwnerDocument, "Curve", this, processed));
 }
Beispiel #47
0
        public void Middle_beam_left_building(ExternalCommandData commandData)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;

            Autodesk.Revit.DB.Document Rdoc = uidoc.Document;
            //族样板路径
            String        filePath = @"C:\ProgramData\Autodesk\RVT 2018\Family Templates\Chinese\公制常规模型.rft";
            UIApplication uiapp    = commandData.Application;

            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;

            //创建族文档
            Autodesk.Revit.DB.Document familyDoc = app.NewFamilyDocument(filePath);
            zz_Coordinate_Transformation.Z_coordinate_transformation();
            Transaction familyTrans = new Transaction(familyDoc, "family");

            //familyDoc.FamilyManager.NewType("1");

            #region 定义主梁轮廓线与轮廓线连接
            //定义部分1左半边轮廓线与轮廓线连接
            CurveArrArray bubufen1_z = app.Create.NewCurveArrArray();
            CurveArray    bufen1_z   = app.Create.NewCurveArray();

            //定义部分1右半边轮廓线与轮廓线连接
            CurveArrArray bubufen1_y = app.Create.NewCurveArrArray();
            CurveArray    bufen1_y   = app.Create.NewCurveArray();

            //定义部分2左半边近心点轮廓线与轮廓线连接
            CurveArrArray bubufen2_jz = app.Create.NewCurveArrArray();
            CurveArray    bufen2_jz   = app.Create.NewCurveArray();

            //定义部分2右半边近心点轮廓线与轮廓线连接
            CurveArrArray bubufen2_jy = app.Create.NewCurveArrArray();
            CurveArray    bufen2_jy   = app.Create.NewCurveArray();

            //定义部分2左半边上部分内侧轮廓线与轮廓线连接
            CurveArrArray bubufen2_z = app.Create.NewCurveArrArray();
            CurveArray    bufen2_z   = app.Create.NewCurveArray();

            //定义部分2右半边轮廓线与轮廓线连接
            CurveArrArray bubufen2_y = app.Create.NewCurveArrArray();
            CurveArray    bufen2_y   = app.Create.NewCurveArray();
            #endregion

            #region 创建坐标点
            #region//创建三维轮廓线坐标点,用于部分1与部分5的拉伸
            XYZ pzz0  = new XYZ(0, 0, 400);
            XYZ pzz1  = new XYZ(Windows_Canvas.b_zd_zl_out[0], 0, z_coordinate_transformation.z_zd_zl_out[0] + 400);
            XYZ pzz2  = new XYZ(Windows_Canvas.b_zd_zl_out[11], 0, z_coordinate_transformation.z_zd_zl_out[11] + 400);
            XYZ pzz3  = new XYZ(Windows_Canvas.b_zd_zl_out[10], 0, z_coordinate_transformation.z_zd_zl_out[10] + 400);
            XYZ pzz4  = new XYZ(Windows_Canvas.b_zd_zl_out[9], 0, z_coordinate_transformation.z_zd_zl_out[9] + 400);
            XYZ pzz5  = new XYZ(Windows_Canvas.b_zd_zl_out[8], 0, z_coordinate_transformation.z_zd_zl_out[8] + 400);
            XYZ pzz6  = new XYZ(0, 0, z_coordinate_transformation.z_zd_zl_out[8] + 400);
            XYZ pzz7  = new XYZ(0, 0, z_coordinate_transformation.z_zd_zl_in[4] + 400);
            XYZ pzz8  = new XYZ(Windows_Canvas.b_zd_zl_in[4], 0, z_coordinate_transformation.z_zd_zl_in[4] + 400);
            XYZ pzz9  = new XYZ(Windows_Canvas.b_zd_zl_in[5], 0, z_coordinate_transformation.z_zd_zl_in[5] + 400);
            XYZ pzz10 = new XYZ(Windows_Canvas.b_zd_zl_in[6], 0, z_coordinate_transformation.z_zd_zl_in[6] + 400);
            XYZ pzz11 = new XYZ(Windows_Canvas.b_zd_zl_in[7], 0, z_coordinate_transformation.z_zd_zl_in[7] + 400);
            XYZ pzz12 = new XYZ(0, 0, z_coordinate_transformation.z_zd_zl_in[7] + 400);
            #endregion

            #region//创建三维轮廓线坐标点,用于2部分的融合(左半边的)
            XYZ pjz0  = new XYZ(0, l1, 400);
            XYZ pjz1  = new XYZ(Windows_Canvas.b_zd_zl_out[0], l1, z_coordinate_transformation.z_zd_zl_out[0] + 400);
            XYZ pjz2  = new XYZ(Windows_Canvas.b_zd_zl_out[11], l1, z_coordinate_transformation.z_zd_zl_out[11] + 400);
            XYZ pjz3  = new XYZ(Windows_Canvas.b_zd_zl_out[10], l1, z_coordinate_transformation.z_zd_zl_out[10] + 400);
            XYZ pjz4  = new XYZ(Windows_Canvas.b_zd_zl_out[9], l1, z_coordinate_transformation.z_zd_zl_out[9] + 400);
            XYZ pjz5  = new XYZ(Windows_Canvas.b_zd_zl_out[8], l1, z_coordinate_transformation.z_zd_zl_out[8] + 400);
            XYZ pjz6  = new XYZ(0, l1, z_coordinate_transformation.z_zd_zl_out[8] + 400);
            XYZ pjz7  = new XYZ(0, l1, z_coordinate_transformation.z_zd_zl_in[4] + 400);
            XYZ pjz8  = new XYZ(Windows_Canvas.b_zd_zl_in[4], l1, z_coordinate_transformation.z_zd_zl_in[4] + 400);
            XYZ pjz9  = new XYZ(Windows_Canvas.b_zd_zl_in[5], l1, z_coordinate_transformation.z_zd_zl_in[5] + 400);
            XYZ pjz10 = new XYZ(Windows_Canvas.b_zd_zl_in[6], l1, z_coordinate_transformation.z_zd_zl_in[6] + 400);
            XYZ pjz11 = new XYZ(Windows_Canvas.b_zd_zl_in[7], l1, z_coordinate_transformation.z_zd_zl_in[7] + 400);
            XYZ pjz12 = new XYZ(0, l1, z_coordinate_transformation.z_zd_zl_in[7] + 400);
            #endregion

            #region//创建三维轮廓线坐标点,用于2部分的融合(右半边的)
            XYZ pjy0  = new XYZ(0, l1, 400);
            XYZ pjy1  = new XYZ(-Windows_Canvas.b_zd_zl_out[0], l1, z_coordinate_transformation.z_zd_zl_out[0] + 400);
            XYZ pjy2  = new XYZ(-Windows_Canvas.b_zd_zl_out[11], l1, z_coordinate_transformation.z_zd_zl_out[11] + 400);
            XYZ pjy3  = new XYZ(-Windows_Canvas.b_zd_zl_out[10], l1, z_coordinate_transformation.z_zd_zl_out[10] + 400);
            XYZ pjy4  = new XYZ(-Windows_Canvas.b_zd_zl_out[9], l1, z_coordinate_transformation.z_zd_zl_out[9] + 400);
            XYZ pjy5  = new XYZ(-Windows_Canvas.b_zd_zl_out[8], l1, z_coordinate_transformation.z_zd_zl_out[8] + 400);
            XYZ pjy6  = new XYZ(0, l1, z_coordinate_transformation.z_zd_zl_out[8] + 400);
            XYZ pjy7  = new XYZ(0, l1, z_coordinate_transformation.z_zd_zl_in[4] + 400);
            XYZ pjy8  = new XYZ(-Windows_Canvas.b_zd_zl_in[4], l1, z_coordinate_transformation.z_zd_zl_in[4] + 400);
            XYZ pjy9  = new XYZ(-Windows_Canvas.b_zd_zl_in[5], l1, z_coordinate_transformation.z_zd_zl_in[5] + 400);
            XYZ pjy10 = new XYZ(-Windows_Canvas.b_zd_zl_in[6], l1, z_coordinate_transformation.z_zd_zl_in[6] + 400);
            XYZ pjy11 = new XYZ(-Windows_Canvas.b_zd_zl_in[7], l1, z_coordinate_transformation.z_zd_zl_in[7] + 400);
            XYZ pjy12 = new XYZ(0, l1, z_coordinate_transformation.z_zd_zl_in[7] + 400);
            #endregion

            #region//创建三维轮廓线坐标点,用于部分3的拉伸,2部分的融合(左半边的)
            XYZ pkz0  = new XYZ(0, l1 + l2, 400);
            XYZ pkz1  = new XYZ(Windows_Canvas.b_kz_zl_out[0], l1 + l2, z_coordinate_transformation.z_kz_zl_out[0] + 400);
            XYZ pkz2  = new XYZ(Windows_Canvas.b_kz_zl_out[11], l1 + l2, z_coordinate_transformation.z_kz_zl_out[11] + 400);
            XYZ pkz3  = new XYZ(Windows_Canvas.b_kz_zl_out[10], l1 + l2, z_coordinate_transformation.z_kz_zl_out[10] + 400);
            XYZ pkz4  = new XYZ(Windows_Canvas.b_kz_zl_out[9], l1 + l2, z_coordinate_transformation.z_kz_zl_out[9] + 400);
            XYZ pkz5  = new XYZ(Windows_Canvas.b_kz_zl_out[8], l1 + l2, z_coordinate_transformation.z_kz_zl_out[8] + 400);
            XYZ pkz6  = new XYZ(0, l1 + l2, z_coordinate_transformation.z_kz_zl_out[8] + 400);
            XYZ pkz7  = new XYZ(0, l1 + l2, z_coordinate_transformation.z_kz_zl_in[4] + 400);
            XYZ pkz8  = new XYZ(Windows_Canvas.b_kz_zl_in[4], l1 + l2, z_coordinate_transformation.z_kz_zl_in[4] + 400);
            XYZ pkz9  = new XYZ(Windows_Canvas.b_kz_zl_in[5], l1 + l2, z_coordinate_transformation.z_kz_zl_in[5] + 400);
            XYZ pkz10 = new XYZ(Windows_Canvas.b_kz_zl_in[6], l1 + l2, z_coordinate_transformation.z_kz_zl_in[6] + 400);
            XYZ pkz11 = new XYZ(Windows_Canvas.b_kz_zl_in[7], l1 + l2, z_coordinate_transformation.z_kz_zl_in[7] + 400);
            XYZ pkz12 = new XYZ(0, l1 + l2, z_coordinate_transformation.z_zd_zl_in[7] + 400);
            #endregion

            #region//创建三维轮廓线坐标点,用于部分1与部分5的拉伸,2部分与4部分的融合(右半边的)
            XYZ pzy0  = new XYZ(0, 0, 400);
            XYZ pzy1  = new XYZ(-Windows_Canvas.b_zd_zl_out[0], 0, z_coordinate_transformation.z_zd_zl_out[0] + 400);
            XYZ pzy2  = new XYZ(-Windows_Canvas.b_zd_zl_out[11], 0, z_coordinate_transformation.z_zd_zl_out[11] + 400);
            XYZ pzy3  = new XYZ(-Windows_Canvas.b_zd_zl_out[10], 0, z_coordinate_transformation.z_zd_zl_out[10] + 400);
            XYZ pzy4  = new XYZ(-Windows_Canvas.b_zd_zl_out[9], 0, z_coordinate_transformation.z_zd_zl_out[9] + 400);
            XYZ pzy5  = new XYZ(-Windows_Canvas.b_zd_zl_out[8], 0, z_coordinate_transformation.z_zd_zl_out[8] + 400);
            XYZ pzy6  = new XYZ(0, 0, z_coordinate_transformation.z_zd_zl_out[8] + 400);
            XYZ pzy7  = new XYZ(0, 0, z_coordinate_transformation.z_zd_zl_in[4] + 400);
            XYZ pzy8  = new XYZ(-Windows_Canvas.b_zd_zl_in[4], 0, z_coordinate_transformation.z_zd_zl_in[4] + 400);
            XYZ pzy9  = new XYZ(-Windows_Canvas.b_zd_zl_in[5], 0, z_coordinate_transformation.z_zd_zl_in[5] + 400);
            XYZ pzy10 = new XYZ(-Windows_Canvas.b_zd_zl_in[6], 0, z_coordinate_transformation.z_zd_zl_in[6] + 400);
            XYZ pzy11 = new XYZ(-Windows_Canvas.b_zd_zl_in[7], 0, z_coordinate_transformation.z_zd_zl_in[7] + 400);
            XYZ pzy12 = new XYZ(0, 0, z_coordinate_transformation.z_zd_zl_in[7] + 400);
            #endregion

            #region//创建三维轮廓线坐标点,用于部分3的拉伸,2部分的融合(左半边的)
            XYZ pky0  = new XYZ(0, l1 + l2, 400);
            XYZ pky1  = new XYZ(-Windows_Canvas.b_kz_zl_out[0], l1 + l2, z_coordinate_transformation.z_kz_zl_out[0] + 400);
            XYZ pky2  = new XYZ(-Windows_Canvas.b_kz_zl_out[11], l1 + l2, z_coordinate_transformation.z_kz_zl_out[11] + 400);
            XYZ pky3  = new XYZ(-Windows_Canvas.b_kz_zl_out[10], l1 + l2, z_coordinate_transformation.z_kz_zl_out[10] + 400);
            XYZ pky4  = new XYZ(-Windows_Canvas.b_kz_zl_out[9], l1 + l2, z_coordinate_transformation.z_kz_zl_out[9] + 400);
            XYZ pky5  = new XYZ(-Windows_Canvas.b_kz_zl_out[8], l1 + l2, z_coordinate_transformation.z_kz_zl_out[8] + 400);
            XYZ pky6  = new XYZ(0, l1 + l2, z_coordinate_transformation.z_kz_zl_out[8] + 400);
            XYZ pky7  = new XYZ(0, l1 + l2, z_coordinate_transformation.z_kz_zl_in[4] + 400);
            XYZ pky8  = new XYZ(-Windows_Canvas.b_kz_zl_in[4], l1 + l2, z_coordinate_transformation.z_kz_zl_in[4] + 400);
            XYZ pky9  = new XYZ(-Windows_Canvas.b_kz_zl_in[5], l1 + l2, z_coordinate_transformation.z_kz_zl_in[5] + 400);
            XYZ pky10 = new XYZ(-Windows_Canvas.b_kz_zl_in[6], l1 + l2, z_coordinate_transformation.z_kz_zl_in[6] + 400);
            XYZ pky11 = new XYZ(-Windows_Canvas.b_kz_zl_in[7], l1 + l2, z_coordinate_transformation.z_kz_zl_in[7] + 400);
            XYZ pky12 = new XYZ(0, l1 + l2, z_coordinate_transformation.z_zd_zl_in[7] + 400);
            #endregion
            #endregion

            #region 创建轮廓线
            #region//创建部分1左半边轮廓线
            Curve bf1_outline_z_1  = Autodesk.Revit.DB.Line.CreateBound(pzz0, pzz1);
            Curve bf1_outline_z_2  = Autodesk.Revit.DB.Line.CreateBound(pzz1, pzz2);
            Curve bf1_outline_z_3  = Autodesk.Revit.DB.Line.CreateBound(pzz2, pzz3);
            Curve bf1_outline_z_4  = Autodesk.Revit.DB.Line.CreateBound(pzz3, pzz4);
            Curve bf1_outline_z_5  = Autodesk.Revit.DB.Line.CreateBound(pzz4, pzz5);
            Curve bf1_outline_z_6  = Autodesk.Revit.DB.Line.CreateBound(pzz5, pzz6);
            Curve bf1_outline_z_7  = Autodesk.Revit.DB.Line.CreateBound(pzz6, pzz7);
            Curve bf1_outline_z_8  = Autodesk.Revit.DB.Line.CreateBound(pzz7, pzz8);
            Curve bf1_outline_z_9  = Autodesk.Revit.DB.Line.CreateBound(pzz8, pzz9);
            Curve bf1_outline_z_10 = Autodesk.Revit.DB.Line.CreateBound(pzz9, pzz10);
            Curve bf1_outline_z_11 = Autodesk.Revit.DB.Line.CreateBound(pzz10, pzz11);
            Curve bf1_outline_z_12 = Autodesk.Revit.DB.Line.CreateBound(pzz11, pzz12);
            Curve bf1_outline_z_13 = Autodesk.Revit.DB.Line.CreateBound(pzz12, pzz0);
            #endregion

            #region//创建部分2左半边近心点轮廓线
            Curve bf2_outline_jz_1  = Autodesk.Revit.DB.Line.CreateBound(pjz0, pjz1);
            Curve bf2_outline_jz_2  = Autodesk.Revit.DB.Line.CreateBound(pjz1, pjz2);
            Curve bf2_outline_jz_3  = Autodesk.Revit.DB.Line.CreateBound(pjz2, pjz3);
            Curve bf2_outline_jz_4  = Autodesk.Revit.DB.Line.CreateBound(pjz3, pjz4);
            Curve bf2_outline_jz_5  = Autodesk.Revit.DB.Line.CreateBound(pjz4, pjz5);
            Curve bf2_outline_jz_6  = Autodesk.Revit.DB.Line.CreateBound(pjz5, pjz6);
            Curve bf2_outline_jz_7  = Autodesk.Revit.DB.Line.CreateBound(pjz6, pjz7);
            Curve bf2_outline_jz_8  = Autodesk.Revit.DB.Line.CreateBound(pjz7, pjz8);
            Curve bf2_outline_jz_9  = Autodesk.Revit.DB.Line.CreateBound(pjz8, pjz9);
            Curve bf2_outline_jz_10 = Autodesk.Revit.DB.Line.CreateBound(pjz9, pjz10);
            Curve bf2_outline_jz_11 = Autodesk.Revit.DB.Line.CreateBound(pjz10, pjz11);
            Curve bf2_outline_jz_12 = Autodesk.Revit.DB.Line.CreateBound(pjz11, pjz12);
            Curve bf2_outline_jz_13 = Autodesk.Revit.DB.Line.CreateBound(pjz12, pjz0);
            #endregion

            #region//创建部分2右半边近心点轮廓线
            Curve bf2_outline_jy_1  = Autodesk.Revit.DB.Line.CreateBound(pjy0, pjy1);
            Curve bf2_outline_jy_2  = Autodesk.Revit.DB.Line.CreateBound(pjy1, pjy2);
            Curve bf2_outline_jy_3  = Autodesk.Revit.DB.Line.CreateBound(pjy2, pjy3);
            Curve bf2_outline_jy_4  = Autodesk.Revit.DB.Line.CreateBound(pjy3, pjy4);
            Curve bf2_outline_jy_5  = Autodesk.Revit.DB.Line.CreateBound(pjy4, pjy5);
            Curve bf2_outline_jy_6  = Autodesk.Revit.DB.Line.CreateBound(pjy5, pjy6);
            Curve bf2_outline_jy_7  = Autodesk.Revit.DB.Line.CreateBound(pjy6, pjy7);
            Curve bf2_outline_jy_8  = Autodesk.Revit.DB.Line.CreateBound(pjy7, pjy8);
            Curve bf2_outline_jy_9  = Autodesk.Revit.DB.Line.CreateBound(pjy8, pjy9);
            Curve bf2_outline_jy_10 = Autodesk.Revit.DB.Line.CreateBound(pjy9, pjy10);
            Curve bf2_outline_jy_11 = Autodesk.Revit.DB.Line.CreateBound(pjy10, pjy11);
            Curve bf2_outline_jy_12 = Autodesk.Revit.DB.Line.CreateBound(pjy11, pjy12);
            Curve bf2_outline_jy_13 = Autodesk.Revit.DB.Line.CreateBound(pjy12, pjy0);
            #endregion

            #region//创建部分1右半边轮廓线
            Curve bf1_outline_y_1  = Autodesk.Revit.DB.Line.CreateBound(pzy0, pzy12);
            Curve bf1_outline_y_2  = Autodesk.Revit.DB.Line.CreateBound(pzy12, pzy11);
            Curve bf1_outline_y_3  = Autodesk.Revit.DB.Line.CreateBound(pzy11, pzy10);
            Curve bf1_outline_y_4  = Autodesk.Revit.DB.Line.CreateBound(pzy10, pzy9);
            Curve bf1_outline_y_5  = Autodesk.Revit.DB.Line.CreateBound(pzy9, pzy8);
            Curve bf1_outline_y_6  = Autodesk.Revit.DB.Line.CreateBound(pzy8, pzy7);
            Curve bf1_outline_y_7  = Autodesk.Revit.DB.Line.CreateBound(pzy7, pzy6);
            Curve bf1_outline_y_8  = Autodesk.Revit.DB.Line.CreateBound(pzy6, pzy5);
            Curve bf1_outline_y_9  = Autodesk.Revit.DB.Line.CreateBound(pzy5, pzy4);
            Curve bf1_outline_y_10 = Autodesk.Revit.DB.Line.CreateBound(pzy4, pzy3);
            Curve bf1_outline_y_11 = Autodesk.Revit.DB.Line.CreateBound(pzy3, pzy2);
            Curve bf1_outline_y_12 = Autodesk.Revit.DB.Line.CreateBound(pzy2, pzy1);
            Curve bf1_outline_y_13 = Autodesk.Revit.DB.Line.CreateBound(pzy1, pzy0);
            #endregion

            #region//创建部分2远心点部分左半边轮廓线
            Curve bf2_outline_z_1  = Autodesk.Revit.DB.Line.CreateBound(pkz0, pkz1);
            Curve bf2_outline_z_2  = Autodesk.Revit.DB.Line.CreateBound(pkz1, pkz2);
            Curve bf2_outline_z_3  = Autodesk.Revit.DB.Line.CreateBound(pkz2, pkz3);
            Curve bf2_outline_z_4  = Autodesk.Revit.DB.Line.CreateBound(pkz3, pkz4);
            Curve bf2_outline_z_5  = Autodesk.Revit.DB.Line.CreateBound(pkz4, pkz5);
            Curve bf2_outline_z_6  = Autodesk.Revit.DB.Line.CreateBound(pkz5, pkz6);
            Curve bf2_outline_z_7  = Autodesk.Revit.DB.Line.CreateBound(pkz6, pkz7);
            Curve bf2_outline_z_8  = Autodesk.Revit.DB.Line.CreateBound(pkz7, pkz8);
            Curve bf2_outline_z_9  = Autodesk.Revit.DB.Line.CreateBound(pkz8, pkz9);
            Curve bf2_outline_z_10 = Autodesk.Revit.DB.Line.CreateBound(pkz9, pkz10);
            Curve bf2_outline_z_11 = Autodesk.Revit.DB.Line.CreateBound(pkz10, pkz11);
            Curve bf2_outline_z_12 = Autodesk.Revit.DB.Line.CreateBound(pkz11, pkz12);
            Curve bf2_outline_z_13 = Autodesk.Revit.DB.Line.CreateBound(pkz12, pkz0);
            #endregion

            #region//创建部分2远心点部分右半边轮廓线
            Curve bf2_outline_y_1  = Autodesk.Revit.DB.Line.CreateBound(pky0, pky1);
            Curve bf2_outline_y_2  = Autodesk.Revit.DB.Line.CreateBound(pky1, pky2);
            Curve bf2_outline_y_3  = Autodesk.Revit.DB.Line.CreateBound(pky2, pky3);
            Curve bf2_outline_y_4  = Autodesk.Revit.DB.Line.CreateBound(pky3, pky4);
            Curve bf2_outline_y_5  = Autodesk.Revit.DB.Line.CreateBound(pky4, pky5);
            Curve bf2_outline_y_6  = Autodesk.Revit.DB.Line.CreateBound(pky5, pky6);
            Curve bf2_outline_y_7  = Autodesk.Revit.DB.Line.CreateBound(pky6, pky7);
            Curve bf2_outline_y_8  = Autodesk.Revit.DB.Line.CreateBound(pky7, pky8);
            Curve bf2_outline_y_9  = Autodesk.Revit.DB.Line.CreateBound(pky8, pky9);
            Curve bf2_outline_y_10 = Autodesk.Revit.DB.Line.CreateBound(pky9, pky10);
            Curve bf2_outline_y_11 = Autodesk.Revit.DB.Line.CreateBound(pky10, pky11);
            Curve bf2_outline_y_12 = Autodesk.Revit.DB.Line.CreateBound(pky11, pky12);
            Curve bf2_outline_y_13 = Autodesk.Revit.DB.Line.CreateBound(pky12, pky0);
            #endregion
            #endregion

            #region 连接轮廓线
            #region//连接部分1左半边轮廓线
            bufen1_z.Append(bf1_outline_z_1);
            bufen1_z.Append(bf1_outline_z_2);
            bufen1_z.Append(bf1_outline_z_3);
            bufen1_z.Append(bf1_outline_z_4);
            bufen1_z.Append(bf1_outline_z_5);
            bufen1_z.Append(bf1_outline_z_6);
            bufen1_z.Append(bf1_outline_z_7);
            bufen1_z.Append(bf1_outline_z_8);
            bufen1_z.Append(bf1_outline_z_9);
            bufen1_z.Append(bf1_outline_z_10);
            bufen1_z.Append(bf1_outline_z_11);
            bufen1_z.Append(bf1_outline_z_12);
            bufen1_z.Append(bf1_outline_z_13);
            bubufen1_z.Append(bufen1_z);
            #endregion

            #region//连接部分2近心点左半边轮廓线
            bufen2_jz.Append(bf2_outline_jz_1);
            bufen2_jz.Append(bf2_outline_jz_2);
            bufen2_jz.Append(bf2_outline_jz_3);
            bufen2_jz.Append(bf2_outline_jz_4);
            bufen2_jz.Append(bf2_outline_jz_5);
            bufen2_jz.Append(bf2_outline_jz_6);
            bufen2_jz.Append(bf2_outline_jz_7);
            bufen2_jz.Append(bf2_outline_jz_8);
            bufen2_jz.Append(bf2_outline_jz_9);
            bufen2_jz.Append(bf2_outline_jz_10);
            bufen2_jz.Append(bf2_outline_jz_11);
            bufen2_jz.Append(bf2_outline_jz_12);
            bufen2_jz.Append(bf2_outline_jz_13);
            bubufen2_jz.Append(bufen2_jz);
            #endregion

            #region//连接部分2近心点右半边轮廓线
            bufen2_jy.Append(bf2_outline_jy_1);
            bufen2_jy.Append(bf2_outline_jy_2);
            bufen2_jy.Append(bf2_outline_jy_3);
            bufen2_jy.Append(bf2_outline_jy_4);
            bufen2_jy.Append(bf2_outline_jy_5);
            bufen2_jy.Append(bf2_outline_jy_6);
            bufen2_jy.Append(bf2_outline_jy_7);
            bufen2_jy.Append(bf2_outline_jy_8);
            bufen2_jy.Append(bf2_outline_jy_9);
            bufen2_jy.Append(bf2_outline_jy_10);
            bufen2_jy.Append(bf2_outline_jy_11);
            bufen2_jy.Append(bf2_outline_jy_12);
            bufen2_jy.Append(bf2_outline_jy_13);
            bubufen2_jy.Append(bufen2_jy);
            #endregion

            #region//连接部分1右半边轮廓线
            bufen1_y.Append(bf1_outline_y_1);
            bufen1_y.Append(bf1_outline_y_2);
            bufen1_y.Append(bf1_outline_y_3);
            bufen1_y.Append(bf1_outline_y_4);
            bufen1_y.Append(bf1_outline_y_5);
            bufen1_y.Append(bf1_outline_y_6);
            bufen1_y.Append(bf1_outline_y_7);
            bufen1_y.Append(bf1_outline_y_8);
            bufen1_y.Append(bf1_outline_y_9);
            bufen1_y.Append(bf1_outline_y_10);
            bufen1_y.Append(bf1_outline_y_11);
            bufen1_y.Append(bf1_outline_y_12);
            bufen1_y.Append(bf1_outline_y_13);
            bubufen1_y.Append(bufen1_y);
            #endregion

            #region//连接部分2左半边轮廓线
            bufen2_z.Append(bf2_outline_z_1);
            bufen2_z.Append(bf2_outline_z_2);
            bufen2_z.Append(bf2_outline_z_3);
            bufen2_z.Append(bf2_outline_z_4);
            bufen2_z.Append(bf2_outline_z_5);
            bufen2_z.Append(bf2_outline_z_6);
            bufen2_z.Append(bf2_outline_z_7);
            bufen2_z.Append(bf2_outline_z_8);
            bufen2_z.Append(bf2_outline_z_9);
            bufen2_z.Append(bf2_outline_z_10);
            bufen2_z.Append(bf2_outline_z_11);
            bufen2_z.Append(bf2_outline_z_12);
            bufen2_z.Append(bf2_outline_z_13);
            bubufen2_z.Append(bufen2_z);
            #endregion

            #region//连接部分2右半边轮廓线
            bufen2_y.Append(bf2_outline_y_1);
            bufen2_y.Append(bf2_outline_y_2);
            bufen2_y.Append(bf2_outline_y_3);
            bufen2_y.Append(bf2_outline_y_4);
            bufen2_y.Append(bf2_outline_y_5);
            bufen2_y.Append(bf2_outline_y_6);
            bufen2_y.Append(bf2_outline_y_7);
            bufen2_y.Append(bf2_outline_y_8);
            bufen2_y.Append(bf2_outline_y_9);
            bufen2_y.Append(bf2_outline_y_10);
            bufen2_y.Append(bf2_outline_y_11);
            bufen2_y.Append(bf2_outline_y_12);
            bufen2_y.Append(bf2_outline_y_13);
            bubufen2_y.Append(bufen2_y);
            #endregion
            #endregion

            #region 定义各部分元素名称
            Element Middlebeam1_z = null;
            Element Middlebeam1_y = null;
            Element Middlebeam2_z = null;
            Element Middlebeam2_y = null;
            Element Middlebeam3_z = null;
            Element Middlebeam3_y = null;
            Element Middlebeam4_z = null;
            Element Middlebeam4_y = null;
            Element Middlebeam5_z = null;
            Element Middlebeam5_y = null;
            #endregion

            #region 主梁的拉伸和融合
            //新建事务,创建主梁部分拉伸体
            using (Transaction Mainbeam_stretching = new Transaction(familyDoc))
            {
                if (Mainbeam_stretching.Start("主梁拉伸") == TransactionStatus.Started)
                {
                    Middlebeam1_z = familyDoc.FamilyCreate.NewExtrusion(true, bubufen1_z, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), l1);
                }
                Middlebeam1_y = familyDoc.FamilyCreate.NewExtrusion(true, bubufen1_y, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), l1);
                Middlebeam3_z = familyDoc.FamilyCreate.NewExtrusion(true, bubufen2_z, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), l3);
                Middlebeam3_y = familyDoc.FamilyCreate.NewExtrusion(true, bubufen2_y, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), l3);
                Middlebeam5_z = familyDoc.FamilyCreate.NewExtrusion(true, bubufen1_z, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), l1);
                Middlebeam5_y = familyDoc.FamilyCreate.NewExtrusion(true, bubufen1_y, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), l1);

                //移动部分5到正确位置
                XYZ transPointModel5 = new XYZ(0, l1 + 2 * l2 + l3, 0);
                ElementTransformUtils.MoveElement(familyDoc, Middlebeam5_z.Id, transPointModel5);
                ElementTransformUtils.MoveElement(familyDoc, Middlebeam5_y.Id, transPointModel5);
                Mainbeam_stretching.Commit();
            }

            //新建事务,创造主梁部分融合体
            using (Transaction Mainbeam_lofting = new Transaction(familyDoc))
            {
                if (Mainbeam_lofting.Start("主梁融合") == TransactionStatus.Started)
                {
                    Middlebeam2_z = familyDoc.FamilyCreate.NewBlend(true, bufen2_jz, bufen2_z, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(new XYZ(0, -1, 0), XYZ.Zero)));
                }
                Middlebeam2_y = familyDoc.FamilyCreate.NewBlend(true, bufen2_jy, bufen2_y, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(new XYZ(0, 1, 0), XYZ.Zero)));
                Middlebeam4_z = familyDoc.FamilyCreate.NewBlend(true, bufen2_jz, bufen2_z, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(new XYZ(0, -1, 0), XYZ.Zero)));
                Middlebeam4_y = familyDoc.FamilyCreate.NewBlend(true, bufen2_jy, bufen2_y, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(new XYZ(0, 1, 0), XYZ.Zero)));

                //移动部分4到正确的位置
                XYZ transPointModel4 = new XYZ(0, l2 + l3, 0);
                ElementTransformUtils.MoveElement(familyDoc, Middlebeam4_z.Id, transPointModel4);
                ElementTransformUtils.MoveElement(familyDoc, Middlebeam4_y.Id, transPointModel4);
                Mainbeam_lofting.Commit();
            }
            #endregion

            //using (Transaction transaction3 = new Transaction(familyDoc))
            //{
            //    if (transaction3.Start("连接") == TransactionStatus.Started)
            //        JoinGeometryUtils.JoinGeometry(familyDoc, Model1_z, Model1_y);
            //    transaction3.Commit();
            //}

            #region 横隔梁部分建模
            //左侧横隔梁坐标点
            XYZ hz1 = new XYZ(Windows_Canvas.b_zd_zl_out[11], 0, z_coordinate_transformation.z_zd_zl_out[11] + 400);
            XYZ hz2 = new XYZ(Windows_Canvas.b_zd_zl_out[13], 0, z_coordinate_transformation.z_zd_zl_out[13] + 400);
            XYZ hz3 = new XYZ(Windows_Canvas.b_zd_zl_out[15], 0, z_coordinate_transformation.z_zd_zl_out[15] + 400);
            XYZ hz4 = new XYZ(Windows_Canvas.b_zd_zl_out[9], 0, z_coordinate_transformation.z_zd_zl_out[9] + 400);
            XYZ hz5 = new XYZ(Windows_Canvas.b_zd_zl_out[10], 0, z_coordinate_transformation.z_zd_zl_out[10] + 400);

            //右侧横隔梁坐标点
            XYZ hy1 = new XYZ(Windows_Canvas.b_zd_zl_out[4], 0, z_coordinate_transformation.z_zd_zl_out[4] + 400);
            XYZ hy2 = new XYZ(Windows_Canvas.b_zd_zl_out[5], 0, z_coordinate_transformation.z_zd_zl_out[5] + 400);
            XYZ hy3 = new XYZ(Windows_Canvas.b_zd_zl_out[6], 0, z_coordinate_transformation.z_zd_zl_out[6] + 400);
            XYZ hy4 = new XYZ(Windows_Canvas.b_zd_zl_out[16], 0, z_coordinate_transformation.z_zd_zl_out[16] + 400);
            XYZ hy5 = new XYZ(Windows_Canvas.b_zd_zl_out[18], 0, z_coordinate_transformation.z_zd_zl_out[18] + 400);

            //定义左侧横隔梁
            CurveArrArray Transversebeam_z = app.Create.NewCurveArrArray();
            CurveArray    Transverse_z     = app.Create.NewCurveArray();

            //定义右侧横隔梁
            CurveArrArray Transversebeam_y = app.Create.NewCurveArrArray();
            CurveArray    Transverse_y     = app.Create.NewCurveArray();

            //左侧横隔梁轮廓线
            Curve Tb_outline_z1 = Autodesk.Revit.DB.Line.CreateBound(hz1, hz2);
            Curve Tb_outline_z2 = Autodesk.Revit.DB.Line.CreateBound(hz2, hz3);
            Curve Tb_outline_z3 = Autodesk.Revit.DB.Line.CreateBound(hz3, hz4);
            Curve Tb_outline_z4 = Autodesk.Revit.DB.Line.CreateBound(hz4, hz5);
            Curve Tb_outline_z5 = Autodesk.Revit.DB.Line.CreateBound(hz5, hz1);

            //右侧横隔梁轮廓线
            Curve Tb_outline_y1 = Autodesk.Revit.DB.Line.CreateBound(hy1, hy2);
            Curve Tb_outline_y2 = Autodesk.Revit.DB.Line.CreateBound(hy2, hy3);
            Curve Tb_outline_y3 = Autodesk.Revit.DB.Line.CreateBound(hy3, hy4);
            Curve Tb_outline_y4 = Autodesk.Revit.DB.Line.CreateBound(hy4, hy5);
            Curve Tb_outline_y5 = Autodesk.Revit.DB.Line.CreateBound(hy5, hy1);

            //连接左侧横隔梁轮廓线
            Transverse_z.Append(Tb_outline_z1);
            Transverse_z.Append(Tb_outline_z2);
            Transverse_z.Append(Tb_outline_z3);
            Transverse_z.Append(Tb_outline_z4);
            Transverse_z.Append(Tb_outline_z5);
            Transversebeam_z.Append(Transverse_z);

            //连接右侧横隔梁轮廓线
            Transverse_y.Append(Tb_outline_y1);
            Transverse_y.Append(Tb_outline_y2);
            Transverse_y.Append(Tb_outline_y3);
            Transverse_y.Append(Tb_outline_y4);
            Transverse_y.Append(Tb_outline_y5);
            Transversebeam_y.Append(Transverse_y);

            #region 横隔梁位置信息处理
            double x1 = l0;
            double x3 = (2 * l1 + 2 * l2 + l3) / 2 - (t / 2);
            double x5 = 2 * l1 + 2 * l2 + l3 - l0 - t;
            double x2 = (x1 + x3) / 2;
            double x4 = (x3 + x5) / 2;
            #endregion

            #region  定义横隔梁部分元素名称
            Element Transversebeam1_z = null;
            Element Transversebeam1_y = null;
            Element Transversebeam2_z = null;
            Element Transversebeam2_y = null;
            Element Transversebeam3_z = null;
            Element Transversebeam3_y = null;
            Element Transversebeam4_z = null;
            Element Transversebeam4_y = null;
            Element Transversebeam5_z = null;
            Element Transversebeam5_y = null;
            #endregion

            using (Transaction Transversebeam_stretching = new Transaction(familyDoc))
            {
                if (Transversebeam_stretching.Start("横隔梁拉伸") == TransactionStatus.Started)
                {
                    //左边的横隔梁拉伸1
                    Transversebeam1_z = familyDoc.FamilyCreate.NewExtrusion(true, Transversebeam_z, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), t);
                }
                Transversebeam2_z = familyDoc.FamilyCreate.NewExtrusion(true, Transversebeam_z, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), t);
                Transversebeam3_z = familyDoc.FamilyCreate.NewExtrusion(true, Transversebeam_z, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), t);
                Transversebeam4_z = familyDoc.FamilyCreate.NewExtrusion(true, Transversebeam_z, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), t);
                Transversebeam5_z = familyDoc.FamilyCreate.NewExtrusion(true, Transversebeam_z, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), t);
                Transversebeam1_y = familyDoc.FamilyCreate.NewExtrusion(true, Transversebeam_y, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), t);
                Transversebeam2_y = familyDoc.FamilyCreate.NewExtrusion(true, Transversebeam_y, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), t);
                Transversebeam3_y = familyDoc.FamilyCreate.NewExtrusion(true, Transversebeam_y, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), t);
                Transversebeam4_y = familyDoc.FamilyCreate.NewExtrusion(true, Transversebeam_y, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), t);
                Transversebeam5_y = familyDoc.FamilyCreate.NewExtrusion(true, Transversebeam_y, SketchPlane.Create(familyDoc, Plane.CreateByNormalAndOrigin(XYZ.BasisY, XYZ.Zero)), t);


                //移动到正确的位置
                ElementTransformUtils.MoveElement(familyDoc, Transversebeam1_z.Id, new XYZ(0, x1, 0));
                ElementTransformUtils.MoveElement(familyDoc, Transversebeam2_z.Id, new XYZ(0, x2, 0));
                ElementTransformUtils.MoveElement(familyDoc, Transversebeam3_z.Id, new XYZ(0, x3, 0));
                ElementTransformUtils.MoveElement(familyDoc, Transversebeam4_z.Id, new XYZ(0, x4, 0));
                ElementTransformUtils.MoveElement(familyDoc, Transversebeam5_z.Id, new XYZ(0, x5, 0));
                ElementTransformUtils.MoveElement(familyDoc, Transversebeam1_y.Id, new XYZ(0, x1, 0));
                ElementTransformUtils.MoveElement(familyDoc, Transversebeam2_y.Id, new XYZ(0, x2, 0));
                ElementTransformUtils.MoveElement(familyDoc, Transversebeam3_y.Id, new XYZ(0, x3, 0));
                ElementTransformUtils.MoveElement(familyDoc, Transversebeam4_y.Id, new XYZ(0, x4, 0));
                ElementTransformUtils.MoveElement(familyDoc, Transversebeam5_y.Id, new XYZ(0, x5, 0));
                Transversebeam_stretching.Commit();
            }
            #endregion

            Family family = familyDoc.LoadFamily(Rdoc);
        }
    private void RunScript(List <Plane> iTravelPlanes, List <double> iPositionerRotation, double iTimeline, double iStepResolution, bool iPlaySim, ref object oCurrentTCP, ref object oCurrentTimestep, ref object oPositionerRotation, ref object oTravelPolyline, ref object Debug)
    {
        // <Custom code>
        if (iPlaySim)
        {
            _inc   = iTimeline;
            _len   = 0;
            _poly  = new Polyline();
            _plane = iTravelPlanes[0];
            _ex    = RhinoMath.ToRadians(iPositionerRotation[0]);

            // Step 1: Get the length of the tool path
            foreach (Plane _pl in iTravelPlanes)
            {
                _poly.Add(_pl.Origin);
            }

            _len = _poly.Length;
        }
        else
        {
            _inc += iStepResolution / _len;
            if (_inc > 1)
            {
                _inc = 1;
            }
            else if (_inc < 0)
            {
                _inc = 0;
            }
        }

        // Step 2: Interpolate the plane based on where along the path we are
        Curve _crv = _poly.ToNurbsCurve();

        _pt = _crv.PointAtNormalizedLength(_inc);
        double _param = _poly.ClosestParameter(_pt);
        int    _index = (int)Math.Floor(_param);
        Line   _line  = _poly.SegmentAt(_index);
        double _t     = _line.ClosestParameter(_pt);
        Plane  _P0    = iTravelPlanes[_index];
        double _EX0   = iPositionerRotation[_index];

        Plane  _P1;
        double _EX1;

        if (_index == _poly.SegmentCount)
        {
            _P1  = iTravelPlanes[_index];
            _EX1 = iPositionerRotation[_index];
        }
        else
        {
            _P1  = iTravelPlanes[_index + 1];
            _EX1 = iPositionerRotation[_index + 1];
        }

        Point3d  _origin = _P0.Origin + _t * (_P1.Origin - _P0.Origin);
        Vector3d _xDir   = _P0.XAxis + _t * (_P1.XAxis - _P0.XAxis);
        Vector3d _yDir   = _P0.YAxis + _t * (_P1.YAxis - _P0.YAxis);

        _plane = new Plane(_origin, _xDir, _yDir);
        _ex    = _EX0 + _t * minPI(_EX1 - _EX0);
        Print(minPI(_EX1 - _EX0).ToString());

        oCurrentTCP         = _plane;
        oCurrentTimestep    = Math.Round(_inc * 100, 3);
        oPositionerRotation = _ex;
        oTravelPolyline     = _poly;

        // </Custom code>
    }
        /// <summary>
        /// Exports materials for host object.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="hostObject">The host object.</param>
        /// <param name="elemHnds">The host IFC handles.</param>
        /// <param name="geometryElement">The geometry element.</param>
        /// <param name="productWrapper">The ProductWrapper.</param>
        /// <param name="levelId">The level id.</param>
        /// <param name="direction">The IFCLayerSetDirection.</param>
        /// <param name="containsBRepGeometry">True if the geometry contains BRep geoemtry.  If so, we will export an IfcMaterialList</param>
        /// <returns>True if exported successfully, false otherwise.</returns>
        public static bool ExportHostObjectMaterials(ExporterIFC exporterIFC, HostObject hostObject,
                                                     IList <IFCAnyHandle> elemHnds, GeometryElement geometryElement, ProductWrapper productWrapper,
                                                     ElementId levelId, Toolkit.IFCLayerSetDirection direction, bool containsBRepGeometry, IFCAnyHandle typeHnd = null)
        {
            if (hostObject == null)
            {
                return(true); //nothing to do
            }
            if (elemHnds == null || (elemHnds.Count == 0))
            {
                return(true); //nothing to do
            }
            IFCFile file = exporterIFC.GetFile();

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                double scaledOffset = 0.0, scaledWallWidth = 0.0, wallHeight = 0.0;
                Wall   wall = hostObject as Wall;

                if (wall != null)
                {
                    scaledWallWidth = UnitUtil.ScaleLength(wall.Width);
                    scaledOffset    = -scaledWallWidth / 2.0;
                    BoundingBoxXYZ boundingBox = wall.get_BoundingBox(null);
                    if (boundingBox != null)
                    {
                        wallHeight = boundingBox.Max.Z - boundingBox.Min.Z;
                    }
                }

                MaterialLayerSetInfo mlsInfo          = new MaterialLayerSetInfo(exporterIFC, hostObject, productWrapper);
                IFCAnyHandle         materialLayerSet = mlsInfo.MaterialLayerSetHandle;
                List <ElementId>     materialIds      = mlsInfo.MaterialIds.Select(x => x.m_baseMatId).ToList();

                // Among all the calls of this method the problem of material association absence was found only
                // for CeilingAndFloor host object type (see JIRA item REVIT-164913)
                if (containsBRepGeometry && (hostObject is CeilingAndFloor) &&
                    materialIds.Count > 0 && !ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView)
                {
                    foreach (IFCAnyHandle elemHnd in elemHnds)
                    {
                        CategoryUtil.CreateMaterialAssociation(exporterIFC, elemHnd, materialIds);
                    }
                }

                if (!IFCAnyHandleUtil.IsNullOrHasNoValue(materialLayerSet))
                {
                    // If there is an override for creating IfcMaterial instead of IfcMaterialLayer for a single material/layer, assign the material directly to type or element(s)
                    if (IFCAnyHandleUtil.IsTypeOf(materialLayerSet, IFCEntityType.IfcMaterial))
                    {
                        if (typeHnd != null)
                        {
                            CategoryUtil.CreateMaterialAssociation(typeHnd, materialLayerSet);
                        }

                        foreach (IFCAnyHandle elemHnd in elemHnds)
                        {
                            CategoryUtil.CreateMaterialAssociation(elemHnd, materialLayerSet);
                        }
                    }
                    else
                    {
                        // IfcMaterialLayerSetUsage is not supported for IfcWall, only IfcWallStandardCase.
                        IFCAnyHandle layerSetUsage = null;
                        for (int ii = 0; ii < elemHnds.Count; ii++)
                        {
                            IFCAnyHandle elemHnd = elemHnds[ii];
                            if (IFCAnyHandleUtil.IsNullOrHasNoValue(elemHnd))
                            {
                                continue;
                            }

                            SpaceBoundingElementUtil.RegisterSpaceBoundingElementHandle(exporterIFC, elemHnd, hostObject.Id, levelId);

                            // Even if it is Tessellated geometry in IFC4RV, the material layer will still be assigned
                            if (containsBRepGeometry && !ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView)
                            {
                                continue;
                            }

                            HashSet <IFCAnyHandle> relDecomposesSet = IFCAnyHandleUtil.GetRelDecomposes(elemHnd);

                            IList <IFCAnyHandle> subElemHnds = null;
                            if (relDecomposesSet != null && relDecomposesSet.Count == 1)
                            {
                                IFCAnyHandle relAggregates = relDecomposesSet.First();
                                if (IFCAnyHandleUtil.IsTypeOf(relAggregates, IFCEntityType.IfcRelAggregates))
                                {
                                    subElemHnds = IFCAnyHandleUtil.GetAggregateInstanceAttribute <List <IFCAnyHandle> >(relAggregates, "RelatedObjects");
                                }
                            }

                            bool hasSubElems          = (subElemHnds != null && subElemHnds.Count != 0);
                            bool isRoof               = IFCAnyHandleUtil.IsTypeOf(elemHnd, IFCEntityType.IfcRoof);
                            bool isDisallowedWallType = (IFCAnyHandleUtil.IsTypeOf(elemHnd, IFCEntityType.IfcWall) && !ExporterCacheManager.ExportOptionsCache.ExportAs4);

                            // Create IfcMaterialLayerSetUsage unless we have sub-elements, are exporting a Roof, or are exporting a pre-IFC4 IfcWall.
                            if (!hasSubElems && !isRoof && !isDisallowedWallType)
                            {
                                bool materialAlreadyAssoc = false;
                                if (typeHnd != null)
                                {
                                    CategoryUtil.CreateMaterialAssociation(typeHnd, materialLayerSet);
                                }

                                if (ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView)
                                {
                                    if (!materialAlreadyAssoc)
                                    {
                                        CategoryUtil.CreateMaterialAssociation(elemHnd, materialLayerSet);
                                    }
                                }
                                else
                                {
                                    if (layerSetUsage == null)
                                    {
                                        bool flipDirSense = true;
                                        if (wall != null)
                                        {
                                            // if we have flipped the center curve on export, we need to take that into account here.
                                            // We flip the center curve on export if it is an arc and it has a negative Z direction.
                                            LocationCurve locCurve = wall.Location as LocationCurve;
                                            if (locCurve != null)
                                            {
                                                Curve     curve        = locCurve.Curve;
                                                Transform lcs          = Transform.Identity;
                                                bool      curveFlipped = GeometryUtil.MustFlipCurve(lcs, curve);
                                                flipDirSense = !(wall.Flipped ^ curveFlipped);
                                            }
                                        }
                                        else if (hostObject is CeilingAndFloor)
                                        {
                                            flipDirSense = false;
                                        }

                                        double            offsetFromReferenceLine = flipDirSense ? -scaledOffset : scaledOffset;
                                        IFCDirectionSense sense = flipDirSense ? IFCDirectionSense.Negative : IFCDirectionSense.Positive;

                                        layerSetUsage = CategoryUtil.CreateMaterialLayerSetUsage(file, materialLayerSet, direction, sense, offsetFromReferenceLine);
                                    }
                                    ExporterCacheManager.MaterialSetUsageCache.Add(layerSetUsage, elemHnd);
                                }
                            }
                            else
                            {
                                if (hasSubElems)
                                {
                                    foreach (IFCAnyHandle subElemHnd in subElemHnds)
                                    {
                                        // TODO: still need to figure out the best way to create type for the sub elements because at this time a lot of information is not available, e.g.
                                        //    the Revit Element to get the type, other information for name, GUID, etc.
                                        if (!IFCAnyHandleUtil.IsNullOrHasNoValue(subElemHnd))
                                        {
                                            CategoryUtil.CreateMaterialAssociation(subElemHnd, materialLayerSet);
                                        }
                                    }
                                }
                                else if (!isRoof)
                                {
                                    if (typeHnd != null)
                                    {
                                        CategoryUtil.CreateMaterialAssociation(typeHnd, materialLayerSet);
                                    }
                                    else
                                    {
                                        CategoryUtil.CreateMaterialAssociation(elemHnd, materialLayerSet);
                                    }
                                }
                                else if (mlsInfo.PrimaryMaterialHandle != null)
                                {
                                    if (typeHnd != null)
                                    {
                                        CategoryUtil.CreateMaterialAssociation(typeHnd, materialLayerSet);
                                    }
                                    else
                                    {
                                        CategoryUtil.CreateMaterialAssociation(elemHnd, materialLayerSet);
                                    }
                                }
                            }
                        }
                    }
                }
                tr.Commit();
                return(true);
            }
        }
Beispiel #50
0
 public static Curve Lerp(Curve a, Curve b, double weight) => t => a(t) * (1 - weight) + b(t) * weight;
        private static Transform CreateProfileCurveTransform(ExporterIFC exporterIFC, Curve directrix, double param)
        {
            Transform directrixDirs = directrix.ComputeDerivatives(param, false);
            XYZ       origin        = ExporterIFCUtils.TransformAndScalePoint(exporterIFC, directrixDirs.Origin);

            // We are constructing the profile plane so that the normal matches the curve tangent, and the X matches the curve normal.
            XYZ profilePlaneXDir = ExporterIFCUtils.TransformAndScaleVector(exporterIFC, directrixDirs.BasisZ.Normalize());
            XYZ profilePlaneYDir = ExporterIFCUtils.TransformAndScaleVector(exporterIFC, -directrixDirs.BasisY.Normalize());
            XYZ profilePlaneZDir = ExporterIFCUtils.TransformAndScaleVector(exporterIFC, directrixDirs.BasisX.Normalize());

            Transform profileCurveTransform = Transform.CreateTranslation(origin);

            profileCurveTransform.BasisX = profilePlaneXDir;
            profileCurveTransform.BasisY = profilePlaneYDir;
            profileCurveTransform.BasisZ = profilePlaneZDir;

            return(profileCurveTransform);
        }
Beispiel #52
0
        public Curve buildRack(Line L, Circle C, double Teeth, double Angle, double addendum, double dedendum)
        {
            double M     = (2 * C.Radius) / Teeth;
            double Pitch = Math.PI * M;
            int    time  = (int)(L.Length / Pitch);

            Vector3d dir  = L.Direction; dir.Unitize();
            Vector3d dirA = dir;

            dirA.Rotate(toRadian(90.0 - Angle), C.Normal);
            Vector3d dirB = dir;

            dirB.Rotate(toRadian(-90.0 + Angle), C.Normal);

            addendum = addendum * M;
            dedendum = dedendum * M;

            double slope  = (addendum + dedendum) / Math.Cos(toRadian(Angle));
            double tip    = (Pitch * 0.50) - Math.Tan(Angle) * addendum * 2.0;
            double buttom = (Pitch * 0.5) - Math.Tan(Angle) * dedendum;

            List <Curve> profiles = new List <Curve>();

            profiles.Add(new LineCurve(new Line(L.From, dir * buttom * 0.5)));
            profiles.Add(new LineCurve(new Line(profiles[0].PointAtEnd, dirA * slope)));
            profiles.Add(new LineCurve(new Line(profiles[1].PointAtEnd, dir * tip)));
            profiles.Add(new LineCurve(new Line(profiles[2].PointAtEnd, dirB * slope)));
            profiles.Add(new LineCurve(new Line(profiles[3].PointAtEnd, dir * buttom * 0.5)));

            Transform move = Transform.Translation(Vector3d.CrossProduct(dir, C.Normal) * dedendum);
            Curve     rack = Curve.JoinCurves(profiles, 0.01, true)[0];

            rack.Transform(move);

            //Display
            locations.Add(rack.PointAtNormalizedLength(0.5));
            texts.Add(Math.Round(tip, 2).ToString());
            sizes.Add(Pitch * 4);

            List <Curve> racks = new List <Curve>();

            for (int i = 0; i < time + 1; i++)
            {
                Transform duplicate = Transform.Translation(dir * Pitch * i);
                Curve     thisC     = rack.DuplicateCurve();
                thisC.Transform(duplicate);
                racks.Add(thisC);
            }

            //align
            var    ccx     = Rhino.Geometry.Intersect.Intersection.CurveCurve(new LineCurve(L), new ArcCurve(C), 0.1, 0.1);
            double align_d = dedendum * Math.Tan(toRadian(Angle)) + tip + addendum / Math.Tan(toRadian(90 - Angle)) * 2 + buttom * 0.5;

            align_d += Math.Floor(ccx[0].PointA.DistanceTo(L.From + dir * align_d) / Pitch) * Pitch;
            Point3d   closet = L.From + dir * align_d;
            Transform align  = Transform.Translation(ccx[0].PointA - closet);

            rack = Curve.JoinCurves(racks, 1, true)[0];
            rack.Transform(align);
            return(rack);
        }
Beispiel #53
0
        /**
         * Generate the last resort PreKey.  Clients should do this only once, at install
         * time, and durably store it for the length of the install.
         *
         * @return the generated last resort PreKeyRecord.
         */
        public static PreKeyRecord generateLastResortPreKey()
        {
            ECKeyPair keyPair = Curve.generateKeyPair();

            return(new PreKeyRecord(Medium.MAX_VALUE, keyPair));
        }
        public override void SolveInstance(IGH_DataAccess DA, out string msg, out GH_RuntimeMessageLevel level)
        {
            msg   = "";
            level = GH_RuntimeMessageLevel.Blank;
            //var line = new LineCurve();
            Curve inCurve    = null;
            var   noIndex    = 0;
            var   comment    = "";
            var   rFMember   = new RFMember();
            var   inRFEM     = new GH_RFEM();
            var   mod        = false;
            var   del        = false;
            var   lineNo     = 0;
            var   memberType = 0;
            var   taperType  = 0;
            var   rotAngle   = 0.0;
            //var intPoints = 4;
            var sCS = 0;
            var eCS = 0;
            var sH  = 0;
            var eH  = 0;
            var ecc = 0;
            var div = 0;

            //int newNo = 0;

            if (DA.GetData(15, ref inRFEM))
            {
                rFMember = new RFMember((RFMember)inRFEM.Value);
                if (DA.GetData(1, ref sCS))
                {
                    rFMember.StartCrossSectionNo = sCS;
                }
                if (DA.GetData(0, ref inCurve))
                {
                    var myRFLine = new RFLine();
                    Component_RFLine.SetGeometry(inCurve, ref myRFLine);
                    rFMember.SetFrames();
                }
                if (DA.GetData(1, ref sCS))
                {
                    rFMember.StartCrossSectionNo = sCS;
                }
            }
            else if (DA.GetData(0, ref inCurve) && DA.GetData(1, ref sCS))
            {
                var myRFLine = new RFLine();
                Component_RFLine.SetGeometry(inCurve, ref myRFLine);
                rFMember.BaseLine = myRFLine;
                rFMember.SetFrames();
                rFMember.StartCrossSectionNo = sCS;
            }
            else
            {
                msg   = "Insufficient input parameters. Provide either Input Curve and Start Cross Section or existing RFMember Object. ";
                level = GH_RuntimeMessageLevel.Warning;
                return;
            }
            if (DA.GetData(16, ref mod))
            {
                rFMember.ToModify = mod;
            }
            if (DA.GetData(17, ref del))
            {
                rFMember.ToDelete = del;
            }
            if (DA.GetData(2, ref noIndex))
            {
                rFMember.No = noIndex;
            }
            if (DA.GetData(3, ref comment))
            {
                rFMember.Comment = comment;
            }
            if (DA.GetData(4, ref lineNo))
            {
                rFMember.LineNo = lineNo;
            }
            if (DA.GetData(5, ref memberType))
            {
                rFMember.Type = (MemberType)memberType;
                if (rFMember.Type == MemberType.UnknownMemberType)
                {
                    msg   = "Member Type not supported. ";
                    level = GH_RuntimeMessageLevel.Warning;
                    return;
                }
            }
            if (DA.GetData(6, ref rotAngle))
            {
                rFMember.RotationType  = RotationType.Angle;
                rFMember.RotationAngle = rotAngle;
            }
            if (DA.GetData(7, ref eCS))
            {
                rFMember.EndCrossSectionNo = eCS;
            }
            if (DA.GetData(8, ref sH))
            {
                rFMember.StartHingeNo = sH;
            }
            if (DA.GetData(9, ref eH))
            {
                rFMember.EndHingeNo = eH;
            }
            if (DA.GetData(10, ref ecc))
            {
                rFMember.EccentricityNo = ecc;
            }
            if (DA.GetData(11, ref div))
            {
                rFMember.DivisionNo = div;
            }
            if (DA.GetData(12, ref taperType))
            {
                rFMember.TaperShape = (TaperShapeType)taperType;
                if (rFMember.TaperShape == TaperShapeType.UnknownTaperShape)
                {
                    msg   = "Taper Shape Type not supported. ";
                    level = GH_RuntimeMessageLevel.Warning;
                    return;
                }
            }
            DA.SetData(0, rFMember);
        }
Beispiel #55
0
        /**
         * Generate a list of PreKeys.  Clients should do this at install time, and
         * subsequently any time the list of PreKeys stored on the server runs low.
         * <p>
         * PreKey IDs are shorts, so they will eventually be repeated.  Clients should
         * store PreKeys in a circular buffer, so that they are repeated as infrequently
         * as possible.
         *
         * @param start The starting PreKey ID, inclusive.
         * @param count The number of PreKeys to generate.
         * @return the list of generated PreKeyRecords.
         */
        public static IList <PreKeyRecord> generatePreKeys(uint start, uint count)
        {
            IList <PreKeyRecord> results = new List <PreKeyRecord>();

            start--;

            for (uint i = 0; i < count; i++)
            {
                results.Add(new PreKeyRecord(((start + i) % (Medium.MAX_VALUE - 1)) + 1, Curve.generateKeyPair()));
            }

            return(results);
        }
Beispiel #56
0
 public static ECKeyPair generateSenderSigningKey()
 {
     return(Curve.generateKeyPair());
 }
Beispiel #57
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            //Reference adaptive = uidoc.Selection.PickObject(ObjectType.Element, "Select adaptive family");

            //Element adaptiveEle = doc.GetElement(adaptive);

            //PlanarFace pf = GetFace(adaptiveEle);

            //TaskDialog.Show("tr", "I am done");

            //TaskDialog.Show("tr", "so done");

            //TaskDialog.Show("tr", "done done");


            List <RG.Point3d> pts = new List <RG.Point3d> {
                new RG.Point3d(0, 0, 0), new RG.Point3d(5, 10, 0), new RG.Point3d(15, 5, 0), new RG.Point3d(20, 0, 0)
            };


            RG.PolylineCurve pc = new RG.PolylineCurve(pts);

            RG.Interval d = pc.Domain;

            //TaskDialog.Show("r", d.ToString());

            RG.NurbsCurve value = pc.ToNurbsCurve();

            value.IncreaseDegree(3);

            int newDegree     = 3;
            var degree        = value.Degree;
            var knots         = ToDoubleArray(value.Knots, newDegree);
            var controlPoints = ToXYZArray(value.Points, 1);
            var weights       = value.Points.ConvertAll(x => x.Weight);

            XYZ normal = new XYZ(0, 0, 1);
            XYZ origin = new XYZ(0, 0, 0);

            Plane rvtPlane = Plane.CreateByNormalAndOrigin(normal, origin);


            string knot = "";

            foreach (var item in knots)
            {
                knot += item.ToString() + "\n";
            }

            //TaskDialog.Show("r", knot);

            //TaskDialog.Show("R", $"ControlPoints > Degree: {controlPoints.Length} > {degree}\nKnots = degree + control points + 1 = {controlPoints.Length + degree + 1} ");

            Curve rvtN = NurbSpline.CreateCurve(newDegree, knots, controlPoints);

            //Trace.WriteLine()
            using (Transaction t = new Transaction(doc, "a"))
            {
                t.Start();
                SketchPlane sketchPlane = SketchPlane.Create(doc, rvtPlane);
                doc.Create.NewModelCurve(rvtN, sketchPlane);

                t.Commit();
            }

            return(Result.Succeeded);
        }
Beispiel #58
0
        private void createTicks()
        {
            if (TickDistance == 0)
            {
                return;
            }

            var length       = Curve.Distance;
            var tickDistance = Math.Min(TickDistance, length);
            var spanDuration = length / Velocity;

            var minDistanceFromEnd = Velocity * 0.01;

            AddNested(new Fruit
            {
                Samples   = Samples,
                StartTime = StartTime,
                X         = X
            });

            double lastDropletTime = StartTime;

            for (int span = 0; span < this.SpanCount(); span++)
            {
                var spanStartTime = StartTime + span * spanDuration;
                var reversed      = span % 2 == 1;

                for (double d = 0; d <= length; d += tickDistance)
                {
                    var timeProgress     = d / length;
                    var distanceProgress = reversed ? 1 - timeProgress : timeProgress;

                    double time = spanStartTime + timeProgress * spanDuration;

                    if (LegacyLastTickOffset != null)
                    {
                        // If we're the last tick, apply the legacy offset
                        if (span == this.SpanCount() - 1 && d + tickDistance > length)
                        {
                            time = Math.Max(StartTime + Duration / 2, time - LegacyLastTickOffset.Value);
                        }
                    }

                    double tinyTickInterval = time - lastDropletTime;
                    while (tinyTickInterval > 100)
                    {
                        tinyTickInterval /= 2;
                    }

                    for (double t = lastDropletTime + tinyTickInterval; t < time; t += tinyTickInterval)
                    {
                        double progress = reversed ? 1 - (t - spanStartTime) / spanDuration : (t - spanStartTime) / spanDuration;

                        AddNested(new TinyDroplet
                        {
                            StartTime = t,
                            X         = X + Curve.PositionAt(progress).X / CatchPlayfield.BASE_WIDTH,
                            Samples   = new List <SampleInfo>(Samples.Select(s => new SampleInfo
                            {
                                Bank   = s.Bank,
                                Name   = @"slidertick",
                                Volume = s.Volume
                            }))
                        });
                    }

                    if (d > minDistanceFromEnd && Math.Abs(d - length) > minDistanceFromEnd)
                    {
                        AddNested(new Droplet
                        {
                            StartTime = time,
                            X         = X + Curve.PositionAt(distanceProgress).X / CatchPlayfield.BASE_WIDTH,
                            Samples   = new List <SampleInfo>(Samples.Select(s => new SampleInfo
                            {
                                Bank   = s.Bank,
                                Name   = @"slidertick",
                                Volume = s.Volume
                            }))
                        });
                    }

                    lastDropletTime = time;
                }

                AddNested(new Fruit
                {
                    Samples   = Samples,
                    StartTime = spanStartTime + spanDuration,
                    X         = X + Curve.PositionAt(reversed ? 0 : 1).X / CatchPlayfield.BASE_WIDTH
                });
            }
        }
Beispiel #59
0
        public static Curve RatchetPawl(Circle C, int T, double D, int pawlCount, double pRad, double Spring, out Curve SpringPawl)
        {
            List <Curve>  rachets = new List <Curve>();
            List <Curve>  paws    = new List <Curve>();
            List <double> split   = new List <double>();

            for (int i = 0; i < T; i++)
            {
                double ta = (Math.PI * 2 / T) * i;
                double tb = (Math.PI * 2 / T) * ((i + 1) % T);
                //teeth build
                Point3d  start = new Circle(C.Plane, C.Radius - D).PointAt(ta); //fillet corner point
                Vector3d va    = C.PointAt(ta) - start; va.Unitize();
                Vector3d vb    = C.PointAt(tb) - start; vb.Unitize();
                Curve    lineA = new LineCurve(C.PointAt(ta), start);
                Curve    lineB = new LineCurve(C.PointAt(tb), start);
                Curve    teeth = Curve.CreateFilletCurves(lineA, start + (va * 0.1), lineB, start + (vb * 0.1), 0.2, true, true, true, 0.01, 0.01)[0];
                rachets.Add(teeth);

                //pawl build
                double t_paw = (double)T / (double)pawlCount;
                if (i == 0 || i + 1 > paws.Count * t_paw)
                {
                    ArcCurve innC = new ArcCurve(new Circle(C.Plane, C.Radius - D - pRad));
                    Point3d  pawP = start + (va * (D - 0.2));

                    double   side = Math.Sqrt(Math.Pow(C.Center.DistanceTo(pawP), 2) - Math.Pow(innC.Radius, 2));
                    ArcCurve tanC = new ArcCurve(new Circle(pawP, side));

                    //diection
                    var     ccx = Rhino.Geometry.Intersect.Intersection.CurveCurve(innC, tanC, 0.1, 0.1);
                    Point3d tanP;
                    if (i == 0)
                    {
                        tanP = ccx[1].PointA;
                    }
                    else
                    {
                        tanP = ccx[0].PointA;
                    }

                    List <double> angle  = Trigonometry(C.Center.DistanceTo(pawP), pawP.DistanceTo(tanP), innC.Radius, TrigLaw.SSS, Traingle.Angle);
                    Point3d       depthP = pawP + ((Spring / Math.Sin(angle[1])) * Math.Tan(angle[1]) * -va);

                    Vector3d tan2cen = C.Center - tanP; tan2cen.Unitize();
                    Vector3d springY = Vector3d.CrossProduct(tan2cen, C.Normal); springY.Unitize();

                    //pawl teeth
                    List <Point3d> points = new List <Point3d> {
                        tanP + (tan2cen * Spring), depthP, pawP, tanP
                    };
                    PolylineCurve pawl = new PolylineCurve(points);

                    //spring arc
                    ArcCurve  springArc = new ArcCurve(new Arc(tanP + (tan2cen * Spring), tanP + (tan2cen * Spring * 1.5) - springY * Spring * 0.5, tanP + (tan2cen * Spring * 2)));
                    Transform xform     = Transform.Rotation(-Math.PI / (pawlCount * 3), C.Normal, C.Center);
                    springArc.Transform(xform);
                    ArcCurve extendSpring = new ArcCurve(new Arc(tanP + (tan2cen * Spring), tanP - pawP, springArc.PointAtStart));
                    ArcCurve clipSpring   = new ArcCurve(new Arc(tanP + (tan2cen * Spring) + tan2cen * Spring, tanP - pawP, springArc.PointAtEnd));
                    clipSpring.Reverse();

                    //innC intersection
                    Line    innRay  = new Line(clipSpring.PointAtEnd, clipSpring.PointAtEnd - (tanP - pawP) * 2);
                    Point3d rayStop = Point3d.Unset;
                    double  clt;
                    var     clx = Rhino.Geometry.Intersect.Intersection.LineCircle(innRay, new Circle(C.Plane, C.Radius - D - pRad),
                                                                                   out clt, out rayStop, out clt, out rayStop);
                    LineCurve innSpring = new LineCurve(clipSpring.PointAtEnd, rayStop);
                    paws.Add(Curve.JoinCurves(new List <Curve> {
                        pawl, extendSpring, springArc, clipSpring, innSpring
                    })[0]);

                    //split t values
                    double splitA; double splitB;
                    new ArcCurve(new Circle(C.Plane, C.Radius - D - pRad)).ClosestPoint(rayStop, out splitA);
                    new ArcCurve(new Circle(C.Plane, C.Radius - D - pRad)).ClosestPoint(tanP, out splitB);

                    split.Add(splitA); split.Add(splitB);
                }
            }

            ArcCurve innCircle = new ArcCurve(new Circle(C.Plane, C.Radius - D - pRad));

            Curve[] shatter = innCircle.Split(split);
            for (int i = 0; i < shatter.Length; i += 2)
            {
                paws.Add(shatter[i]);
            }

            SpringPawl = Curve.JoinCurves(paws)[0];
            return(Curve.JoinCurves(rachets)[0]);
        }
Beispiel #60
0
 private bool IsInsideShape(Shape shape, Point p)
 {
     return(Curve.PointRelativeToCurveLocation(p, shape.BoundaryCurve) == PointLocation.Inside &&
            shape.Children.All(ch => Curve.PointRelativeToCurveLocation(p, ch.BoundaryCurve) == PointLocation.Outside));
 }