Affine is a class used to perform Affine transforms on a matrix. Affine transforms are those which can be mathematically reversed. Examples include translation, scaling, shearing, and the like.
Example #1
0
        public Affine EcAffinify(Projective s)
        {
            Contract.Assert(!s.z.IsZero());

            var lambda = s.z.ModInv(p, negP);
            var lambda2 = modp(lambda * lambda);
            var lambda3 = modp(lambda2 * lambda);

            var res = new Affine() { x = modp(lambda2 * s.x), y = modp(lambda3 * s.y) };
            lambda.Clear();
            lambda2.Clear();
            lambda3.Clear();
            return res;
        }
Example #2
0
 public Projective EcProjectify(Affine s)
 {
     return new Projective() { x = s.x, y = s.y, z = new BigInt(1, s.x.Length) };
 }
Example #3
0
        public string getFriendListData(long uid, long pid, Affine.Utils.ConstsUtil.FriendListModes mode, int skip = 0, int take = 50, long contextUserSettingsKey = 0)
        {
            take = TakeGaurd(take, 50);
            aqufitEntities entities = new aqufitEntities();
            UserSettings settings = entities.UserSettings.FirstOrDefault(s => s.UserKey == uid && s.PortalKey == pid);
            long[] friendIds = null;
            // TODO: we can not do an orderby at the "id" level to do a skip take..
            if (mode == Utils.ConstsUtil.FriendListModes.FOLLOWING)
            {   // Folling is (user as SRC) + RelationShip == FOLLOWING
                friendIds = entities.UserFriends.Where(f => f.SrcUserSettingKey == settings.Id && f.Relationship == (int)Affine.Utils.ConstsUtil.Relationships.FOLLOW ).Select(f => f.DestUserSettingKey).ToArray();
            }
            else if (mode == Utils.ConstsUtil.FriendListModes.FOLLOWERS)
            {
                friendIds = entities.UserFriends.Where(f => f.DestUserSettingKey == settings.Id && f.Relationship == (int)Affine.Utils.ConstsUtil.Relationships.FOLLOW).Select(f => f.SrcUserSettingKey).ToArray();
            }
            else
            {   // Friend is (user as SRC or DST) + RelationShip == FRIEND
                friendIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == settings.Id || f.DestUserSettingKey == settings.Id) && f.Relationship == (int)Affine.Utils.ConstsUtil.Relationships.FRIEND).Select(f => f.SrcUserSettingKey == settings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey).ToArray();
            }
            UserSettings[] friendList = entities.UserSettings.OfType<User>().Where(LinqUtils.BuildContainsExpression<UserSettings, long>(us => us.Id, friendIds)).OrderBy(f => f.UserName).Skip(skip).Take(take).ToArray();
            if (contextUserSettingsKey == 0 || contextUserSettingsKey == settings.Id)
            {
                // This is kinda messed here... since request status is 0 if they are not friends
                Affine.Data.json.UserSetting[] ret = friendList.Select(f => new Affine.Data.json.UserSetting() { Id = f.Id, FirstName = f.UserFirstName, LastName = f.UserLastName, UserKey = f.UserKey, PortalKey = f.PortalKey, UserName = f.UserName,
                                                                                                                 RequestStatus = 0  // alread friends (since this is a request for that users friends)
                }).ToArray();
                var data = new { Data = ret, PagerInfo = new { Skip = skip, Take = take, Length = friendIds.Length } };
                string json = _jserializer.Serialize(data);
                return json;
            }
            else
            {
                Affine.Data.json.UserSetting[] ret = friendList.Where(f => f.Id != contextUserSettingsKey).Select(f => new Affine.Data.json.UserSetting()
                {
                    Id = f.Id,
                    FirstName = f.UserFirstName,
                    LastName = f.UserLastName,
                    UserKey = f.UserKey,
                    PortalKey = f.PortalKey,
                    UserName = f.UserName,
                    RequestStatus = (entities.UserRequestSet.OfType<FriendRequest>().Where(rs => (rs.UserSetting.Id == contextUserSettingsKey && rs.FriendRequestSettingsId == f.Id) || (rs.UserSetting.Id == f.Id && rs.FriendRequestSettingsId == contextUserSettingsKey)).FirstOrDefault() == null ? -1 : entities.UserRequestSet.OfType<FriendRequest>().Where(rs => (rs.UserSetting.Id == contextUserSettingsKey && rs.FriendRequestSettingsId == f.Id) || (rs.UserSetting.Id == f.Id && rs.FriendRequestSettingsId == contextUserSettingsKey)).FirstOrDefault().Status.Value)
                }).ToArray();

                var data = new { Data = ret, PagerInfo = new { Skip = skip, Take = take, Length = friendIds.Length } };
                string json = _jserializer.Serialize(data);
                return json;
            }
        }
Example #4
0
        public void Ecdh(BigInt publicX, BigInt publicY, RandomNumberGenerator rng, out byte[] preMasterSecret, out Affine publicPoint)
        {
            var limbLen = (curveByteLen + 3) >> 2;

            var priv = GenPriv(rng);

            var serverPublic = new EllipticCurve.Projective() { x = publicX, y = publicY, z = new EllipticCurve.BigInt(1, limbLen) };
            var commonSecretProj = EcMult(priv, serverPublic);
            var commonSecretAff = EcAffinify(commonSecretProj);
            serverPublic.Clear();
            commonSecretProj.Clear();

            var g = new EllipticCurve.Projective() { x = xg, y = yg, z = new EllipticCurve.BigInt(1, limbLen) };
            var pubProj = EcMult(priv, g);
            var pubAff = EcAffinify(pubProj);
            priv.Clear();
            pubProj.Clear();

            preMasterSecret = commonSecretAff.x.ExportToBigEndian(curveByteLen);
            commonSecretAff.Clear();

            publicPoint = pubAff;
        }
 private void SetupUnit(Affine.Utils.UnitsUtil.MeasureUnit unit)
 {
     switch (unit)
     {
         case Affine.Utils.UnitsUtil.MeasureUnit.UNIT_CM:
             ddlUnitsType.Items.Add(new ListItem("cm", "" + (int)Affine.Utils.UnitsUtil.MeasureUnit.UNIT_CM));
             break;
         case Affine.Utils.UnitsUtil.MeasureUnit.UNIT_INCHES:
             ddlUnitsType.Items.Add(new ListItem("in", "" + (int)Affine.Utils.UnitsUtil.MeasureUnit.UNIT_INCHES));
             break;
         case Affine.Utils.UnitsUtil.MeasureUnit.UNIT_KG:
             ddlUnitsType.Items.Add(new ListItem("Kg", "" + (int)Affine.Utils.UnitsUtil.MeasureUnit.UNIT_KG));
             break;
         case Affine.Utils.UnitsUtil.MeasureUnit.UNIT_KM:
             ddlUnitsType.Items.Add(new ListItem("KM", "" + (int)Affine.Utils.UnitsUtil.MeasureUnit.UNIT_KM));
             break;
         case Affine.Utils.UnitsUtil.MeasureUnit.UNIT_LBS:
             ddlUnitsType.Items.Add(new ListItem("lbs", "" + (int)Affine.Utils.UnitsUtil.MeasureUnit.UNIT_LBS));
             break;
         case Affine.Utils.UnitsUtil.MeasureUnit.UNIT_M:
             ddlUnitsType.Items.Add(new ListItem("M", "" + (int)Affine.Utils.UnitsUtil.MeasureUnit.UNIT_M));
             break;
         case Affine.Utils.UnitsUtil.MeasureUnit.UNIT_MILES:
             ddlUnitsType.Items.Add(new ListItem("Mi", "" + (int)Affine.Utils.UnitsUtil.MeasureUnit.UNIT_MILES));
             break;
         case Affine.Utils.UnitsUtil.MeasureUnit.UNIT_FT_IN:
             ddlUnitsType.Items.Add(new ListItem("ft/in", "" + (int)Affine.Utils.UnitsUtil.MeasureUnit.UNIT_FT_IN));
             break;
         default:
             throw new Affine.Utils.InvalidUnitsException("Unknown Units: ATI_UnitControl.SetupUnit");
     }
 }
