コード例 #1
0
        public void TestFailure()
        {
            Promise<long> p = new Promise<long>(cb => cb("uh oh", default(long)));

            bool test = false;

            p.Success(x => test = true);

            Assert.IsFalse(test);

            p.Fail(s => test = true);

            Assert.IsTrue(test);

            var p2 = p.FlatMap(l => new Promise<int>(cb => cb(null, 3)));

            test = false;

            p2.Success(x => test = true);

            Assert.IsFalse(test);

            p2.Fail(s => test = true);

            Assert.IsTrue(test);
        }
コード例 #2
0
        public UIRenderPlane(UISpriteBatch batch, Promise<Texture2D> texture)
        {
            this.GD = batch.GraphicsDevice;
            this.Target = batch.GetBuffer();
            this.Texture = texture;
            this.Batch = batch;

            //GD.PresentationParameters.RenderTargetUsage = RenderTargetUsage.PreserveContents;

            /** Switch the render target **/
            Batch.Pause();
            GD.SetRenderTarget(0, Target);
            GD.Clear(Color.TransparentBlack);
            Batch.Resume();

            /**
                batch.Pause();
                var buffer = batch.GetBuffer();
                var gd = GameFacade.GraphicsDevice;

                var renderTarget = gd.GetRenderTarget(0);
                gd.SetRenderTarget(0, buffer);
                batch.Resume();
                gd.render
                //gd.Clear(Color.TransparentBlack);**/
        }
コード例 #3
0
        private object BuidlListHal(Promise<int> total, IEnumerable<Place> places, SearchPlacesParameters parameters)
        {
            var totalPages = total/parameters.PageSize;

            var builder = new HalBuilder(Request.Url.ToString())
                .AddProperty("pages", totalPages)
                .AddProperty("page", parameters.Page)
                .EmbedListResourceWithProperties(
                    "places",
                    places,
                    place => Settings.ToAbsolute(string.Format("/places/{0}", place.Id)),
                    place => place.Id,
                    place => place.EnglishName,
                    place => place.CornishName,
                    place => place.Type,
                    place => place.Parish);

            if (parameters.Page < totalPages)
                builder.AddLink("next", new SearchUrlBuilder(parameters).NextPage().Build());

            if (parameters.Page > 1)
                builder.AddLink("prev", new SearchUrlBuilder(parameters).PreviousPage().Build());

            return builder.Build();
        }
コード例 #4
0
        public void Promise_Reject_UserInfo()
        {
            var args = default(object[]);
            var are = new AutoResetEvent(false);
            var resolve = new MockCallback(_ => { });
            var reject = new MockCallback(a =>
            {
                args = a;
                are.Set();
            });
            var promise = new Promise(resolve, reject);

            var code = "42";
            var message = "foo";
            var e = new Exception();
            e.Data.Add("qux", "baz");
            promise.Reject(code, message, e);
            are.WaitOne();

            Assert.IsNotNull(args);
            Assert.AreEqual(1, args.Length);
            var json = args[0] as JObject;
            Assert.IsNotNull(json);
            var userInfo = json["userInfo"] as JObject;
            Assert.IsNotNull(userInfo);
            Assert.AreEqual("baz", userInfo["qux"]);
        }
コード例 #5
0
ファイル: CommunityTests.cs プロジェクト: StudioJD/unity-sdk
    public void ShouldAddFriend(Cloud cloud)
    {
        // Use two test accounts
        Login2NewUsers(cloud, (gamer1, gamer2) => {
            // Expects friend status change event
            Promise restOfTheTestCompleted = new Promise();
            gamer1.StartEventLoop();
            gamer1.Community.OnFriendStatusChange += (FriendStatusChangeEvent e) => {
                Assert(e.FriendId == gamer2.GamerId, "Should come from P2");
                Assert(e.NewStatus == FriendRelationshipStatus.Add, "Should have added me");
                restOfTheTestCompleted.Done(CompleteTest);
            };

            // Add gamer1 as a friend of gamer2
            gamer2.Community.AddFriend(gamer1.GamerId)
            .ExpectSuccess(addResult => {
                // Then list the friends of gamer1, gamer2 should be in it
                return gamer1.Community.ListFriends();
            })
            .ExpectSuccess(friends => {
                Assert(friends.Count == 1, "Expects one friend");
                Assert(friends[0].GamerId == gamer2.GamerId, "Wrong friend ID");
                restOfTheTestCompleted.Resolve();
            });
        });
    }
コード例 #6
0
ファイル: AppStoreImpl.cs プロジェクト: StudioJD/unity-sdk
        // Callback from native code
        void IStore.GetInformationAboutProducts_Done(string message)
        {
            // Extract promise and allow again
            Promise<List<ProductInfo>> promise;
            lock (this) {
                promise = LastGetInformationAboutProductsPromise;
                LastGetInformationAboutProductsPromise = null;
            }

            if (promise == null) {
                Debug.LogWarning("Responding to GetInformationAboutProducts without having promise set");
            }

            Bundle json = Bundle.FromJson(message);
            // Error
            if (json.Has("error")) {
                promise.Reject(ParseError(json));
                return;
            }

            List<ProductInfo> result = new List<ProductInfo>();
            foreach (Bundle obj in json["products"].AsArray()) {
                result.Add(new ProductInfo(obj));
            }
            promise.Resolve(result);
        }
コード例 #7
0
ファイル: GodfatherTests.cs プロジェクト: StudioJD/unity-sdk
    public void ShouldAssociateGodfather(Cloud cloud)
    {
        Login2NewUsers(cloud, (gamer1, gamer2) => {
            // Expects godchild event
            Promise restOfTheTestCompleted = new Promise();
            gamer1.StartEventLoop();
            gamer1.Godfather.OnGotGodchild += (GotGodchildEvent e) => {
                Assert(e.Gamer.GamerId == gamer2.GamerId, "Should come from player2");
                Assert((object)e.Reward == (object)Bundle.Empty, "No reward should be associated");
                restOfTheTestCompleted.Done(CompleteTest);
            };

            // P1 generates a code and associates P2 with it
            gamer1.Godfather.GenerateCode()
            // Use code
            .ExpectSuccess(genCode => gamer2.Godfather.UseCode(genCode))
            .ExpectSuccess(dummy => gamer2.Godfather.GetGodfather())
            .ExpectSuccess(result => {
                Assert(result.GamerId == gamer1.GamerId, "P1 should be godfather");
                Assert(result.AsBundle().Root.Has("godfather"), "Underlying structure should be accessible");
                return gamer1.Godfather.GetGodchildren();
            })
            .ExpectSuccess(result => {
                Assert(result.Count == 1, "Should have only one godchildren");
                Assert(result[0].GamerId == gamer2.GamerId, "P2 should be godchildren");
                restOfTheTestCompleted.Resolve();
            });
        });
    }
コード例 #8
0
ファイル: 2.2.cs プロジェクト: avenema/C-Sharp-Promise
            public void _if_onRejected_is_not_a_function_it_must_be_ignored_1()
            {
                var promise = new Promise<object>();

                var resultPromise = promise
                    .Then(
                        v => Promise.Resolved(),
                        null
                    );

                var resolved = 0;
                var errors = 0;
                var e = new Exception();
                resultPromise.Then(() => ++resolved);
                resultPromise.Catch(ex =>
                {
                    Assert.Equal(e, ex);
                    ++errors;
                });

                promise.Reject(e);

                Assert.Equal(0, resolved);
                Assert.Equal(1, errors);
            }
コード例 #9
0
		public Promise LoadActivityStates(string studentId, IEnumerable<string> activityIds)
		{
			Promise promise = new Promise();
			
			try
			{
				Uri serverUri = new Uri(appSettings.ServerURI, UriKind.RelativeOrAbsolute);
				Uri restUri = new Uri(serverUri, "rest/");
				
				ActivityStateRepository repo = new ActivityStateRepository(restUri);
				if (repo == null)
				{
					throw new Exception("ActivityStateRepository is not initialized.");
				}
				
				repo.GetActivityStates(studentId, activityIds, (ActivityStateRepository.Response response) =>
				{
					if (response.Success)
					{
						promise.Resolve(response.Items);
					}
					else
					{
						promise.Reject(new Exception(response.Error));
					}
				});                   
			}
			catch (Exception e)
			{
				promise.Reject(e);
			}
			
			return promise;
		}
コード例 #10
0
		public Promise SignIn(string domain, string username, string password)
		{
			Promise promise = new Promise();

			try
			{
				Uri serverUri = new Uri(appSettings.ServerURI, UriKind.RelativeOrAbsolute);
				Uri restUri = new Uri(serverUri, "rest/");

				StudentRepository repo = new StudentRepository(restUri);
				if (repo == null)
				{
					throw new Exception("StudentRepository is not initialized.");
				}
				
				repo.SignIn(domain, username, password, (StudentRepository.Response response) =>
				{
					if (response.Success)
					{
						Token = Guid.NewGuid().ToString();
						promise.Resolve(response.Item);
					}
					else
					{
						promise.Reject(new Exception(response.Error));
					}
				});                   
			}
			catch (Exception e)
			{
				promise.Reject(e);
			}

			return promise;
		}