Example #6
0
        public long SaveRecipe(long uid, long pid, Affine.Data.json.StreamData recipe)
        {
            aqufitEntities entities = new aqufitEntities();
            UserSettings settings = entities.UserSettings.FirstOrDefault(us => us.UserKey == uid && us.PortalKey == pid);
            Recipe r = null;
            RecipeExtended re = null;
            if (recipe.Id > 0)
            {
                r = entities.UserStreamSet.OfType<Recipe>().Include("RecipeExtendeds").FirstOrDefault(us => us.UserSetting.UserKey == uid && us.PortalKey == pid && us.Id == recipe.Id);
                re = r.RecipeExtendeds.First();
                RecipeIngredient[] riOld = entities.RecipeIngredients.Where(ri => ri.RecipeExtended.Id == re.Id).ToArray();
                foreach (RecipeIngredient ri in riOld)
                {
                    entities.DeleteObject(ri);  // delete and re add new ing
                }
            }else{
                r = new Recipe();
                re = new RecipeExtended();
                re.NumRatings = 1;
                re.NumStrictness = 1;
                re.UserStream = r;
                entities.AddToUserStreamSet(r);
                r.Date = DateTime.Now.ToUniversalTime();
            }
            r.PortalKey = pid;
            r.UserSetting = settings;
            r.TimeStamp = DateTime.Now.ToUniversalTime();
            r.Title = recipe.Title;
            r.Description = recipe.Description;
            r.AvrStrictness = recipe.AvrStrictness;
            r.AvrRating = recipe.AvrRating;
            r.NumServings = recipe.NumServings;
            r.Tags = recipe.Tags;
            r.TimeCook = recipe.TimeCook;
            r.TimePrep = recipe.TimePrep;
            re.Directions = recipe.RecipeExtended.Directions;
            RecipeIngredient[] riArray = recipe.RecipeExtended.Ingredients.Select(i => new RecipeIngredient() { Text = i.Name, RecipeExtended = re }).ToArray();
            entities.SaveChanges();

            // Update the metrics for this user
            if (recipe.Id == 0) // if thie is NOT an edit
            {
                Metric met = entities.Metrics.FirstOrDefault(m => m.UserSetting.UserKey == uid && m.UserSetting.PortalKey == pid && m.MetricType == (int)Affine.Utils.MetricUtil.MetricType.NUM_RECIPES);
                if (met == null)
                {
                    met = new Metric()
                    {
                        UserSetting = settings,
                        MetricType = (int)Affine.Utils.MetricUtil.MetricType.NUM_RECIPES,
                        MetricValue = "1"       // This is the first recipe they have saved
                    };
                    entities.AddToMetrics(met);
                }
                else
                {
                    met.MetricValue = "" + (Convert.ToInt32(met.MetricValue) + 1);
                }
                entities.SaveChanges();
                UserStream ret = entities.UserStreamSet.OfType<Recipe>().Where(u => u.PortalKey == pid && u.UserSetting.UserKey == uid).OrderByDescending(u => u.Id).FirstOrDefault();
                return ret.Id;

            }
            return recipe.Id;
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        // CA - this will need to be cleaned up a lot.. but here is the iteration one version
        // ** People can view workouts in 4 modes (everyone, watchlist, friends, just them)
        //     -In the case of running, cycling, swimming, and STANDARD crossfit Wods... we are going to
        //      be storing peoples best times for (distance rnages) and standard wods... so in these cases
        //      we can shorted the query time when we do an "everyone" query
        //     -Watch list and friends we do the work of getting every time that person did the workout.. not just
        //      there best times.
        //     -Same for the (you only) view
        //        
        private void LoadFlexDataForWorkout(Workout workout, Affine.Utils.ConstsUtil.GraphContext context)
        {
            Affine.Data.Managers.IDataManager dataManager = Affine.Data.Managers.LINQ.DataManager.Instance;

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            // onload we send friend, watch, and group member data that is needed to the app
            aqufitEntities entities = new aqufitEntities();
            IList<long> friendIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == ProfileSettings.Id || f.DestUserSettingKey == ProfileSettings.Id)).Select(f => (f.SrcUserSettingKey == ProfileSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey)).ToList();
            friendIds.Add(ProfileSettings.Id);

            // send the persons profile through
            var profile = new { UserName = ProfileSettings.UserName, Id = ProfileSettings.Id, FirstName = ProfileSettings.UserFirstName, LastName= ProfileSettings.UserLastName };
            hiddenProfileJson.Value = serializer.Serialize(profile);

            var friends = entities.UserSettings.OfType<User>().Where(LinqUtils.BuildContainsExpression<User, long>(s => s.Id, friendIds)).Select(u => new { Id = u.Id, Un = u.UserName, Fn = u.UserFirstName, Ln = u.UserLastName }).ToArray();
            hiddenFriendJson.Value = serializer.Serialize(friends);
            // get groups
            long[] groupIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == ProfileSettings.Id || f.DestUserSettingKey == ProfileSettings.Id) && f.Relationship > 0).Select(f => f.SrcUserSettingKey == ProfileSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey).ToArray();
            UserSettings[] groupList = entities.UserSettings.OfType<Group>().Where(LinqUtils.BuildContainsExpression<UserSettings, long>(us => us.Id, groupIds)).OrderBy(f => f.UserName).ToArray();
            var groups = entities.UserSettings.OfType<Group>().Where(LinqUtils.BuildContainsExpression<Group, long>(s => s.Id, groupIds)).Select(u => new { Id = u.Id, Un = u.UserName }).ToArray();
            hiddenGroupJson.Value = serializer.Serialize(groups);
            // next we load the workout compare to all (friends)

            Affine.WebService.StreamService ss = new WebService.StreamService();

            //hiddenWorkout.Value = ss.getWorkout(workout.Id);
            Affine.Data.json.Workout jsonWorkout = dataManager.workoutToJsonWorkout(workout);
            Affine.Data.json.WOD wod = null;
            Affine.Data.json.WorkoutData[] jsonWorkoutData = null;
            //var workoutJson = new { Id = workout.Id, WorkoutTypeKey = workout.WorkoutTypeKey, Title = workout.Title, Date = workout.Date.ToLocalTime().ToShortDateString(), DataSrc = workout.DataSrc };

            Affine.Utils.UnitsUtil.MeasureUnit weight = base.WeightUnits;
            if (workout.WorkoutTypeKey == (int)Affine.Utils.WorkoutUtil.WorkoutType.CROSSFIT)
            {
                if (context == Utils.ConstsUtil.GraphContext.DEFAULT)
                {   // default context for crossfit is the watchlist
                    context = Utils.ConstsUtil.GraphContext.WATCHLIST;
                }
                // if this is a crossfit workout
                // we want to get ALL the same WoDs for you and your friends
                IQueryable<Workout> workoutDataQuery = context == Utils.ConstsUtil.GraphContext.EVERYONE ?
                                    entities.UserStreamSet.Include("UserSettings").OfType<Workout>().Where(w => w.WOD.Id == workout.WOD.Id).AsQueryable()
                                    :
                                    context == Utils.ConstsUtil.GraphContext.WATCHLIST ?
                                    entities.UserStreamSet.Include("UserSettings").OfType<Workout>().Where(w => w.WOD.Id == workout.WOD.Id).Where(LinqUtils.BuildContainsExpression<Workout, long>(w => w.UserSetting.Id, friendIds)).AsQueryable()
                                    :
                                    context == Utils.ConstsUtil.GraphContext.FRIENDS ?
                                    entities.UserStreamSet.Include("UserSettings").OfType<Workout>().Where(w => w.WOD.Id == workout.WOD.Id).Where(LinqUtils.BuildContainsExpression<Workout, long>(w => w.UserSetting.Id, friendIds)).AsQueryable()
                                    :
                                    entities.UserStreamSet.Include("UserSettings").OfType<Workout>().Where(w => w.WOD.Id == workout.WOD.Id && w.UserSetting.Id == ProfileSettings.Id ).AsQueryable();
                var workoutData = workoutDataQuery.Select(w => new { Id = w.Id, UsKey = w.UserSetting.Id, Un = w.UserSetting.UserName, T = w.Duration, S = w.Score, M = w.Max, Rx = w.RxD, D = w.Date }).ToArray();
                wod = new Affine.Data.json.WOD (){ Id = workout.WOD.Id, Standard = workout.WOD.Standard, Type = workout.WOD.WODType.Id, Name = workout.WOD.Name, Description = workout.WOD.Description };
                if (wod.Type == (int)Affine.Utils.WorkoutUtil.WodType.TIMED)
                {   // time in sec
                    jsonWorkoutData = workoutData.OrderByDescending(w => w.T).Select(w => new Affine.Data.json.WorkoutData() { UId = w.Un + "_" + w.Id, Id = w.Id, S = (double)w.T, Un = w.Un, D = w.D.ToLocalTime().ToShortDateString(), Rx = (w.Rx.HasValue ? w.Rx.Value : false) }).ToArray();
                }
                else if (wod.Type == (int)Affine.Utils.WorkoutUtil.WodType.MAX_WEIGHT)
                {
                    jsonWorkoutData = workoutData.OrderByDescending(w => w.M).Select(w => new Affine.Data.json.WorkoutData() { UId = w.Un + "_" + w.Id, Id = w.Id, S = Math.Round(Affine.Utils.UnitsUtil.systemDefaultToUnits(Convert.ToDouble(w.M), weight), 2), Un = w.Un, D = w.D.ToLocalTime().ToShortDateString(), Rx = (w.Rx.HasValue ? w.Rx.Value : false) }).ToArray();
                }
                else
                {
                    jsonWorkoutData = workoutData.OrderByDescending(w => w.S).Select(w => new Affine.Data.json.WorkoutData() { UId = w.Un + "_" + w.Id , Id = w.Id, S = Math.Round(Convert.ToDouble(w.S), 2), Un = w.Un, D = w.D.ToLocalTime().ToShortDateString(), Rx = (w.Rx.HasValue ? w.Rx.Value : false) }).ToArray();
                }
            }
            else
            {   // for now this will handle "running, swimming, walking, cycling"
                if (context == Utils.ConstsUtil.GraphContext.DEFAULT)
                {
                    if (workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.MANUAL_NO_MAP || workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.MANUAL_WITH_MAP)
                    {
                        context = Utils.ConstsUtil.GraphContext.EVERYONE;
                    }
                    else if (workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.NIKE_NO_MAP)
                    {
                        context = Utils.ConstsUtil.GraphContext.WATCHLIST;
                    }
                    // TODO: not sure about this one....
                    /*
                else if (workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.MANUAL_WITH_MAP)
                {   // TODO: ?? this is a special case that we want to compare all the times of people that have logged a run for the route.
                    long mapRouteKey = entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workout.Id).Select(w => w.WorkoutExtendeds.FirstOrDefault().MapRoute.Id).FirstOrDefault();
                    IQueryable<Workout> workoutQuery = entities.WorkoutExtendeds.Include("UserStream").Where(we => we.MapRoute != null && we.MapRoute.Id == mapRouteKey).Select(we => we.UserStream).OfType<Workout>().OrderBy(w => w.Duration).Take(5000);
                    workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here.
                    Workout[] data = workoutQuery.ToArray();
                    var wd = data.OrderByDescending(w => w.Duration).Select(w => new
                    {
                        UId = w.UserSetting.UserName + "_" + w.Id,
                        Id = w.Id,
                        S = w.Duration,
                        Un = w.UserSetting.UserName,
                        D = w.Date.ToLocalTime().ToShortDateString()
                    }).ToArray();
                    var ret = new { WOD = new { }, WorkoutData = wd, Workout = workoutJson, Context = (int)context };
                    hiddenWorkoutData.Value = serializer.Serialize(ret);
                }*/
                    else
                    {
                        context = Utils.ConstsUtil.GraphContext.ME;
                    }
                }

                if (context == Utils.ConstsUtil.GraphContext.EVERYONE)
                {   // we want to compare achievments...
                    IQueryable<Workout> workoutQuery = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Where(a =>
                                                                                                    a.AchievementType.WorkoutType.Id == workout.WorkoutTypeKey &&
                                                                                                    workout.Distance >= a.AchievementType.DistanceRangeA &&
                                                                                                    workout.Distance < a.AchievementType.DistanceRangeB).Take(5000).Select(a => a.UserStream).OfType<Workout>().AsQueryable();
                    workoutQuery = workoutQuery.Union(entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workout.Id));
                    workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here.
                    Workout[] data = workoutQuery.ToArray();
                    jsonWorkoutData = data.OrderByDescending(w => w.Duration).Select(w => new Affine.Data.json.WorkoutData()
                    {
                        UId = w.UserSetting.UserName + "_" + w.Id,
                        Id = w.Id,
                        S = w.Duration.Value,
                        Un = w.UserSetting.UserName,
                        D = w.Date.ToLocalTime().ToShortDateString()
                    }).ToArray();
                }
                else if (context == Utils.ConstsUtil.GraphContext.WATCHLIST || context == Utils.ConstsUtil.GraphContext.FRIENDS)
                {
                    IQueryable<Workout> workoutQuery = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Where(a =>
                                                                                                    a.AchievementType.WorkoutType.Id == workout.WorkoutTypeKey &&
                                                                                                    workout.Distance >= a.AchievementType.DistanceRangeA &&
                                                                                                    workout.Distance < a.AchievementType.DistanceRangeB).
                                                                                                    Where(LinqUtils.BuildContainsExpression<Achievement, long>(a => a.UserSetting.Id, friendIds)).Take(5000).Select(a => a.UserStream).OfType<Workout>().AsQueryable();
                    workoutQuery = workoutQuery.Union(entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workout.Id));
                    workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here.
                    Workout[] data = workoutQuery.ToArray();
                    jsonWorkoutData = data.OrderByDescending(w => w.Duration).Select(w => new Affine.Data.json.WorkoutData()
                    {
                        UId = w.UserSetting.UserName + "_" + w.Id,
                        Id = w.Id,
                        S = w.Duration.Value,
                        Un = w.UserSetting.UserName,
                        D = w.Date.ToLocalTime().ToShortDateString()
                    }).ToArray();
                }
                else if (context == Utils.ConstsUtil.GraphContext.ME)   // this is just you for the ranges.. since no map data
                {
                    IQueryable<Workout> workoutQuery = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Where(a => a.UserSetting.Id == ProfileSettings.Id &&
                                                                                                    a.AchievementType.WorkoutType.Id == workout.WorkoutTypeKey &&
                                                                                                    workout.Distance >= a.AchievementType.DistanceRangeA &&
                                                                                                    workout.Distance < a.AchievementType.DistanceRangeB).
                                                                                                    Take(5000).Select(a => a.UserStream).OfType<Workout>().AsQueryable();
                   workoutQuery = workoutQuery.Union(entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workout.Id));
                   workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here.
                   Workout[] data = workoutQuery.ToArray();
                   jsonWorkoutData = data.OrderByDescending(w => w.Duration).Select(w => new Affine.Data.json.WorkoutData()
                   {
                       UId = w.UserSetting.UserName + "_" + w.Id,
                       Id = w.Id,
                       S = w.Duration.Value,
                       Un = w.UserSetting.UserName,
                       D = w.Date.ToLocalTime().ToShortDateString()
                   }).ToArray();
                }
            }
            var retWorkout = new { WOD = wod, WorkoutData = jsonWorkoutData, Workout = jsonWorkout, Context = (int)context };
            hiddenWorkoutData.Value = serializer.Serialize(retWorkout);
        }
        public override void OnDraw(Graphics2D graphics2D)
        {
            var inverseScale = 1 / scalingFactor;
            var offset       = Vector2.Zero;

            // Reset to zero
            var existing = graphics2D.GetTransform();

            existing.translation(out double x, out double y);
            offset.X += x;
            offset.Y += y;

            // Center
            if (this.Width > this.Height)
            {
                offset.X += (this.Width / 2) - (bedBounds.Width * scalingFactor / 2);
            }
            else
            {
                offset.Y += (this.Height / 2) - (bedBounds.Height * scalingFactor / 2);
            }

            // Offset considering bed bounds
            offset.X -= bedBounds.Left * scalingFactor;
            offset.Y -= bedBounds.Bottom * scalingFactor;

            // Apply transform
            graphics2D.PushTransform();
            graphics2D.SetTransform(Affine.NewScaling(scalingFactor) * Affine.NewTranslation(offset));

            // Draw the bed
            this.RenderBed(graphics2D);

            // Build hotend path
            if (this.RenderProbePath)
            {
                this.RenderProbingPath(graphics2D);
            }

            if (this.RenderLevelingData)
            {
                if (currentLevelingFunctions == null)
                {
                    PrintLevelingData levelingData = printer.Settings.Helpers.PrintLevelingData;
                    currentLevelingFunctions = new LevelingFunctions(printer, levelingData);
                }

                var levelingTriangles = new VertexStorage();

                foreach (var region in currentLevelingFunctions.Regions)
                {
                    levelingTriangles.MoveTo(region.V0.X, region.V0.Y);

                    levelingTriangles.LineTo(region.V1.X, region.V1.Y);
                    levelingTriangles.LineTo(region.V2.X, region.V2.Y);
                    levelingTriangles.LineTo(region.V0.X, region.V0.Y);
                }

                graphics2D.Render(
                    new Stroke(levelingTriangles),
                    opaqueMinimumAccent);
            }

            // Render probe points
            int i = 0;

            foreach (var position in probePoints)
            {
                var center = new Vector2(position.X, position.Y);

                var textColor   = lightText;
                var circleColor = bedCircleColor;

                if (this.SimplePoints)
                {
                    graphics2D.Render(
                        new Ellipse(center, 4 * inverseScale),
                        simpleBedCircleColor);
                }
                else
                {
                    if (i < this.ActiveProbeIndex)
                    {
                        circleColor = opaqueMinimumAccent;
                        textColor   = circleText;
                    }
                    else if (i == this.ActiveProbeIndex)
                    {
                        circleColor = opaqueAccent;
                        textColor   = circleText;
                    }

                    if (i >= this.ActiveProbeIndex)
                    {
                        graphics2D.Circle(
                            center,
                            9 * inverseScale,
                            i == this.ActiveProbeIndex ? circleText : lightText);

                        graphics2D.Circle(
                            center,
                            8 * inverseScale,
                            circleColor);
                    }
                    else
                    {
                        graphics2D.Circle(
                            center,
                            9 * inverseScale,
                            circleColor);
                    }

                    graphics2D.DrawString(
                        $"{1 + i}",
                        center.X,
                        center.Y,
                        justification: Justification.Center,
                        baseline: Baseline.BoundsCenter,
                        pointSize: theme.FontSize7 * inverseScale,
                        color: textColor);

                    i++;
                }
            }

            graphics2D.PopTransform();

            base.OnDraw(graphics2D);
        }
Example #9
0
        private void task()
        {
            MotorControler mc     = MotorControler.GetInstance(parameterManager);
            Surface        sur    = Surface.GetInstance(parameterManager);
            Camera         camera = Camera.GetInstance();
            Led            led    = Led.GetInstance();
            CoordManager   cm     = new CoordManager(parameterManager);

            Vector3 InitPoint = mc.GetPoint();


            List <Mat> image_set = new List <Mat>();
            Vector3    ggg       = mc.GetPoint();

            string       txtfileName = string.Format(@"c:\img\bbbbbb.txt");
            StreamWriter twriter     = File.CreateText(txtfileName);
            // twriter.Write("line95\n");

            Vector3 initialpoint = mc.GetPoint();

            List <Vector2> list_lateralmark43 = new List <Vector2>();//in PL#43

            list_lateralmark43.Add(new Vector2(81.706, 89.124));
            list_lateralmark43.Add(new Vector2(-89.715, 83.350));
            list_lateralmark43.Add(new Vector2(-86.969, -87.964));
            list_lateralmark43.Add(new Vector2(83.521, -86.169));

            List <Vector2> list_scanregion43 = new List <Vector2>();

            list_scanregion43.Add(list_lateralmark43[0] - new Vector2(-5, -5));
            list_scanregion43.Add(list_lateralmark43[1] - new Vector2(+5, -5));
            list_scanregion43.Add(list_lateralmark43[2] - new Vector2(+5, +5));
            list_scanregion43.Add(list_lateralmark43[3] - new Vector2(-5, +5));


            List <Vector2> list_lateralmark42 = new List <Vector2>();//in PL#42

            list_lateralmark42.Add(new Vector2(81.750, 89.099));
            list_lateralmark42.Add(new Vector2(-89.526, 83.417));
            list_lateralmark42.Add(new Vector2(-86.754, -87.727));
            list_lateralmark42.Add(new Vector2(83.612, -85.831));

            List <Vector2> list_scanregion42 = new List <Vector2>();

            list_scanregion42.Add(list_lateralmark42[0] - new Vector2(-5, -5));
            list_scanregion42.Add(list_lateralmark42[1] - new Vector2(+5, -5));
            list_scanregion42.Add(list_lateralmark42[2] - new Vector2(+5, +5));
            list_scanregion42.Add(list_lateralmark42[3] - new Vector2(-5, +5));

            Affine ap_s43_s42 = Affine.CreateAffineBy(list_lateralmark43, list_lateralmark42);

            List <Vector2> list_scanpoint_g = new List <Vector2>();

            for (int x = 0; x < 11; x++)
            {
                for (int y = 0; y < 11; y++)
                {
                    list_scanpoint_g.Add(new Vector2(x * 1.0, y * 1.0));
                }
            }


            List <Vector2> list_scancorner_g = new List <Vector2>();

            list_scancorner_g.Add(new Vector2(10.0, 10.0));
            list_scancorner_g.Add(new Vector2(0.0, 10.0));
            list_scancorner_g.Add(new Vector2(0.0, 0.0));
            list_scancorner_g.Add(new Vector2(10.0, 0.0));


            Affine ap_g43_s43 = Affine.CreateAffineBy(list_scancorner_g, list_scanregion43);



            camera.Start();



            for (int d = 0; d < list_scanpoint_g.Count; d++)
            {
//                Vector2 predpoint41 = ap_g41_s41.Trance(list_scanpoint_g[d]);

                Vector2 predpoint43 = ap_g43_s43.Trance(list_scanpoint_g[d]);
                Vector2 predpoint42 = ap_s43_s42.Trance(predpoint43);


                mc.MoveTo(new Vector3(predpoint42.X, predpoint42.Y, initialpoint.Z - 0.100));
                mc.Join();
                Thread.Sleep(4000);
                int ledbrightness = led.AdjustLight(parameterManager);

                int  viewcounter = 0;
                bool flag        = true;
                while (flag)
                {
                    mc.MoveDistance(+0.003, VectorId.Z);
                    mc.Join();
                    byte[] b   = camera.ArrayImage;
                    Mat    src = new Mat(440, 512, MatType.CV_8U, b);
                    Mat    mat = src.Clone();

                    Cv2.GaussianBlur(mat, mat, Cv.Size(3, 3), -1);
                    Mat gau = mat.Clone();
                    Cv2.GaussianBlur(gau, gau, Cv.Size(7, 7), -1);
                    Cv2.Subtract(gau, mat, mat);
                    Cv2.Threshold(mat, mat, 4, 1, ThresholdType.Binary);
                    int brightness = Cv2.CountNonZero(mat);

                    viewcounter++;

                    if (brightness > 2000 || viewcounter > 100)
                    {
                        flag = false;
                    }
                }//while-loop surface detection

                Vector3 surfacepoint = mc.GetPoint();

                for (int vy = 0; vy < 2; vy++)
                {
                    for (int vx = 0; vx < 2; vx++)
                    {
                        mc.MoveTo
                            (new Vector3(
                                predpoint42.X - 0.125 / 2.0 + 0.125 * vx,
                                predpoint42.Y - 0.105 / 2.0 + 0.105 * vy,
                                surfacepoint.Z));
                        mc.Join();


                        for (int q = 0; q < 8; q++)
                        {
                            mc.MovePointZ(surfacepoint.Z + 0.003 + (0.003 * q));
                            mc.Join();

                            Vector3 currentpoint = mc.GetPoint();

                            byte[] b           = camera.ArrayImage;
                            Mat    image       = new Mat(440, 512, MatType.CV_8U, b);
                            Mat    clone_image = image.Clone();

                            //clone_image.ImWrite(String.Format(@"c:\img\{0}_{1:00}.bmp", d, q));

                            clone_image.ImWrite(String.Format(@"c:\img\{0}_{1}_{2}_{3:00}.bmp", d, vx, vy, q));

                            string stlog = "";
                            stlog += String.Format("{0}   {1}  {2}  {3}\n",
                                                   ledbrightness,
                                                   currentpoint.X,
                                                   currentpoint.Y,
                                                   currentpoint.Z);
                            twriter.Write(stlog);
                            // twriter.Write("line198\n");
                            twriter.Flush();
                        } //for-loop q pictureID
                    }     //for-loop vx view0,1
                }         //for-loop vy view0,1
            }             //for-loop d-th scanning point

            camera.Stop();
            twriter.Close();
        }