コード例 #11
0
ファイル: Program.cs プロジェクト: avenema/C-Sharp-Promise
        /// <summary>
        /// Download text from a URL.
        /// A promise is returned that is resolved when the download has completed.
        /// The promise is rejected if an error occurs during download.
        /// </summary>
        static IPromise<string> Download(string url)
        {
            Console.WriteLine("Downloading " + url + " ...");

            var promise = new Promise<string>();
            using (var client = new WebClient())
            {
                client.DownloadStringCompleted +=
                    (s, ev) =>
                    {
                        if (ev.Error != null)
                        {
                            Console.WriteLine("An error occurred... rejecting the promise.");

                            // Error during download, reject the promise.
                            promise.Reject(ev.Error);
                        }
                        else
                        {
                            Console.WriteLine("... Download completed.");

                            // Downloaded completed successfully, resolve the promise.
                            promise.Resolve(ev.Result);
                        }
                    };

                client.DownloadStringAsync(new Uri(url), null);
            }
            return promise;
        }
コード例 #12
0
 public AsyncStreamWriter(Stream stream, Action onComplete, Action<Exception> onError)
 {
   _stream = stream;
   _promise = new Promise<bool>();
   if (onComplete != null) _promise.Done(r => onComplete());
   if (onError != null) _promise.Fail(onError);
 }
コード例 #13
0
        public IPromise<string> GetJsonString()
        {
            var promise = new Promise<string> ();

            using (var client = new WebClient())
            {

                if (this.headers != null) {
                    foreach(KeyValuePair<string, string> h in this.headers){
                        client.Headers.Add(h.Key, h.Value);
                    }
                }

                client.DownloadStringCompleted +=
                    (s, ev) =>
                {
                    if (ev.Error != null){
                        promise.Reject(ev.Error);
                    } else {
                        promise.Resolve(ev.Result);
                    }
                };

                client.DownloadStringAsync(new Uri(this.url), null);
            }
            return promise;
        }
コード例 #14
0
        public IPromise<string> GET(Dictionary<string, string> parameters)
        {
            if (parameters == null) {
                throw new ArgumentNullException ();
            }

            var promise = new Promise<string> ();

            using(var client = new WebClient()){

                if (this.headers != null) {
                    foreach(KeyValuePair<string, string> h in this.headers){
                        client.Headers.Add(h.Key, h.Value);
                    }
                }

                client.DownloadStringCompleted +=
                    (s, ev) =>
                {
                    if (ev.Error != null){
                        promise.Reject(ev.Error);
                    } else {
                        promise.Resolve(ev.Result);
                    }
                };

                client.DownloadStringAsync(new Uri(this.url + "?" + PromisedRequest.Helpers.GenerateQueryString(parameters)), null);

            }
            return promise;
        }
コード例 #15
0
		public Promise LoadSettings(string studentId)
		{
			Promise promise = new Promise();

			try
			{
				Uri serverUri = new Uri(appSettings.ServerURI, UriKind.RelativeOrAbsolute);
				Uri restUri = new Uri(serverUri, "rest/");

				CourseSettingsRepository repo = new CourseSettingsRepository(restUri);
				if (repo == null)
				{
					throw new Exception("CourseSettingsRepository is not initialized.");
				}

				repo.GetByKey("studentid/", studentId, (CourseSettingsRepository.Response response) =>
				{
					if (response.Success)
					{
						promise.Resolve(response.Item);
					}
					else
					{
						promise.Reject(new Exception(response.Error));
					}
				});                  
			}
			catch (Exception e)
			{
				promise.Reject(e);
			}

			return promise;
		}
コード例 #16
0
 public void TestBasicPromise()
 {
     Promise<int> p1 = new Promise<int>(cb => cb(null, 5));
     bool test = false;
     p1.Success(s => test = true);
     p1.Success(s => Assert.AreEqual(s, 5));
     Assert.IsTrue(test);
 }
コード例 #17
0
ファイル: PromiseTest.cs プロジェクト: jedahu/Jib
 public void Signalled_Promise_throws_exception_on_Signal(object value)
 {
     var p = new Promise<object>();
     p.Signal(value);
     Assert.Throws<InvalidOperationException>(
         () => p.Signal(value),
         "Cannot signal fulfilled Promise.");
 }
コード例 #18
0
ファイル: InventorySlot.cs プロジェクト: craus/UnityTest
 public IPromise Ready() {
     if (started) {
         return Promise.Resolved();
     }
     var result = new Promise();
     onStart += result.Resolve;
     return result.WithName(string.Format("Inventory slot ready: {0}", name));
 }
コード例 #19
0
ファイル: 2.1.cs プロジェクト: avenema/C-Sharp-Promise
            public void _must_not_transition_to_any_other_state()
            {
                var rejectedPromise = new Promise<object>();
                rejectedPromise.Reject(new Exception());

                Assert.Throws<ApplicationException>(() => rejectedPromise.Resolve(new object()));

                Assert.Equal(PromiseState.Rejected, rejectedPromise.CurState);
            }
コード例 #20
0
ファイル: PromiseTests.cs プロジェクト: zon/cardinal
		public void exception_is_thrown_for_resolve_after_reject() {
			var promise = new Promise<int>();

			promise.Reject(new ApplicationException());

			Assert.Throws<ApplicationException>(() =>
				promise.Resolve(5)
			);
		}
コード例 #21
0
ファイル: ShopService.cs プロジェクト: kicholen/SpaceShooter
    IPromise BuyGems(ShopModel model)
    {
        promise = new Promise();

        if (iapService.IsInitialized())
            iapService.BuyConsumableProduct(model.googleId);
        else
            promise.Reject(new Exception());
        return promise;
    }
コード例 #22
0
        public void CanResolvePromiseAndTriggerThenHandler()
        {
            var promise = new Promise();
            var completed = 0;

            promise.Then(() => ++completed);
            promise.Resolve();

            Assert.AreEqual(1, completed);
        }
コード例 #23
0
        public void ExceptionIsThrownForResolveAfterReject()
        {
            var promise = new Promise<int>();

            promise.Reject(new ApplicationException());

            Assert.Throws<ApplicationException>(() =>
                promise.Resolve(5)
            );
        }
コード例 #24
0
        public void can_handle_Done_onResolved()
        {
            var promise = new Promise();
            var callback = 0;

            promise.Done(() => ++callback);

            promise.Resolve();

            Assert.Equal(1, callback);
        }
コード例 #25
0
ファイル: 2.1.cs プロジェクト: avenema/C-Sharp-Promise
		public void When_pending_a_promise_may_transition_to_either_the_fulfilled_or_rejected_state()
        {
            var pendingPromise1 = new Promise<object>();
            Assert.Equal(PromiseState.Pending, pendingPromise1.CurState);
            pendingPromise1.Resolve(new object());
            Assert.Equal(PromiseState.Resolved, pendingPromise1.CurState);
        
            var pendingPromise2 = new Promise<object>();
            Assert.Equal(PromiseState.Pending, pendingPromise2.CurState);
            pendingPromise2.Reject(new Exception());
            Assert.Equal(PromiseState.Rejected, pendingPromise2.CurState);
        }
コード例 #26
0
ファイル: BonusService.cs プロジェクト: kicholen/SpaceShooter
 public IPromise LoadBonuses()
 {
     Promise promise = new Promise();
     wwwService.Send<GetBonuses>(new GetBonuses(), (request) => {
         bonuses = request.Bonuses;
         replaceOrAddBonuses(bonuses);
         promise.Resolve();
     }, (error) => {
         promise.Reject(new Exception(error));
     });
     return promise;
 }
コード例 #27
0
        public void can_resolve_promise_and_trigger_then_handler()
        {
            var promise = new Promise();

            var completed = 0;

            promise.Then(() => ++completed);

            promise.Resolve();

            Assert.Equal(1, completed);
        }
コード例 #28
0
ファイル: TileWorks.cs プロジェクト: FatihBAKIR/GGJ2016
    void Ascend()
    {
        _state = ChangeState.Ascending;
        _t = 0;
        _to = Grid.CoordToPosition(_tile.Coordinate) + (_tile.Elevation * Vector3.up);
        _from = transform.position;

        _colorFrom = GetComponent<Renderer>().material.color;
        _colorTo = Color.white;

        Level.CurrentLevel.AddPromise(_tilePromise = new Promise());
    }