Example #10
0
        public override void OnDraw(Graphics2D graphics2D)
        {
            ImageBuffer        widgetsSubImage = ImageBuffer.NewSubImageReference(graphics2D.DestImage, graphics2D.GetClippingRect());
            ImageClippingProxy clippingProxy   = new ImageClippingProxy(widgetsSubImage);

            clippingProxy.clear(new ColorF(1, 1, 1));
            m_ras.SetVectorClipBox(0, 0, Width, Height);

            Affine move = Affine.NewTranslation(10, 10);

            Perspective shadow_persp = new Perspective(m_shape_bounds.Left, m_shape_bounds.Bottom,
                                                       m_shape_bounds.Right, m_shape_bounds.Top,
                                                       m_shadow_ctrl.polygon());

            IVertexSource shadow_trans;

            if (m_FlattenCurves.Checked)
            {
                shadow_trans = new VertexSourceApplyTransform(m_shape, shadow_persp);
            }
            else
            {
                shadow_trans = new VertexSourceApplyTransform(m_path, shadow_persp);
                // this will make it very smooth after the transform
                //shadow_trans = new conv_curve(shadow_trans);
            }

            // Render shadow
            m_ras.add_path(shadow_trans);
            ScanlineRenderer scanlineRenderer = new ScanlineRenderer();

            scanlineRenderer.RenderSolid(clippingProxy, m_ras, m_sl, new ColorF(0.2, 0.3, 0).ToColor());

            // Calculate the bounding box and extend it by the blur radius
            RectangleDouble bbox = new RectangleDouble();

            bounding_rect.bounding_rect_single(shadow_trans, 0, ref bbox);

            bbox.Left   -= m_radius.Value;
            bbox.Bottom -= m_radius.Value;
            bbox.Right  += m_radius.Value;
            bbox.Top    += m_radius.Value;

            if (m_method.SelectedIndex == 1)
            {
                // The recursive blur method represents the true Gaussian Blur,
                // with theoretically infinite kernel. The restricted window size
                // results in extra influence of edge pixels. It's impossible to
                // solve correctly, but extending the right and top areas to another
                // radius value produces fair result.
                //------------------
                bbox.Right += m_radius.Value;
                bbox.Top   += m_radius.Value;
            }

            stopwatch.Restart();

            if (m_method.SelectedIndex != 2)
            {
                // Create a new pixel renderer and attach it to the main one as a child image.
                // It returns true if the attachment succeeded. It fails if the rectangle
                // (bbox) is fully clipped.
                //------------------
#if SourceDepth24
                ImageBuffer image2 = new ImageBuffer(new BlenderBGR());
#else
                ImageBuffer image2 = new ImageBuffer(new BlenderBGRA());
#endif
                if (image2.Attach(widgetsSubImage, (int)bbox.Left, (int)bbox.Bottom, (int)bbox.Right, (int)bbox.Top))
                {
                    // Blur it
                    if (m_method.SelectedIndex == 0)
                    {
                        // More general method, but 30-40% slower.
                        //------------------
                        //m_stack_blur.blur(pixf2, agg::uround(m_radius.Value));

                        // Faster, but bore specific.
                        // Works only for 8 bits per channel and only with radii <= 254.
                        //------------------
                        stack_blur test = new stack_blur();
                        test.Blur(image2, agg_basics.uround(m_radius.Value), agg_basics.uround(m_radius.Value));
                    }
                    else
                    {
                        // True Gaussian Blur, 3-5 times slower than Stack Blur,
                        // but still constant time of radius. Very sensitive
                        // to precision, doubles are must here.
                        //------------------
                        m_recursive_blur.blur(image2, m_radius.Value);
                    }
                }
            }
            else
            {
                /*
                 * // Blur separate channels
                 * //------------------
                 * if(m_channel_r.Checked)
                 * {
                 *      typedef agg::pixfmt_alpha_blend_gray<
                 *              agg::blender_gray8,
                 *              agg::rendering_buffer,
                 *              3, 2> pixfmt_gray8r;
                 *
                 *      pixfmt_gray8r pixf2r(m_rbuf2);
                 *      if(pixf2r.attach(pixf, int(bbox.x1), int(bbox.y1), int(bbox.x2), int(bbox.y2)))
                 *      {
                 *              agg::stack_blur_gray8(pixf2r, agg::uround(m_radius.Value),
                 *                                                                        agg::uround(m_radius.Value));
                 *      }
                 * }
                 *
                 * if(m_channel_g.Checked)
                 * {
                 *      typedef agg::pixfmt_alpha_blend_gray<
                 *              agg::blender_gray8,
                 *              agg::rendering_buffer,
                 *              3, 1> pixfmt_gray8g;
                 *
                 *      pixfmt_gray8g pixf2g(m_rbuf2);
                 *      if(pixf2g.attach(pixf, int(bbox.x1), int(bbox.y1), int(bbox.x2), int(bbox.y2)))
                 *      {
                 *              agg::stack_blur_gray8(pixf2g, agg::uround(m_radius.Value),
                 *                                                                        agg::uround(m_radius.Value));
                 *      }
                 * }
                 *
                 * if(m_channel_b.Checked)
                 * {
                 *      typedef agg::pixfmt_alpha_blend_gray<
                 *              agg::blender_gray8,
                 *              agg::rendering_buffer,
                 *              3, 0> pixfmt_gray8b;
                 *
                 *      pixfmt_gray8b pixf2b(m_rbuf2);
                 *      if(pixf2b.attach(pixf, int(bbox.x1), int(bbox.y1), int(bbox.x2), int(bbox.y2)))
                 *      {
                 *              agg::stack_blur_gray8(pixf2b, agg::uround(m_radius.Value),
                 *                                                                        agg::uround(m_radius.Value));
                 *      }
                 * }
                 */
            }

            double tm = stopwatch.ElapsedMilliseconds;

            // Render the shape itself
            //------------------
            if (m_FlattenCurves.Checked)
            {
                m_ras.add_path(m_shape);
            }
            else
            {
                m_ras.add_path(m_path);
            }

            scanlineRenderer.RenderSolid(clippingProxy, m_ras, m_sl, new ColorF(0.6, 0.9, 0.7, 0.8).ToColor());

            graphics2D.DrawString(string.Format("{0:F2} ms", tm), 140, 30);
            base.OnDraw(graphics2D);
        }
        public void GenerateMarchingSquaresAndLines(Action <double, string> progressReporter, ImageBuffer image, IThresholdFunction thresholdFunction)
        {
            if (image != null)
            {
                // Regenerate outline
                var marchingSquaresData = new MarchingSquaresByte(
                    image,
                    thresholdFunction.ZeroColor,
                    thresholdFunction.Threshold,
                    0);

                progressReporter?.Invoke(0, "Creating Outline");

                marchingSquaresData.CreateLineSegments();
                progressReporter?.Invoke(.1, null);

                int pixelsToIntPointsScale = 1000;
                var lineLoops = marchingSquaresData.CreateLineLoops(pixelsToIntPointsScale);

                NumLineLoops = lineLoops.Count;

                if (NumLineLoops > 1 && MinSurfaceArea > 0)
                {
                    var minimumSurfaceArea = Math.Pow(MinSurfaceArea * 1000, 2);

                    for (int i = lineLoops.Count - 1; i >= 0; i--)
                    {
                        var area = Math.Abs(Clipper.Area(lineLoops[i]));
                        if (area < minimumSurfaceArea)
                        {
                            lineLoops.RemoveAt(i);
                        }
                    }
                }

                progressReporter?.Invoke(.15, null);

                var min = new IntPoint(-10, -10);
                var max = new IntPoint(10 + image.Width * pixelsToIntPointsScale, 10 + image.Height * pixelsToIntPointsScale);

                var boundingPoly = new Polygon
                {
                    min,
                    new IntPoint(min.X, max.Y),
                    max,
                    new IntPoint(max.X, min.Y)
                };

                // now clip the polygons to get the inside and outside polys
                var clipper = new Clipper();
                clipper.AddPaths(lineLoops, PolyType.ptSubject, true);
                clipper.AddPath(boundingPoly, PolyType.ptClip, true);

                var polygonShapes = new Polygons();
                progressReporter?.Invoke(.3, null);

                clipper.Execute(ClipType.ctIntersection, polygonShapes);

                progressReporter?.Invoke(.55, null);

                polygonShapes = Clipper.CleanPolygons(polygonShapes, 100);

                progressReporter?.Invoke(.75, null);

                VertexStorage rawVectorShape = polygonShapes.PolygonToPathStorage();

                var aabb   = this.VisibleMeshes().FirstOrDefault().GetAxisAlignedBoundingBox();
                var xScale = aabb.XSize / image.Width;

                var affine = Affine.NewScaling(1.0 / pixelsToIntPointsScale * xScale);
                affine *= Affine.NewTranslation(-aabb.XSize / 2, -aabb.YSize / 2);

                rawVectorShape.transform(affine);
                this.VertexSource = rawVectorShape;

                progressReporter?.Invoke(1, null);
            }
        }
Example #12
0
        private void task()
        {
            MotorControler mc     = MotorControler.GetInstance(parameterManager);
            Surface        sur    = Surface.GetInstance(parameterManager);
            Camera         camera = Camera.GetInstance();
            Led            led    = Led.GetInstance();
            CoordManager   cm     = new CoordManager(parameterManager);


            Vector3 InitPoint = mc.GetPoint();

            List <Vector2> src = new List <Vector2>();
            List <Vector2> dst = new List <Vector2>();

            src.Add(new Vector2(0, 0));
            dst.Add(new Vector2(0, 0));

            src.Add(new Vector2(-140.0, 150.0));
            dst.Add(new Vector2(-138.770, 151.485));

            src.Add(new Vector2(+140.0, 160.0));
            dst.Add(new Vector2(+141.581, 158.903));

            src.Add(new Vector2(+150.0, -140.0));
            dst.Add(new Vector2(+148.880, -141.600));

            src.Add(new Vector2(-150.0, -140.0));
            dst.Add(new Vector2(-151.297, -138.670));


            Affine ap = Affine.CreateAffineBy(src, dst);


            string       txtfileName = string.Format(@"c:\img\_grid_g.txt");
            StreamWriter twriter     = File.CreateText(txtfileName);

            for (int x = -14; x < 14; x += 2)
            {
                for (int y = -14; y < 14; y += 2)
                {
                    Vector2 predpoint = ap.Trance(new Vector2(x * 10, y * 10));
                    mc.MoveTo(new Vector3(predpoint.X, predpoint.Y, InitPoint.Z));
                    mc.Join();

                    led.AdjustLight(parameterManager);

                    byte[] b2   = camera.ArrayImage;
                    Mat    src2 = new Mat(440, 512, MatType.CV_8U, b2);
                    Mat    mat2 = src2.Clone();

                    string FileName = string.Format(@"C:\img\grid_x{0}_y{1}.png", x, y);
                    Cv2.ImWrite(FileName, mat2);


                    string stlog = "";
                    stlog += String.Format("{0} {1} {2:f4} {3:f4}\n",
                                           x * 10,
                                           y * 10,
                                           predpoint.X,
                                           predpoint.Y);
                    twriter.Write(stlog);
                } //for y
            }     //for x

            twriter.Close();
        }//task()