コード例 #29
0
ファイル: PathService.cs プロジェクト: kicholen/SpaceShooter
 public IPromise LoadPaths()
 {
     Promise promise = new Promise();
     wwwService.Send<GetPaths>(new GetPaths(), (request) => {
         paths = request.Paths;
         replaceOrAddPaths(paths);
         promise.Resolve();
      }, (error) => {
          promise.Reject(new Exception(error));
      });
     return promise;
 }
コード例 #30
0
ファイル: TileWorks.cs プロジェクト: FatihBAKIR/GGJ2016
    public void Descend()
    {
        _state = ChangeState.Descending;
        _t = 0;
        _from = transform.position;
        _to = transform.position - Vector3.up * 10;

        _colorFrom = GetComponent<Renderer>().material.color;
        _colorTo = Color.black;

        Level.CurrentLevel.AddPromise(_tilePromise = new Promise());
    }
コード例 #31
0
 protected override void Reinitialize <T>(FactoryObjectParams assetParams, FactoryObject item, Promise <T> assetReadyPromise)
 {
     item.Reinitialize(assetParams, assetReadyPromise);
 }
コード例 #32
0
 public override void Reinitialize <T>(FactoryObjectParams assetParams, Promise <T> assetReadyPromise)
 {
     _assetParams = assetParams;
     assetReadyPromise.Resolve(this as T);
 }
コード例 #33
0
 public IPromise FlowPromise()
 {
     Event?.Invoke();
     return(Promise.Resolved());
 }
コード例 #34
0
ファイル: ASync.cs プロジェクト: Marwan0/tlplib
 public static IEnumerator WWWEnumerator(WWW www, Promise <Either <Cancelled, Either <WWWError, WWW> > > promise) =>
 WWWEnumerator(www).afterThis(() => promise.complete(
                                  Either <Cancelled, Either <WWWError, WWW> > .Right(www.toEither())
                                  ));
コード例 #35
0
 private void ContinueWithRepaint(Promise promise)
 {
     this.Repaint();
 }
コード例 #36
0
        /// <summary>
        /// Gets an object's ID given an object's screen position.
        /// </summary>
        /// <param name="x">The object's X position.</param>
        /// <param name="y">The object's Y position.</param>
        /// <param name="gd">GraphicsDevice instance.</param>
        /// <param name="state">WorldState instance.</param>
        /// <returns>Object's ID if the object was found at the given position.</returns>
        public short GetObjectIDAtScreenPos(int x, int y, GraphicsDevice gd, WorldState state)
        {
            /** Draw all objects to a texture as their IDs **/
            var oldCenter = state.CenterTile;
            var tileOff   = state.WorldSpace.GetTileFromScreen(new Vector2(x, y));

            state.CenterTile += tileOff;
            var pxOffset = state.WorldSpace.GetScreenOffset();
            var _2d      = state._2D;
            Promise <Texture2D> bufferTexture = null;

            var worldBounds = new Rectangle((-pxOffset).ToPoint(), new Point(1, 1));

            state.TempDraw      = true;
            state._2D.OBJIDMode = true;
            state._3D.OBJIDMode = true;
            using (var buffer = state._2D.WithBuffer(BUFFER_OBJID, ref bufferTexture))
            {
                _2d.SetScroll(-pxOffset);

                while (buffer.NextPass())
                {
                    foreach (var obj in Blueprint.Objects)
                    {
                        var tilePosition = obj.Position;

                        if (obj.Level != state.Level)
                        {
                            continue;
                        }

                        var oPx = state.WorldSpace.GetScreenFromTile(tilePosition);
                        obj.ValidateSprite(state);
                        var offBound = new Rectangle(obj.Bounding.Location + oPx.ToPoint(), obj.Bounding.Size);
                        if (!offBound.Intersects(worldBounds))
                        {
                            continue;
                        }

                        var renderInfo = GetRenderInfo(obj);

                        _2d.OffsetPixel(oPx);
                        _2d.OffsetTile(tilePosition);
                        _2d.SetObjID(obj.ObjectID);
                        obj.Draw(gd, state);
                    }

                    state._3D.Begin(gd);
                    foreach (var avatar in Blueprint.Avatars)
                    {
                        _2d.OffsetPixel(state.WorldSpace.GetScreenFromTile(avatar.Position));
                        _2d.OffsetTile(avatar.Position);
                        avatar.Draw(gd, state);
                    }
                    state._3D.End();
                }
            }
            state._3D.OBJIDMode = false;
            state._2D.OBJIDMode = false;
            state.TempDraw      = false;
            state.CenterTile    = oldCenter;

            var tex = bufferTexture.Get();

            Color[] data = new Color[1];
            tex.GetData <Color>(data);
            var f = Vector3.Dot(new Vector3(data[0].R / 255.0f, data[0].G / 255.0f, data[0].B / 255.0f), new Vector3(1.0f, 1 / 255.0f, 1 / 65025.0f));

            return((short)Math.Round(f * 65535f));
        }