Example #13
0
        public override void Draw(CanvasPainter p)
        {
            int strokeWidth = 1;
            int width       = p.Width;
            int height      = p.Height;

            Affine affTx = Affine.NewMatix(
                AffinePlan.Translate(-lionShape.Center.x, -lionShape.Center.y),
                AffinePlan.Scale(spriteScale, spriteScale),
                AffinePlan.Rotate(angle + Math.PI),
                AffinePlan.Skew(skewX / 1000.0, skewY / 1000.0),
                AffinePlan.Translate(width / 2, height / 2));

            var p1 = p as AggCanvasPainter;

            if (p1 == null)
            {
                int             j        = lionShape.NumPaths;
                int[]           pathList = lionShape.PathIndexList;
                Drawing.Color[] colors   = lionShape.Colors;
                //graphics2D.UseSubPixelRendering = true;
                var vxs = GetFreeVxs();
                affTx.TransformToVxs(lionShape.Path.Vxs, vxs);
                p.StrokeWidth = 1;
                for (int i = 0; i < j; ++i)
                {
                    p.StrokeColor = colors[i];
                    p.Draw(new VertexStoreSnap(vxs, pathList[i]));
                }
                //not agg
                Release(ref vxs);
                return; //**
            }

            Graphics2D graphics2D = p1.Graphics;
            //var widgetsSubImage = ImageHelper.CreateChildImage(graphics2D.DestImage, graphics2D.GetClippingRect());
            //int width = widgetsSubImage.Width;
            //int height = widgetsSubImage.Height;
            var widgetsSubImage = ImageHelper.CreateChildImage(graphics2D.DestImage, graphics2D.GetClippingRect());

            var            clippedSubImage    = new ChildImage(widgetsSubImage, new PixelBlenderBGRA());
            ClipProxyImage imageClippingProxy = new ClipProxyImage(clippedSubImage);

            imageClippingProxy.Clear(PixelFarm.Drawing.Color.White);


            if (RenderAsScanline)
            {
                var rasterizer = graphics2D.ScanlineRasterizer;
                rasterizer.SetClipBox(0, 0, width, height);
                Stroke stroke = new Stroke(strokeWidth);
                stroke.LineJoin = LineJoin.Round;
                var vxs = GetFreeVxs();
                affTx.TransformToVxs(lionShape.Path.Vxs, vxs);
                ScanlineRasToDestBitmapRenderer sclineRasToBmp = graphics2D.ScanlineRasToDestBitmap;
                sclineRasToBmp.RenderSolidAllPaths(
                    imageClippingProxy,
                    rasterizer,
                    graphics2D.ScanlinePacked8,
                    vxs,
                    lionShape.Colors,
                    lionShape.PathIndexList,
                    lionShape.NumPaths);
                Release(ref vxs);
            }
            else
            {
                double w = strokeWidth * affTx.GetScale();
                LineProfileAnitAlias lineProfile     = new LineProfileAnitAlias(w, new GammaNone());
                OutlineRenderer      outlineRenderer = new OutlineRenderer(imageClippingProxy, new PixelBlenderBGRA(), lineProfile);
                OutlineAARasterizer  rasterizer      = new OutlineAARasterizer(outlineRenderer);
                rasterizer.LineJoin = (RenderAccurateJoins ?
                                       OutlineAARasterizer.OutlineJoin.AccurateJoin
                    : OutlineAARasterizer.OutlineJoin.Round);
                rasterizer.RoundCap = true;
                //VertexSourceApplyTransform trans = new VertexSourceApplyTransform(lionShape.Path, transform);
                var vxs = GetFreeVxs();
                affTx.TransformToVxs(lionShape.Path.Vxs, vxs);// trans.DoTransformToNewVxStorage();
                int j = lionShape.NumPaths;
                for (int i = 0; i < j; ++i)
                {
                    rasterizer.RenderVertexSnap(
                        new VertexStoreSnap(vxs,
                                            lionShape.PathIndexList[i]),
                        lionShape.Colors[i]);
                }
                Release(ref vxs);
            }
            base.Draw(p);
        }