コード例 #37
0
        /// <summary>
        /// Prep work before screen is painted
        /// </summary>
        /// <param name="gd"></param>
        /// <param name="state"></param>
        public virtual void PreDraw(GraphicsDevice gd, WorldState state)
        {
            //var oht = state.BaseHeight;
            //state.BaseHeight = 0;
            var pxOffset = -state.WorldSpace.GetScreenOffset();
            //state.BaseHeight = oht;
            var damage = Blueprint.Damage;
            var _2d    = state._2D;

            /**
             * Tasks:
             *  If zoom or rotation has changed, redraw all static layers
             *  If scroll has changed, redraw static layer if the scroll is outwith the buffered region
             *  If architecture has changed, redraw appropriate static layer
             *  If there is a new object in the static layer, redraw the static layer
             *  If an objects in the static layer has changed, redraw the static layer and move the object to the dynamic layer
             *  If wall visibility has changed, redraw wall layer (should think about how this works with breakthrough wall mode
             */

            var im = state.ThisFrameImmediate;
            var redrawStaticObjects = im;
            var redrawFloor         = im;
            var redrawWall          = im;

            var recacheWalls   = false;
            var recacheCutaway = false;
            var recacheFloors  = false;
            var recacheTerrain = false;
            var recacheObjects = false;
            var drawImmediate  = false;

            var lightChangeType = 0;

            if (TicksSinceLight++ > 60 * 4)
            {
                damage.Add(new BlueprintDamage(BlueprintDamageType.OUTDOORS_LIGHTING_CHANGED));
            }

            WorldObjectRenderInfo info = null;

            foreach (var item in damage)
            {
                switch (item.Type)
                {
                case BlueprintDamageType.OPENGL_SECOND_DRAW:
                    recacheFloors = true;
                    break;

                case BlueprintDamageType.ROTATE:
                case BlueprintDamageType.ZOOM:
                case BlueprintDamageType.LEVEL_CHANGED:
                    recacheObjects = true;
                    recacheWalls   = true;
                    recacheFloors  = true;
                    if (item.Type != BlueprintDamageType.OPENGL_SECOND_DRAW && !FSOEnvironment.DirectX)
                    {
                        //need to draw one frame after this in opengl.
                        //to mitigate a problem with floor content not setting to "wrap" mode
                        GameThread.NextUpdate(x =>
                        {
                            Blueprint.Damage.Add(new BlueprintDamage(BlueprintDamageType.OPENGL_SECOND_DRAW));
                        });
                    }
                    break;

                case BlueprintDamageType.SCROLL:
                    if (StaticObjects == null || StaticObjects.PxOffset != GetScrollIncrement(pxOffset, state))
                    {
                        redrawFloor         = true;
                        redrawWall          = true;
                        redrawStaticObjects = true;
                    }
                    break;

                case BlueprintDamageType.PRECISE_ZOOM:
                    drawImmediate = true;
                    redrawFloor   = redrawWall = redrawStaticObjects = true;
                    break;

                case BlueprintDamageType.LIGHTING_CHANGED:
                    if (lightChangeType >= 2)
                    {
                        break;
                    }
                    var room = (ushort)item.TileX;
                    redrawFloor         = true;
                    redrawWall          = true;
                    redrawStaticObjects = true;

                    state.Light?.InvalidateRoom(room);
                    Blueprint.GenerateRoomLights();
                    state.OutsideColor   = Blueprint.RoomColors[1];
                    state._3D.RoomLights = Blueprint.RoomColors;
                    state.OutsidePx.SetData(new Color[] { new Color(Blueprint.OutsideColor, (Blueprint.OutsideColor.R + Blueprint.OutsideColor.G + Blueprint.OutsideColor.B) / (255 * 3f)) });
                    if (state.AmbientLight != null)
                    {
                        state.AmbientLight.SetData(Blueprint.RoomColors);
                    }
                    TicksSinceLight = 0;
                    break;

                case BlueprintDamageType.OUTDOORS_LIGHTING_CHANGED:
                    if (lightChangeType >= 1)
                    {
                        break;
                    }
                    lightChangeType     = 1;
                    redrawFloor         = true;
                    redrawWall          = true;
                    redrawStaticObjects = true;

                    Blueprint.GenerateRoomLights();
                    state.OutsideColor   = Blueprint.RoomColors[1];
                    state._3D.RoomLights = Blueprint.RoomColors;
                    state.OutsidePx.SetData(new Color[] { new Color(Blueprint.OutsideColor, (Blueprint.OutsideColor.R + Blueprint.OutsideColor.G + Blueprint.OutsideColor.B) / (255 * 3f)) });
                    if (state.AmbientLight != null)
                    {
                        state.AmbientLight.SetData(Blueprint.RoomColors);
                    }
                    state.Light?.InvalidateOutdoors();

                    TicksSinceLight = 0;
                    break;

                case BlueprintDamageType.OBJECT_MOVE:
                    /** Redraw if its in static layer **/
                    info = GetRenderInfo(item.Component);
                    if (info.Layer == WorldObjectRenderLayer.STATIC)
                    {
                        recacheObjects = true;
                        info.Layer     = WorldObjectRenderLayer.DYNAMIC;
                    }
                    if (item.Component is ObjectComponent)
                    {
                        ((ObjectComponent)item.Component).DynamicCounter = 0;
                    }
                    break;

                case BlueprintDamageType.OBJECT_GRAPHIC_CHANGE:
                    /** Redraw if its in static layer **/
                    info = GetRenderInfo(item.Component);
                    if (info.Layer == WorldObjectRenderLayer.STATIC)
                    {
                        recacheObjects = true;
                        info.Layer     = WorldObjectRenderLayer.DYNAMIC;
                    }
                    if (item.Component is ObjectComponent)
                    {
                        ((ObjectComponent)item.Component).DynamicCounter = 0;
                    }
                    break;

                case BlueprintDamageType.OBJECT_RETURN_TO_STATIC:
                    info = GetRenderInfo(item.Component);
                    if (info.Layer == WorldObjectRenderLayer.DYNAMIC)
                    {
                        recacheObjects = true;
                        info.Layer     = WorldObjectRenderLayer.STATIC;
                    }
                    break;

                case BlueprintDamageType.WALL_CUT_CHANGED:
                    recacheCutaway = true;
                    break;

                case BlueprintDamageType.ROOF_STYLE_CHANGED:
                    Blueprint.RoofComp.StyleDirty = true;
                    break;

                case BlueprintDamageType.ROOM_CHANGED:
                    for (sbyte i = 0; i < Blueprint.RoomMap.Length; i++)
                    {
                        state.Rooms.SetRoomMap(i, Blueprint.RoomMap[i]);
                    }
                    if (state.Light != null)
                    {
                        if (lightChangeType < 2)
                        {
                            lightChangeType = 2;
                            state.Light.InvalidateAll();
                        }
                    }
                    Blueprint.Indoors             = null;
                    Blueprint.RoofComp.ShapeDirty = true;
                    break;

                case BlueprintDamageType.FLOOR_CHANGED:
                case BlueprintDamageType.WALL_CHANGED:
                    //recacheTerrain = true;
                    recacheFloors = true;
                    recacheWalls  = true;
                    Blueprint.RoofComp.ShapeDirty = true;
                    break;
                }
            }
            if (recacheFloors || recacheTerrain)
            {
                redrawFloor = true;
            }
            if (recacheWalls || recacheCutaway)
            {
                redrawWall = true;
            }
            if (recacheObjects)
            {
                redrawStaticObjects = true;
            }
            damage.Clear();

            //scroll buffer loads in increments of SCROLL_BUFFER
            var newOff    = GetScrollIncrement(pxOffset, state);
            var oldCenter = state.CenterTile;

            state.CenterTile += state.WorldSpace.GetTileFromScreen(newOff - pxOffset); //offset the scroll to the position of the scroll buffer.
            var tileOffset = state.CenterTile;

            pxOffset = newOff;

            if (recacheTerrain)
            {
                Blueprint.Terrain.RegenTerrain(gd, Blueprint);
            }

            if (recacheWalls)
            {
                Blueprint.WCRC?.Generate(gd, state, false);
            }
            else if (recacheCutaway)
            {
                Blueprint.WCRC?.Generate(gd, state, true);
            }

            state.Light?.ParseInvalidated((sbyte)(state.Level + ((state.DrawRoofs) ? 1 : 0)), state);

            if (recacheWalls || recacheCutaway)
            {
                _2d.Pause();
                _2d.Resume(); //clear the sprite buffer before we begin drawing what we're going to cache
                Blueprint.WallComp.Draw(gd, state);
                ClearDrawBuffer(StaticWallCache);
                state.PrepareLighting();
                _2d.End(StaticWallCache, true);
            }

            if (recacheFloors)
            {
                _2d.Pause();
                _2d.Resume(); //clear the sprite buffer before we begin drawing what we're going to cache
                //Blueprint.FloorComp.Draw(gd, state);
                Blueprint.FloorGeom.FullReset(gd, state.BuildMode > 1);
                ClearDrawBuffer(StaticFloorCache);
                _2d.End(StaticFloorCache, true);
            }

            if (recacheObjects)
            {
                _2d.Pause();
                _2d.Resume();

                foreach (var obj in Blueprint.Objects)
                {
                    if (obj.Level > state.Level)
                    {
                        continue;
                    }
                    var renderInfo = GetRenderInfo(obj);
                    if (renderInfo.Layer == WorldObjectRenderLayer.STATIC)
                    {
                        var tilePosition = obj.Position;
                        _2d.OffsetPixel(state.WorldSpace.GetScreenFromTile(tilePosition));
                        _2d.OffsetTile(tilePosition);
                        _2d.SetObjID(obj.ObjectID);
                        obj.Draw(gd, state);
                    }
                }
                ClearDrawBuffer(StaticObjectsCache);
                _2d.End(StaticObjectsCache, true);
            }

            if (!drawImmediate)
            {
                state.PrepareLighting();

                if (redrawStaticObjects || redrawFloor || redrawWall)
                {
                    /** Draw static objects to a texture **/
                    Promise <Texture2D> bufferTexture = null;
                    Promise <Texture2D> depthTexture  = null;
                    using (var buffer = state._2D.WithBuffer(BUFFER_STATIC, ref bufferTexture, BUFFER_STATIC_DEPTH, ref depthTexture))
                    {
                        while (buffer.NextPass())
                        {
                            DrawFloorBuf(gd, state, pxOffset);
                            DrawWallBuf(gd, state, pxOffset);
                            DrawObjBuf(gd, state, pxOffset);
                        }
                    }
                    StaticObjects = new ScrollBuffer(bufferTexture.Get(), depthTexture.Get(), newOff, new Vector3(tileOffset, 0));
                }
            }
            //state._2D.PreciseZoom = state.PreciseZoom;
            state.CenterTile = oldCenter; //revert to our real scroll position

            state.ThisFrameImmediate = drawImmediate;
        }