Example #14
0
    public virtual bool TranslateTransform(int dx, int dy)
    {
        // Get the current transform
        XFORM oldTransform = GetWorldTransform();

        // Put it into an Affine so that we can change it
        Affine anAffine = new Affine();
        anAffine.fMatrix = oldTransform;
        anAffine.Translate((float)dx, (float)dy);

        // Set it back on the graph port
        bool result = SetWorldTransform(anAffine.fMatrix);

        return result;
    }
Example #15
0
 public static extern bool SetLayerAffineTransform(int nlayer, ref Affine affine);
Example #16
0
	// Find a transform which maps p0, q0, and r0 to p1, p1 and r1 respectively
	public bool MapTri(float px0, float py0, float qx0, float qy0, float rx0, float ry0,
						 float px1, float py1, float qx1, float qy1, float rx1, float ry1)
	{
		if (!MapTri(px0, py0, qx0, qy0, rx0, ry0))
			return false;

		Invert();		// transform p0, q0, and r0 back to (0,0),(1,0),(0,1)

		Affine map1 = new Affine();

		if (!map1.MapTri(px1, py1, qx1, qy1, rx1, ry1))
			return false;

		return Combine(map1.fMatrix);	// then to p1,r1,q1
	}
Example #17
0
        private void MakeArrowIcons()
        {
            var center = mainTrackBallController.ScreenCenter;
            var radius = mainTrackBallController.TrackBallRadius;

            insideArrows.Clear();
            // create the inside arrows
            {
                var             svg                = new PathStorage("M560.512 0.570216 C560.512 2.05696 280.518 560.561 280.054 560 C278.498 558.116 0 0.430888 0.512416 0.22416 C0.847112 0.089136 63.9502 27.1769 140.742 60.4192 C140.742 60.4192 280.362 120.86 280.362 120.86 C280.362 120.86 419.756 60.4298 419.756 60.4298 C496.422 27.1934 559.456 0 559.831 0 C560.205 0 560.512 0.2566 560.512 0.570216 Z");
                RectangleDouble bounds             = svg.GetBounds();
                double          arrowWidth         = radius / 10;
                var             centered           = Affine.NewTranslation(-bounds.Center);
                var             scalledTo1         = Affine.NewScaling(1 / bounds.Width);
                var             scaledToSize       = Affine.NewScaling(arrowWidth);
                var             moveToRadius       = Affine.NewTranslation(new Vector2(0, radius * 9 / 10));
                var             moveToScreenCenter = Affine.NewTranslation(center);
                for (int i = 0; i < 4; i++)
                {
                    var arrowLeftTransform = centered * scalledTo1 * scaledToSize * moveToRadius * Affine.NewRotation(MathHelper.Tau / 4 * i) * moveToScreenCenter;
                    insideArrows.Add(new VertexSourceApplyTransform(svg, arrowLeftTransform));
                }
            }

            outsideArrows.Clear();
            // and the outside arrows
            {
                //var svg = new PathStorage("m 271.38288,545.86543 c -10.175,-4.94962 -23,-11.15879 -28.5,-13.79816 -5.5,-2.63937 -24.34555,-11.82177 -41.87901,-20.40534 -17.53346,-8.58356 -32.21586,-15.60648 -32.62756,-15.60648 -0.4117,0 -1.28243,-0.64329 -1.93495,-1.42954 -0.98148,-1.1826 -0.0957,-1.94177 5.12755,-4.39484 3.47268,-1.63091 16.21397,-7.7909 28.31397,-13.68887 12.1,-5.89797 30.55,-14.8788 41,-19.9574 10.45,-5.07859 25.64316,-12.49628 33.76258,-16.48374 8.11942,-3.98746 15.43192,-6.99308 16.25,-6.67916 2.02527,0.77717 1.8755,5.19031 -0.56452,16.63355 -1.11411,5.225 -2.29208,10.9625 -2.6177,12.75 l -0.59204,3.25 80.19823,0 c 75.90607,0 80.17104,-0.0937 79.69036,-1.75 -2.47254,-8.51983 -5.62648,-24.42623 -5.62674,-28.37756 -3.6e-4,-5.51447 1.61726,-5.18356 21.01872,4.29961 10.16461,4.96833 22.98111,11.1892 28.48111,13.82415 5.5,2.63496 24.34555,11.81375 41.87901,20.39732 17.53346,8.58356 32.21586,15.60648 32.62756,15.60648 0.4117,0 1.28243,0.64329 1.93495,1.42954 0.98144,1.18256 0.0956,1.94283 -5.12755,4.40048 -3.47268,1.63401 -15.98897,7.68875 -27.81397,13.45496 -11.825,5.76621 -31.625,15.41743 -44,21.44716 -12.375,6.02972 -27.79146,13.55332 -34.2588,16.71911 -6.99025,3.42175 -12.41867,5.50276 -13.38597,5.13157 -2.11241,-0.81061 -1.37413,-8.85503 2.14722,-23.39653 1.37365,-5.67253 2.49755,-10.73503 2.49755,-11.25 0,-0.57397 -31.15148,-0.93629 -80.5,-0.93629 -76.11526,0 -80.5,0.0957 -80.5,1.7566 0,0.96613 0.45587,3.32863 1.01304,5.25 1.68077,5.79599 4.98696,23.01922 4.98696,25.97902 0,5.59974 -1.53004,5.29551 -21,-4.17564 z");
                var             svg                = new PathStorage("M560.512 0.570216 C560.512 2.05696 280.518 560.561 280.054 560 C278.498 558.116 0 0.430888 0.512416 0.22416 C0.847112 0.089136 63.9502 27.1769 140.742 60.4192 C140.742 60.4192 280.362 120.86 280.362 120.86 C280.362 120.86 419.756 60.4298 419.756 60.4298 C496.422 27.1934 559.456 0 559.831 0 C560.205 0 560.512 0.2566 560.512 0.570216 Z");
                RectangleDouble bounds             = svg.GetBounds();
                double          arrowWidth         = radius / 15;
                var             centered           = Affine.NewTranslation(-bounds.Center);
                var             scalledTo1         = Affine.NewScaling(1 / bounds.Width);
                var             scaledToSize       = Affine.NewScaling(arrowWidth);
                var             moveToRadius       = Affine.NewTranslation(new Vector2(0, radius * 16 / 15));
                var             moveToScreenCenter = Affine.NewTranslation(center);
                for (int i = 0; i < 4; i++)
                {
                    var arrowLeftTransform = centered * scalledTo1 * scaledToSize * Affine.NewRotation(MathHelper.Tau / 4) * moveToRadius * Affine.NewRotation(MathHelper.Tau / 8 + MathHelper.Tau / 4 * i + MathHelper.Tau / 80) * moveToScreenCenter;
                    outsideArrows.Add(new VertexSourceApplyTransform(svg, arrowLeftTransform));

                    var arrowRightTransform = centered * scalledTo1 * scaledToSize * Affine.NewRotation(-MathHelper.Tau / 4) * moveToRadius * Affine.NewRotation(MathHelper.Tau / 8 + MathHelper.Tau / 4 * i - MathHelper.Tau / 80) * moveToScreenCenter;
                    outsideArrows.Add(new VertexSourceApplyTransform(svg, arrowRightTransform));
                }
            }
        }