コード例 #38
0
        protected override Future <object> DoStart()
        {
            var promise = new Promise <object>();

            try
            {
                Pipe              = new NamedPipe(PipeName, Server);
                Pipe.OnConnected += () =>
                {
                    var handler = OnPipeConnected;
                    if (handler != null)
                    {
                        handler();
                    }
                };
                Pipe.OnReadDataBuffer += (dataBuffer) =>
                {
                    RaiseFramePayload(dataBuffer);
                };

                if (StartAsync)
                {
                    Task ready;
                    if (Server)
                    {
                        ready = Pipe.WaitForConnectionAsync();
                    }
                    else
                    {
                        ready = Pipe.ConnectAsync();
                    }

                    Task.Run(async() =>
                    {
                        await ready.ConfigureAwait(false);

                        ReadStreamHeader();

                        Pipe.StartReading(ReadFrameHeader);
                    });

                    promise.Resolve(null);
                }
                else
                {
                    Task.Run(async() =>
                    {
                        try
                        {
                            if (Server)
                            {
                                await Pipe.WaitForConnectionAsync();
                            }
                            else
                            {
                                await Pipe.ConnectAsync();
                            }

                            ReadStreamHeader();

                            Pipe.StartReading(ReadFrameHeader);

                            promise.Resolve(null);
                        }
                        catch (Exception ex)
                        {
                            promise.Reject(ex);
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                promise.Reject(ex);
            }
            return(promise);
        }
コード例 #39
0
        private IPromise <string> LoginAmlCall(bool async)
        {
            var result = new Promise <string>();

            result.CancelTarget(
                Process(new Command("<Item/>").WithAction(CommandAction.ValidateUser), async)
                .Progress(result.Notify)
                .Done(r =>
            {
                string xml;
                using (var reader = new StreamReader(r))
                {
                    xml = reader.ReadToEnd();
                }

                var root     = XElement.Parse(xml);
                var data     = root.DescendantsAndSelf("Result").FirstOrDefault();
                var afNs     = (XNamespace)"http://www.aras.com/InnovatorFault";
                var authNode = root.DescendantsAndSelf(afNs + "supported_authentication_schema").FirstOrDefault();
                if (authNode != null &&
                    authNode.Element(afNs + "schema")?.Attribute("mode")?.Value == "SHA256" &&
                    _authenticator is LegacyAuthenticator legacy)
                {
                    legacy.HashFunction = ElementFactory.Local.CalcSha256;
                    // Switch from MD5 hashing to SHA256
                    LoginAmlCall(async)
                    .Done(result.Resolve)
                    .Fail(result.Reject);
                }
                else if (data == null)
                {
                    var res = ElementFactory.Local.FromXml(xml);
                    var ex  = res.Exception ?? ElementFactory.Local.ServerException("Failed to login");
                    ex.SetDetails(Database, "<Item/>");

                    Database      = null;
                    _httpUsername = null;
                    result.Reject(ex);
                }
                else
                {
                    foreach (var elem in data.Elements())
                    {
                        switch (elem.Name.LocalName)
                        {
                        case "id":
                            UserId = elem.Value;
                            break;

                        case "login_name":
                            _httpUsername = elem.Value;
                            break;

                        case "database":
                            Database = elem.Value;
                            break;

                        case "i18nsessioncontext":
                            _context.DefaultLanguageCode   = elem.Element("default_language_code").Value;
                            _context.DefaultLanguageSuffix = elem.Element("default_language_suffix").Value;
                            _context.LanguageCode          = elem.Element("language_code").Value;
                            _context.LanguageSuffix        = elem.Element("language_suffix").Value;
                            _context.Locale   = elem.Element("locale").Value;
                            _context.TimeZone = elem.Element("time_zone").Value;
                            break;

                        case "ServerInfo":
                            foreach (var info in elem.Elements())
                            {
                                if (info.Name.LocalName == "Version")
                                {
                                    Version = new Version(info.Value);
                                }

                                if (!string.IsNullOrEmpty(elem.Value))
                                {
                                    _serverInfo.Add(new KeyValuePair <string, string>("ServerInfo/" + elem.Name.LocalName, elem.Value));
                                }
                            }
                            break;

                        default:
                            if (!string.IsNullOrEmpty(elem.Value))
                            {
                                _serverInfo.Add(new KeyValuePair <string, string>(elem.Name.LocalName, elem.Value));
                            }
                            break;
                        }
                    }

                    _vaultConn.InitializeStrategy();
                    result.Resolve(UserId);
                }
            }).Fail(ex =>
            {
                Database      = null;
                _httpUsername = null;
                result.Reject(ex);
            }));
            return(result);
        }
コード例 #40
0
        /// <summary>
        /// Gets an object group's thumbnail provided an array of objects.
        /// </summary>
        /// <param name="objects">The object components to draw.</param>
        /// <param name="gd">GraphicsDevice instance.</param>
        /// <param name="state">WorldState instance.</param>
        /// <returns>Object's ID if the object was found at the given position.</returns>
        public Texture2D GetObjectThumb(ObjectComponent[] objects, Vector3[] positions, GraphicsDevice gd, WorldState state)
        {
            var oldZoom     = state.Zoom;
            var oldRotation = state.Rotation;
            /** Center average position **/
            Vector3 average = new Vector3();

            for (int i = 0; i < positions.Length; i++)
            {
                average += positions[i];
            }
            average /= positions.Length;

            state.SilentZoom     = WorldZoom.Near;
            state.SilentRotation = WorldRotation.BottomRight;
            state.WorldSpace.Invalidate();
            state.InvalidateCamera();
            state.TempDraw = true;
            var pxOffset = new Vector2(442, 275) - state.WorldSpace.GetScreenFromTile(average);

            var _2d = state._2D;
            Promise <Texture2D> bufferTexture = null;
            Promise <Texture2D> depthTexture  = null;

            state._2D.OBJIDMode = false;
            Rectangle bounds = new Rectangle();

            using (var buffer = state._2D.WithBuffer(BUFFER_THUMB, ref bufferTexture, BUFFER_THUMB_DEPTH, ref depthTexture))
            {
                _2d.SetScroll(new Vector2());
                while (buffer.NextPass())
                {
                    for (int i = 0; i < objects.Length; i++)
                    {
                        var obj          = objects[i];
                        var tilePosition = positions[i];

                        //we need to trick the object into believing it is in a set world state.
                        var oldObjRot = obj.Direction;
                        var oldRoom   = obj.Room;

                        obj.Direction        = Direction.NORTH;
                        obj.Room             = 65535;
                        state.SilentZoom     = WorldZoom.Near;
                        state.SilentRotation = WorldRotation.BottomRight;
                        obj.OnRotationChanged(state);
                        obj.OnZoomChanged(state);

                        _2d.OffsetPixel(state.WorldSpace.GetScreenFromTile(tilePosition) + pxOffset);
                        _2d.OffsetTile(tilePosition);
                        _2d.SetObjID(obj.ObjectID);
                        obj.Draw(gd, state);

                        //return everything to normal
                        obj.Direction        = oldObjRot;
                        obj.Room             = oldRoom;
                        state.SilentZoom     = oldZoom;
                        state.SilentRotation = oldRotation;
                        obj.OnRotationChanged(state);
                        obj.OnZoomChanged(state);
                    }
                    bounds = _2d.GetSpriteListBounds();
                }
            }
            bounds.X = Math.Max(0, Math.Min(1023, bounds.X));
            bounds.Y = Math.Max(0, Math.Min(1023, bounds.Y));
            if (bounds.Width + bounds.X > 1024)
            {
                bounds.Width = 1024 - bounds.X;
            }
            if (bounds.Height + bounds.Y > 1024)
            {
                bounds.Height = 1024 - bounds.Y;
            }

            //return things to normal
            state.WorldSpace.Invalidate();
            state.InvalidateCamera();
            state.TempDraw = false;

            var tex = bufferTexture.Get();

            return(TextureUtils.Clip(gd, tex, bounds));
        }
コード例 #41
0
        protected void OnGUI()
        {
            if (this.columns == null)
            {
                return;
            }

            if (Event.current.type == EventType.repaint)
            {
                this.UpdateColumnWidths();
            }

            GUI.enabled = this.updatePromise == null && EditorApplication.isCompiling == false;

            var headerStyle = new GUIStyle(GUIStyle.none)
            {
                clipping  = TextClipping.Clip,
                fontStyle = FontStyle.Bold,
                normal    =
                {
                    background = Texture2D.whiteTexture
                }
            };

            var cellStyle = new GUIStyle(GUIStyle.none)
            {
                clipping = TextClipping.Clip,
                normal   =
                {
                    background = Texture2D.whiteTexture
                }
            };

            // paddings
            GUILayout.BeginHorizontal(GUILayout.Width(this.position.width - this.padding.x - this.padding.width));
            GUILayout.Space(this.padding.x);
            GUILayout.BeginVertical(GUILayout.Width(this.position.height - this.padding.y - this.padding.height));
            GUILayout.Space(this.padding.y);

            // render headers
            GUILayout.BeginHorizontal(headerStyle);
            foreach (var column in this.columns)
            {
                GUILayout.Label(column.Title, GUILayout.Width(column.Width));
            }
            GUILayout.EndHorizontal();
            EditorGUILayout.Separator();
            // render rows
            foreach (var row in this.rows)
            {
                if (row.Disabled)
                {
                    continue;
                }

                GUILayout.BeginHorizontal(cellStyle);
                foreach (var column in this.columns)
                {
                    column.Renderer(row, column.Width);
                }
                GUILayout.EndHorizontal();
            }

            EditorGUILayout.Separator();
            GUILayout.BeginHorizontal();
            GUILayout.Label(this.updateStatus ?? string.Empty);
            EditorGUILayout.Space();
            var wasEnabled = GUI.enabled;

            GUI.enabled = wasEnabled && this.rows.All(r => r.CurrentVersion.IsCompleted && r.AllBuilds.IsCompleted) && !EditorApplication.isCompiling;
            var actionText = this.rows.Any(r => r.Action != DeploymentAction.ACTION_SKIP) ? Resources.UI_UNITYPLUGIN_WINDOW_UPDATE_UPDATE_BUTTON : Resources.UI_UNITYPLUGIN_ABOUT_CLOSE_BUTTON;

            if (this.updatePromise == null && GUILayout.Button(actionText, GUILayout.Width(80)))
            {
                if (actionText == Resources.UI_UNITYPLUGIN_ABOUT_CLOSE_BUTTON)
                {
                    this.Close();
                    return;
                }

                this.updatePromise = new Coroutine <object>(this.PerformUpdateAsync());
                this.updatePromise.ContinueWith(p =>
                {
                    if (p.HasErrors)
                    {
                        this.updateStatus = Resources.UI_UNITYPLUGIN_WINDOW_UPDATE_ERROR_MESSAGE + ": " + p.Error.Unwrap().Message;
                        Debug.LogError("An update process has ended with error." + Environment.NewLine + p.Error.Unwrap());
                        Menu.FocusConsoleWindow();
                    }
                    this.Repaint();
                });
            }
            GUI.enabled = wasEnabled;
            GUILayout.EndHorizontal();

            // paddings
            GUILayout.EndVertical();
            GUILayout.EndHorizontal();

            GUILayoutUtility.GetRect(1, 1, 1, 1);
            if (Event.current.type == EventType.repaint && GUILayoutUtility.GetLastRect().y > 0)
            {
                var newRect = GUILayoutUtility.GetLastRect();
                this.position = new Rect(this.position.position, new Vector2(this.position.width, newRect.y + 7));
                this.minSize  = new Vector2(this.minSize.x, this.position.height);
                this.maxSize  = new Vector2(this.maxSize.x, this.position.height);
            }

            GUI.enabled = true;
        }
コード例 #42
0
        /// <summary>
        /// Prep work before screen is painted
        /// </summary>
        /// <param name="gd"></param>
        /// <param name="state"></param>
        public void PreDraw(GraphicsDevice gd, WorldState state)
        {
            var pxOffset = -state.WorldSpace.GetScreenOffset();
            var damage   = Blueprint.Damage;
            var _2d      = state._2D;

            /**
             * Tasks:
             *  If zoom or rotation has changed, redraw all static layers
             *  If scroll has changed, redraw static layer if the scroll is outwith the buffered region
             *  If architecture has changed, redraw appropriate static layer
             *  If there is a new object in the static layer, redraw the static layer
             *  If an objects in the static layer has changed, redraw the static layer and move the object to the dynamic layer
             *  If wall visibility has changed, redraw wall layer (should think about how this works with breakthrough wall mode
             */

            var redrawStaticObjects = false;
            var redrawFloor         = false;
            var redrawWall          = false;

            var recacheWalls   = false;
            var recacheFloors  = false;
            var recacheTerrain = false;
            var recacheObjects = false;

            if (TicksSinceLight++ > 60 * 4)
            {
                damage.Add(new BlueprintDamage(BlueprintDamageType.LIGHTING_CHANGED));
            }

            WorldObjectRenderInfo info = null;

            foreach (var item in damage)
            {
                switch (item.Type)
                {
                case BlueprintDamageType.ROTATE:
                case BlueprintDamageType.ZOOM:
                case BlueprintDamageType.LEVEL_CHANGED:
                    recacheObjects = true;
                    recacheWalls   = true;
                    recacheFloors  = true;
                    recacheTerrain = true;
                    break;

                case BlueprintDamageType.SCROLL:
                    if (StaticObjects == null || StaticObjects.PxOffset != GetScrollIncrement(pxOffset))
                    {
                        redrawFloor         = true;
                        redrawWall          = true;
                        redrawStaticObjects = true;
                    }
                    break;

                case BlueprintDamageType.LIGHTING_CHANGED:
                    redrawFloor         = true;
                    redrawWall          = true;
                    redrawStaticObjects = true;

                    Blueprint.GenerateRoomLights();
                    state.OutsideColor   = Blueprint.RoomColors[1];
                    state._3D.RoomLights = Blueprint.RoomColors;
                    state._2D.AmbientLight.SetData(Blueprint.RoomColors);
                    TicksSinceLight = 0;
                    break;

                case BlueprintDamageType.OBJECT_MOVE:
                    /** Redraw if its in static layer **/
                    info = GetRenderInfo(item.Component);
                    if (info.Layer == WorldObjectRenderLayer.STATIC)
                    {
                        recacheObjects = true;
                        info.Layer     = WorldObjectRenderLayer.DYNAMIC;
                    }
                    if (item.Component is ObjectComponent)
                    {
                        ((ObjectComponent)item.Component).DynamicCounter = 0;
                    }
                    break;

                case BlueprintDamageType.OBJECT_GRAPHIC_CHANGE:
                    /** Redraw if its in static layer **/
                    info = GetRenderInfo(item.Component);
                    if (info.Layer == WorldObjectRenderLayer.STATIC)
                    {
                        recacheObjects = true;
                        info.Layer     = WorldObjectRenderLayer.DYNAMIC;
                    }
                    if (item.Component is ObjectComponent)
                    {
                        ((ObjectComponent)item.Component).DynamicCounter = 0;
                    }
                    break;

                case BlueprintDamageType.OBJECT_RETURN_TO_STATIC:
                    info = GetRenderInfo(item.Component);
                    if (info.Layer == WorldObjectRenderLayer.DYNAMIC)
                    {
                        recacheObjects = true;
                        info.Layer     = WorldObjectRenderLayer.STATIC;
                    }
                    break;

                case BlueprintDamageType.WALL_CUT_CHANGED:
                    recacheWalls = true;
                    break;

                case BlueprintDamageType.FLOOR_CHANGED:
                case BlueprintDamageType.WALL_CHANGED:
                    recacheTerrain = true;
                    recacheFloors  = true;
                    recacheWalls   = true;
                    break;
                }
                if (recacheFloors || recacheTerrain)
                {
                    redrawFloor = true;
                }
                if (recacheWalls)
                {
                    redrawWall = true;
                }
                if (recacheObjects)
                {
                    redrawStaticObjects = true;
                }
            }
            damage.Clear();

            var tileOffset = state.WorldSpace.GetTileFromScreen(-pxOffset);
            //scroll buffer loads in increments of SCROLL_BUFFER
            var newOff    = GetScrollIncrement(pxOffset);
            var oldCenter = state.CenterTile;

            state.CenterTile += state.WorldSpace.GetTileFromScreen(newOff - pxOffset); //offset the scroll to the position of the scroll buffer.
            tileOffset        = state.CenterTile;

            pxOffset = newOff;

            if (recacheTerrain)
            {
                Blueprint.Terrain.RegenTerrain(gd, state, Blueprint);
            }

            if (recacheWalls)
            {
                _2d.Pause();
                _2d.Resume(); //clear the sprite buffer before we begin drawing what we're going to cache
                Blueprint.WallComp.Draw(gd, state);
                ClearDrawBuffer(StaticWallCache);
                _2d.End(StaticWallCache, true);
            }

            if (recacheFloors)
            {
                _2d.Pause();
                _2d.Resume(); //clear the sprite buffer before we begin drawing what we're going to cache
                Blueprint.FloorComp.Draw(gd, state);
                ClearDrawBuffer(StaticFloorCache);
                _2d.End(StaticFloorCache, true);
            }

            if (redrawFloor)
            {
                /** Draw archetecture to a texture **/
                Promise <Texture2D> bufferTexture = null;
                Promise <Texture2D> depthTexture  = null;
                using (var buffer = state._2D.WithBuffer(BUFFER_FLOOR_PIXEL, ref bufferTexture, BUFFER_FLOOR_DEPTH, ref depthTexture))
                {
                    _2d.SetScroll(pxOffset);
                    while (buffer.NextPass())
                    {
                        _2d.RenderCache(StaticFloorCache);
                        Blueprint.Terrain.DepthMode = _2d.OutputDepth;
                        Blueprint.Terrain.Draw(gd, state);
                    }
                }
                StaticFloor = new ScrollBuffer(bufferTexture.Get(), depthTexture.Get(), pxOffset, new Vector3(tileOffset, 0));
            }

            if (redrawWall)
            {
                Promise <Texture2D> bufferTexture = null;
                Promise <Texture2D> depthTexture  = null;
                using (var buffer = state._2D.WithBuffer(BUFFER_WALL_PIXEL, ref bufferTexture, BUFFER_WALL_DEPTH, ref depthTexture))
                {
                    _2d.SetScroll(pxOffset);
                    while (buffer.NextPass())
                    {
                        _2d.RenderCache(StaticWallCache);
                    }
                }
                StaticWall = new ScrollBuffer(bufferTexture.Get(), depthTexture.Get(), pxOffset, new Vector3(tileOffset, 0));
            }

            if (recacheObjects)
            {
                _2d.Pause();
                _2d.Resume();

                foreach (var obj in Blueprint.Objects)
                {
                    if (obj.Level > state.Level)
                    {
                        continue;
                    }
                    var renderInfo = GetRenderInfo(obj);
                    if (renderInfo.Layer == WorldObjectRenderLayer.STATIC)
                    {
                        var tilePosition = obj.Position;
                        _2d.OffsetPixel(state.WorldSpace.GetScreenFromTile(tilePosition));
                        _2d.OffsetTile(tilePosition);
                        _2d.SetObjID(obj.ObjectID);
                        obj.Draw(gd, state);
                    }
                }
                ClearDrawBuffer(StaticObjectsCache);
                _2d.End(StaticObjectsCache, true);
            }

            if (redrawStaticObjects)
            {
                /** Draw static objects to a texture **/
                Promise <Texture2D> bufferTexture = null;
                Promise <Texture2D> depthTexture  = null;
                using (var buffer = state._2D.WithBuffer(BUFFER_STATIC_OBJECTS_PIXEL, ref bufferTexture, BUFFER_STATIC_OBJECTS_DEPTH, ref depthTexture))
                {
                    _2d.SetScroll(pxOffset);
                    while (buffer.NextPass())
                    {
                        _2d.RenderCache(StaticObjectsCache);
                    }
                }
                StaticObjects = new ScrollBuffer(bufferTexture.Get(), depthTexture.Get(), pxOffset, new Vector3(tileOffset, 0));
            }
            state.CenterTile = oldCenter; //revert to our real scroll position
        }
コード例 #43
0
        public IEnumerable PerformUpdateAsync()
        {
            var deploymentActions = new List <DeploymentAction>();

            try
            {
                // downloading
                for (var i = 0; i < this.rows.Length; i++)
                {
                    var row = this.rows[i];
                    if (row.Disabled || row.Action == DeploymentAction.ACTION_SKIP)
                    {
                        continue;
                    }

                    var progressCallback = this.GetProgressReportFor(row, i + 1, this.rows.Length);
                    var downloadVersion  = default(SemanticVersion);
                    if (row.Action == DeploymentAction.ACTION_DOWNLOAD || row.Action == DeploymentAction.ACTION_UPDATE)
                    {
                        downloadVersion = row.SelectedVersion;
                    }
                    else if (row.Action == DeploymentAction.ACTION_REPAIR)
                    {
                        downloadVersion = row.CurrentVersion.GetResult();
                    }

                    if (row.Id == ProductInformation.PRODUCT_CHARON)
                    {
                        deploymentActions.Add(new CharonDeploymentAction(downloadVersion, progressCallback));
                    }
                    else
                    {
                        deploymentActions.Add(new LibraryDeploymentAction(row.Id, downloadVersion, row.Location, progressCallback));
                    }
                }

                if (deploymentActions.Count == 0)
                {
                    yield break;
                }

                // call prepare
                yield return(Promise.WhenAll(deploymentActions.ConvertAll(a => a.Prepare()).ToArray()).IgnoreFault());

                // call deploy
                yield return(Promise.WhenAll(deploymentActions.ConvertAll(a => a.Complete()).ToArray()).IgnoreFault());

                foreach (var forceReImportPath in deploymentActions.SelectMany(a => a.ChangedAssets))
                {
                    AssetDatabase.ImportAsset(forceReImportPath, ImportAssetOptions.ForceUpdate);
                }

                this.updateStatus = Resources.UI_UNITYPLUGIN_PROGRESS_DONE;
            }
            finally
            {
                foreach (var deploymentAction in deploymentActions)
                {
                    deploymentAction.CleanUp();
                }
            }

            this.Close();

            // re-load window if not 'Close' button was pressed
            if (this.rows.All(r => r.Action == DeploymentAction.ACTION_SKIP) == false)
            {
                Promise.Delayed(TimeSpan.FromSeconds(1)).ContinueWith(_ => EditorWindow.GetWindow <UpdateWindow>(utility: true));
            }
        }
コード例 #44
0
        public override Widget build(BuildContext context)
        {
            JPushPlugin.context = context;
            return(new WillPopScope(
                       onWillPop: () => {
                var promise = new Promise <bool>();
                if (LoginScreen.navigator?.canPop() ?? false)
                {
                    LoginScreen.navigator.pop();
                    promise.Resolve(false);
                }
                else if (Screen.orientation != ScreenOrientation.Portrait)
                {
                    //视频全屏时禁止物理返回按钮
                    EventBus.publish(EventBusConstant.fullScreen, new List <object> {
                        true
                    });
                    promise.Resolve(false);
                }
                else if (navigator.canPop())
                {
                    navigator.pop();
                    promise.Resolve(false);
                }
                else
                {
                    if (Application.platform == RuntimePlatform.Android)
                    {
                        if (this._exitApp)
                        {
                            CustomToast.hidden();
                            promise.Resolve(true);
                            if (this._timer != null)
                            {
                                this._timer.Dispose();
                                this._timer = null;
                            }
                        }
                        else
                        {
                            this._exitApp = true;
                            CustomToast.show(new CustomToastItem(
                                                 context: context,
                                                 "再按一次退出",
                                                 TimeSpan.FromMilliseconds(2000)
                                                 ));
                            this._timer = Window.instance.run(TimeSpan.FromMilliseconds(2000),
                                                              () => { this._exitApp = false; });
                            promise.Resolve(false);
                        }
                    }
                    else
                    {
                        promise.Resolve(true);
                    }
                }

                return promise;
            },
                       child: new Navigator(
                           key: globalKey,
                           observers: new List <NavigatorObserver> {
                _routeObserve
            },
                           onGenerateRoute: settings => {
                return new PageRouteBuilder(
                    settings: settings,
                    (context1, animation, secondaryAnimation) => mainRoutes[settings.name](context1),
                    (context1, animation, secondaryAnimation, child) => {
                    if (fullScreenRoutes.ContainsKey(settings.name))
                    {
                        return new ModalPageTransition(
                            routeAnimation: animation,
                            child: child
                            );
                    }

                    return new PushPageTransition(
                        routeAnimation: animation,
                        child: child
                        );
                }
                    );
            }
                           )
                       ));
        }
コード例 #45
0
ファイル: Deferrer.cs プロジェクト: benlesh/ALE
 public Deferrer(Promise promise)
 {
     Promise = promise;
 }
コード例 #46
0
        /// <summary>
        /// Gets the current lot's thumbnail.
        /// </summary>
        /// <param name="objects">The object components to draw.</param>
        /// <param name="gd">GraphicsDevice instance.</param>
        /// <param name="state">WorldState instance.</param>
        /// <returns>Object's ID if the object was found at the given position.</returns>
        public virtual Texture2D GetLotThumb(GraphicsDevice gd, WorldState state, Action <Texture2D> rooflessCallback)
        {
            if (!(state.Camera is WorldCamera))
            {
                return(new Texture2D(gd, 8, 8));
            }
            var oldZoom           = state.Zoom;
            var oldRotation       = state.Rotation;
            var oldLevel          = state.Level;
            var oldCutaway        = Blueprint.Cutaway;
            var wCam              = (WorldCamera)state.Camera;
            var oldViewDimensions = wCam.ViewDimensions;
            //wCam.ViewDimensions = new Vector2(-1, -1);
            var oldPreciseZoom = state.PreciseZoom;

            //full invalidation because we must recalculate all object sprites. slow but necessary!
            state.Zoom            = WorldZoom.Far;
            state.Rotation        = WorldRotation.TopLeft;
            state.Level           = Blueprint.Stories;
            state.PreciseZoom     = 1 / 4f;
            state._2D.PreciseZoom = state.PreciseZoom;
            state.WorldSpace.Invalidate();
            state.InvalidateCamera();

            var oldCenter = state.CenterTile;

            state.CenterTile  = Blueprint.GetThumbCenterTile(state);
            state.CenterTile -= state.WorldSpace.GetTileFromScreen(new Vector2((576 - state.WorldSpace.WorldPxWidth) * 4, (576 - state.WorldSpace.WorldPxHeight) * 4) / 2);
            var pxOffset = -state.WorldSpace.GetScreenOffset();

            state.TempDraw    = true;
            Blueprint.Cutaway = new bool[Blueprint.Cutaway.Length];

            var _2d = state._2D;

            state.ClearLighting(false);
            Promise <Texture2D> bufferTexture = null;
            var lastLight = state.OutsideColor;

            state.OutsideColor  = Color.White;
            state._2D.OBJIDMode = false;
            using (var buffer = state._2D.WithBuffer(BUFFER_LOTTHUMB, ref bufferTexture))
            {
                _2d.SetScroll(pxOffset);
                while (buffer.NextPass())
                {
                    _2d.Pause();
                    _2d.Resume();
                    Blueprint.FloorGeom.SliceReset(gd, new Rectangle(6, 6, Blueprint.Width - 13, Blueprint.Height - 13));
                    //Blueprint.SetLightColor(WorldContent.GrassEffect, Color.White, Color.White);
                    Blueprint.Terrain.Draw(gd, state);
                    Blueprint.Terrain.DrawMask(gd, state, state.Camera.View, state.Camera.Projection);
                    Blueprint.WallComp.Draw(gd, state);
                    _2d.Pause();
                    _2d.Resume();
                    foreach (var obj in Blueprint.Objects)
                    {
                        var renderInfo   = GetRenderInfo(obj);
                        var tilePosition = obj.Position;
                        _2d.OffsetPixel(state.WorldSpace.GetScreenFromTile(tilePosition));
                        _2d.OffsetTile(tilePosition);
                        obj.Draw(gd, state);
                    }
                    _2d.Pause();
                    _2d.Resume();
                    rooflessCallback?.Invoke(bufferTexture.Get());
                    Blueprint.RoofComp.Draw(gd, state);
                }
            }

            Blueprint.Damage.Add(new BlueprintDamage(BlueprintDamageType.LIGHTING_CHANGED));
            Blueprint.Damage.Add(new BlueprintDamage(BlueprintDamageType.FLOOR_CHANGED));
            //return things to normal
            //state.PrepareLighting();
            state.OutsideColor = lastLight;
            state.PreciseZoom  = oldPreciseZoom;
            state.WorldSpace.Invalidate();
            state.InvalidateCamera();
            wCam.ViewDimensions = oldViewDimensions;
            state.TempDraw      = false;
            state.CenterTile    = oldCenter;

            state.Zoom        = oldZoom;
            state.Rotation    = oldRotation;
            state.Level       = oldLevel;
            Blueprint.Cutaway = oldCutaway;

            var tex = bufferTexture.Get();

            return(tex); //TextureUtils.Clip(gd, tex, bounds);
        }
コード例 #47
0
 public SqlQueryHolderTask(SqlQueryHolderBase holder)
 {
     _holder = holder;
     _result = new Promise <SqlQueryHolderBase>();
 }
コード例 #48
0
 /// <summary>
 /// Attempt to update or install necessary XR software. Will only be called if
 /// <see cref="XRSessionSubsystemDescriptor.supportsInstall"/> is true.
 /// </summary>
 /// <returns></returns>
 public virtual Promise <SessionInstallationStatus> InstallAsync()
 {
     return(Promise <SessionInstallationStatus> .CreateResolvedPromise(SessionInstallationStatus.ErrorInstallNotSupported));
 }
コード例 #49
0
 /// <summary>
 /// Get the session's availability, such as whether the platform supports XR.
 /// </summary>
 /// <returns>A <see cref="Promise{T}"/> that the caller can yield on until availability is determined.</returns>
 public virtual Promise <SessionAvailability> GetAvailabilityAsync()
 {
     return(Promise <SessionAvailability> .CreateResolvedPromise(SessionAvailability.None));
 }
コード例 #50
0
 public static void exists(Promise promise, string directoryPath)
 {
     promise.Resolve(new object[] { System.IO.Directory.Exists(directoryPath) });
 }
コード例 #51
0
 public static void tryCompleteError <Val>(this Promise <Try <Val> > p, Exception error)
 {
     p.tryComplete(F.err <Val>(error));
 }
コード例 #52
0
 public static void tryCompleteError <Err, Val>(this Promise <Either <Err, Val> > p, Err error)
 {
     p.tryComplete(Either <Err, Val> .Left(error));
 }
コード例 #53
0
 public static void tryCompleteSuccess <Err, Val>(this Promise <Either <Err, Val> > p, Val value)
 {
     p.tryComplete(Either <Err, Val> .Right(value));
 }
コード例 #54
0
 public static Future <A> async <A>(out Promise <A> promise) => Future <A> .async(out promise);
コード例 #55
0
        public IPromise <string> BuySmallGems()
        {
            // do stuff here

            return(Promise <string> .Resolved("some-receipt-id"));
        }
コード例 #56
0
 public static void tryCompleteSuccess <Val>(this Promise <Try <Val> > p, Val value)
 {
     p.tryComplete(F.scs(value));
 }
コード例 #57
0
ファイル: Router.cs プロジェクト: soulhez/ConnectAppCN
        public override Widget build(BuildContext context)
        {
            GlobalContext.context = context;
            return(new WillPopScope(
                       onWillPop: () => {
                TipMenu.dismiss();
                var promise = new Promise <bool>();
                if (LoginScreen.navigator?.canPop() ?? false)
                {
                    LoginScreen.navigator.pop();
                    promise.Resolve(false);
                }
                else if (Screen.orientation != ScreenOrientation.Portrait)
                {
                    //视频全屏时禁止物理返回按钮
                    EventBus.publish(sName: EventBusConstant.fullScreen, new List <object> {
                        true
                    });
                    promise.Resolve(false);
                }
                else if (navigator.canPop())
                {
                    navigator.pop();
                    promise.Resolve(false);
                }
                else
                {
                    if (Application.platform == RuntimePlatform.Android)
                    {
                        if (this._exitApp)
                        {
                            CustomToast.hidden();
                            promise.Resolve(true);
                            if (this._timer != null)
                            {
                                this._timer.Dispose();
                                this._timer = null;
                            }
                        }
                        else
                        {
                            this._exitApp = true;
                            CustomToast.show(new CustomToastItem(
                                                 context: context,
                                                 "再按一次退出",
                                                 TimeSpan.FromMilliseconds(2000)
                                                 ));
                            this._timer = Window.instance.run(TimeSpan.FromMilliseconds(2000),
                                                              () => { this._exitApp = false; });
                            promise.Resolve(false);
                        }
                    }
                    else
                    {
                        promise.Resolve(true);
                    }
                }

                return promise;
            },
                       child: new Navigator(
                           key: globalKey,
                           observers: new List <NavigatorObserver> {
                _routeObserve,
                _heroController
            },
                           onGenerateRoute: settings => new CustomPageRoute(
                               settings: settings,
                               fullscreenDialog: fullScreenRoutes.ContainsKey(key: settings.name),
                               builder: context1 => mainRoutes[key: settings.name](context: context1)
                               )
                           )
                       ));
        }
コード例 #58
0
ファイル: codec.cs プロジェクト: JC-ut0/CubeGame
 public static IPromise <Codec> getCodec(Image image)
 {
     return(Promise <Codec> .Resolved(new ImageCodec(image)));
 }
コード例 #59
0
ファイル: CharonCli.cs プロジェクト: shi377034/charon-unity3d
        internal static Promise <RequirementsCheckResult> CheckRequirementsAsync()
        {
            if (String.IsNullOrEmpty(Settings.CharonPath) || !File.Exists(Settings.CharonPath))
            {
                return(Promise.FromResult(RequirementsCheckResult.MissingExecutable));
            }

            var additionalChecks = new List <Promise <RequirementsCheckResult> >();

            if (RuntimeInformation.IsWindows)
            {
                if (DotNetRuntimeInformation.GetVersion() == null && (String.IsNullOrEmpty(MonoRuntimeInformation.MonoPath) ||
                                                                      File.Exists(MonoRuntimeInformation.MonoPath) == false))
                {
                    return(Promise.FromResult(RequirementsCheckResult.MissingRuntime));
                }
            }
            else
            {
                if (String.IsNullOrEmpty(MonoRuntimeInformation.MonoPath) || File.Exists(MonoRuntimeInformation.MonoPath) == false)
                {
                    return(Promise.FromResult(RequirementsCheckResult.MissingRuntime));
                }

                additionalChecks.Add(GetMonoVersionAsync().ContinueWith(getMonoVersion =>
                {
                    if (getMonoVersion.HasErrors || getMonoVersion.GetResult() == null || getMonoVersion.GetResult() < MinimalMonoVersion)
                    {
                        return(RequirementsCheckResult.MissingRuntime);
                    }
                    else
                    {
                        return(RequirementsCheckResult.Ok);
                    }
                }));
            }

            if (!String.IsNullOrEmpty(Settings.Current.EditorVersion))
            {
                additionalChecks.Add(GetVersionAsync().ContinueWith(getCharonVersion =>
                {
                    if (getCharonVersion.HasErrors || getCharonVersion.GetResult() == null ||
                        getCharonVersion.GetResult().ToString() != Settings.Current.EditorVersion)
                    {
                        return(RequirementsCheckResult.WrongVersion);
                    }
                    else
                    {
                        return(RequirementsCheckResult.Ok);
                    }
                }));
            }

            if (additionalChecks.Count == 0)
            {
                return(Promise.FromResult(RequirementsCheckResult.Ok));
            }
            else
            {
                return(Promise.WhenAll(additionalChecks.ToArray())
                       .ContinueWith(results => results.GetResult().FirstOrDefault(r => r != RequirementsCheckResult.Ok)));
            }
        }
コード例 #60
0
 protected virtual IPromise <string> OnCreate()
 {
     return(Promise <string> .Rejected(null));
 }