Example #1
0
    inline task<void> create_for_loop_task(T from_inclusive, T to_exclusive, std::function<task<void>(T&)> loop_function)
    {
        auto from_ = std::make_shared<T>(from_inclusive);

        return create_iterative_task([=]
        {
            auto task_ = loop_function(*from_.get());

            bool finished = false;

            ++*from_.get();

            if (*from_.get() >= to_exclusive)
            {
                finished = true;
            }

            return task_.then([=]
            {
                if(finished)
                {
                    return false;
                }
                
                return true;
            });
        });
    }
		R await(std::shared_future<R> t){
			PPL_HELPER_ENTER_EXIT;
			assert(co_->coroutine_caller_);
			auto co = co_;
			func_type retfunc([co, t](){
				auto sptr = co->shared_from_this();
				return then(t,[sptr](std::shared_future<R> et)->T{
					detail::ret_type ret;
					ret.eptr_ = nullptr;
					ret.pv_ = nullptr;
					ret.pv_ = &et;
					(*sptr->coroutine_)(&ret);
					try{
						func_type f(std::move(*static_cast<func_type*>(sptr->coroutine_->get())));
						return f().get();
					}
					catch (std::exception&){
						ret.eptr_ = std::current_exception();
						ret.pv_ = nullptr;
						(*sptr->coroutine_)(&ret);
						throw;
					}
				});
			});

			(*co_->coroutine_caller_)(&retfunc);
			return static_cast<detail::ret_type*>(co_->coroutine_caller_->get())->get<std::shared_future<R>>().get();
		}
Example #3
0
bool CWinRenderer::LoadCLUT()
{
  m_CLUTSize = 0;
  m_clutLoaded = false;

  auto loadLutTask = Concurrency::create_task([this]{
    // load 3DLUT data
    int clutSize, dataSize;
    if (!CColorManager::Get3dLutSize(CMS_DATA_FMT_RGBA, &clutSize, &dataSize))
      return 0;

    uint16_t* clutData = static_cast<uint16_t*>(_aligned_malloc(dataSize, 16));
    bool success = m_colorManager->GetVideo3dLut(m_iFlags, &m_cmsToken, CMS_DATA_FMT_RGBA, clutSize, clutData);
    if (success)
    {
      success = COutputShader::CreateCLUTView(clutSize, clutData, false, m_pCLUTView.ReleaseAndGetAddressOf());
    }
    else
      CLog::Log(LOGERROR, "%s: unable to loading the 3dlut data.", __FUNCTION__);

    _aligned_free(clutData);
    if (!success)
      return 0;

    return clutSize;
  });

  loadLutTask.then([&](int clutSize){
    m_CLUTSize = clutSize;
    if (m_outputShader)
        m_outputShader->SetCLUT(m_CLUTSize, m_pCLUTView.Get());
    m_clutLoaded = true;
  });
  return true;
}
Example #4
0
        void trigger_impl_future(std::true_type,
            typed_continuation<Result, RemoteResult>&& cont, F&& f, Ts&&... vs)
        {
            typedef
                typename std::is_same<RemoteResult, util::unused_type>::type
                is_void;

            auto result = util::invoke(std::forward<F>(f),
                std::forward<Ts>(vs)...);

            typedef typename hpx::util::decay<decltype(result)>::type future_type;

            if(result.is_ready())
            {
                detail::deferred_trigger<Result, RemoteResult>(
                    is_void(), std::move(cont), std::move(result));
                return;
            }

            void (*fun)(is_void, typed_continuation<Result, RemoteResult>&&,
                    future_type&&)
                = &detail::deferred_trigger<Result, RemoteResult, future_type>;

            result.then(
                hpx::util::bind(
                    hpx::util::one_shot(fun)
                  , is_void()
                  , std::move(cont) //-V575
                  , util::placeholders::_1
                )
            );
        }
Example #5
0
void initialize_contradiction_tactic() {
    register_tac(name{"tactic", "contradiction"},
                 [](type_checker &, elaborate_fn const &, expr const &, pos_info_provider const *) {
                     list<name> empty;
                     return then(orelse(intros_tactic(empty), id_tactic()), contradiction_tactic());
                 });
}
    VerEx & alt(const std::string & value) {
        if (prefixes.find("(") == std::string::npos) prefixes += "(";
        if (suffixes.find(")") == std::string::npos) suffixes = ")" + suffixes;

        add( ")|(" );
        return then(value);
    }
Example #7
0
int main() {
    auto ctx = tl::launch_local(1);
    auto stream = make_stream(10);
    auto result = stream.then(
        [] (FList<int>& x) { return sum_stream(x, 0); }
    ).unwrap().get();
    std::cout << "Total: " << result << std::endl;
}
int main()
{
    hpx::threads::executors::pool_executor executor("default");

    auto future = hpx::make_ready_future().share();

    future.then(executor, [](hpx::shared_future<void> future) { future.get(); });

    return 0;
}
Example #9
0
TEST(AsyncTest, asyncMultipThenValueOrder) {
  std::string order;
  std::thread::id mainThreadId = std::this_thread::get_id();

  std::shared_ptr<native::Loop> currLoop = native::Loop::Create();
  {
    auto async1 = native::async(currLoop, [&order, &mainThreadId]() {
      order += "1";
      std::thread::id currThreadId = std::this_thread::get_id();
      EXPECT_EQ(mainThreadId, currThreadId);
    });
    auto async2 = async1.then([&order, &mainThreadId]() {
      order += ",2";
      std::thread::id currThreadId = std::this_thread::get_id();
      EXPECT_EQ(mainThreadId, currThreadId);
    });
    async1.then([&order, &mainThreadId]() {
      order += ",21";
      std::thread::id currThreadId = std::this_thread::get_id();
      EXPECT_EQ(mainThreadId, currThreadId);
    });
    async2.then([&order, &mainThreadId] {
      order += ",3";
      std::thread::id currThreadId = std::this_thread::get_id();
      EXPECT_EQ(mainThreadId, currThreadId);
    });
    async2.then([&order, &mainThreadId]() {
      order += ",31";
      std::thread::id currThreadId = std::this_thread::get_id();
      EXPECT_EQ(mainThreadId, currThreadId);
    });
  }

  std::string expectedorder;
  EXPECT_EQ(order, expectedorder);

  currLoop->run();

  // Maybe this is an issue, for non async callback first are resolved dependences callbacks
  // An solution would be each callback from "then" to call async, this may resolve the issue
  expectedorder = "1,2,21,3,31";
  EXPECT_EQ(expectedorder, order);
}
 void
 on_chunk(const char *chunk,
          size_t size)
 {
     auto generator = parent().m_storage->read(
         "namespace",
         "key." + cocaine::framework::unpack<std::string>(chunk, size)
     );
     generator.then(std::bind(&on_event1::send_resp, shared_from_this(), std::placeholders::_1));
 }
Example #11
0
int main()
{
#if ! defined  BOOST_NO_CXX11_DECLTYPE && ! defined  BOOST_NO_CXX11_AUTO_DECLARATIONS
    boost::promise<void> test_promise;
    boost::future<void> test_future(test_promise.get_future());
    auto f1 = test_future.then(TestCallback());
    BOOST_STATIC_ASSERT(std::is_same<decltype(f1), boost::future<boost::future<void> > >::value);
    auto f2 = f1.then(TestCallback());
    BOOST_STATIC_ASSERT(std::is_same<decltype(f2), boost::future<boost::future<void> > >::value);
#endif
    return 0;
}
Example #12
0
void initialize_revert_tactic() {
    auto fn = [](type_checker &, elaborate_fn const &, expr const & e, pos_info_provider const *) {
        buffer<name> ns;
        get_tactic_id_list_elements(app_arg(e), ns, "invalid 'reverts' tactic, list of identifiers expected");
        tactic r = revert_tactic(ns[0]);
        for (unsigned i = 1; i < ns.size(); i++)
            r = then(revert_tactic(ns[i]), r);
        return r;
    };
    register_tac(get_tactic_revert_name(), fn);
    register_tac(get_tactic_reverts_name(), fn);
}
Example #13
0
void task_loop(std::shared_ptr<std::promise<void>> p, Body body) {
  auto s = body().share();
  then(s, [=](auto f) {
    try {
      if (f.get())
        task_loop(p, body);
      else
        p->set_value();
    } catch (...) {
    }
  });
}
Example #14
0
    /* Optimized interative_task_impl (http://pplpp.codeplex.com/SourceControl/latest#include/impl/pplppimplshare.h).  
       This version uses move semantics and std::bind to avoid copies and ref counting of captured objects.  A cleaner
       version can probably be made using generalized lambda capture, but many compilers don't support yet.
       Note that vanilla pplx does not have movable task_completion events or task_continuation_context. 
       Unlike the original interative_task_impl, this only exits the loop by exception */
    inline static void iterative_task_impl(
        task_completion_event<void> finished, 
        std::function<task<bool>()> body,
        cancellation_token          ct, 
        cancellation_token_source   cts, 
        task_continuation_context   context = task_continuation_context::use_default())
    {
        if (ct.is_canceled())
        {
            cts.cancel();
            return;
        }

        auto body_result_task = body();

        std::function<void(task<bool>)> b = std::bind([](
            task<bool>                  previous,
            task_completion_event<void> finished_,
            std::function<task<bool>()> body_,
            cancellation_token          ct_,
            cancellation_token_source   cts_,
            task_continuation_context   context_) mutable
        {
            try
            {
                auto continue_result = previous.get();

                if (!continue_result)
                {
                    finished_.set();
                    return;
                }

                iterative_task_impl(std::move(finished_),
                    std::move(body_),
                    std::move(ct_),
                    std::move(cts_),
                    std::move(context_));
            }
            catch (task_canceled)
            {
                cts_.cancel();
            }
            catch (...)
            {
                finished_.set_exception(std::current_exception());
            }

        }, std::placeholders::_1, std::move(finished), std::move(body), std::move(ct), std::move(cts), std::move(context));

        body_result_task.then(b, context);
    }
Example #15
0
    Promise<R> Core<T>::then(const std::function<Promise<R> (const T&)> &f) {
	auto defer = When::defer<R>();
	then([f, defer] (const T& value) mutable -> void {
		try {
		    defer.resolve(f(value));
		} catch (const std::exception& e) {
		    defer.reject(e.what());
		}
	    });
	otherwise([f, defer] (const std::string& err) mutable {
		defer.reject(err);
	    });
	return defer.promise();
   }
void get_system_time(uuid_time_t* uuid_time) {
    // REVISIT (fbrereto) : universal_time() is only available on the second_clock.
    //                      It would be nice if it was one on the microsec_clock.

    boost::posix_time::ptime then(boost::gregorian::date(1585, boost::date_time::Oct, 15));
#if BOOST_VERSION < 103300
    boost::posix_time::ptime now(boost::date_time::second_clock<
        boost::gregorian::date, boost::posix_time::ptime>::universal_time());
#else
    boost::posix_time::ptime now(
        boost::date_time::second_clock<boost::posix_time::ptime>::universal_time());
#endif
    *uuid_time = static_cast<uuid_time_t>((now - then).total_nanoseconds() /
                                          boost::posix_time::time_duration::ticks_per_second());
}
void ext_future_test()
{
	{
		auto f1 = ext::async(ext::launch::deferred, [] { return 12; });
		auto f2 = f1.then([](auto f)
		{
			auto val = f.get();
			return ext::async(ext::launch::deferred, [val] { return val * 2 + 3; });
		});

		auto fall = ext::when_all(f2.unwrap());
		ext::future<int> fi = std::get<0>(fall.get());
		assert(fi.get() == 12 * 2 + 3);
	}

}
ContestResultsApi::ContestResultsApi(ContestResults::Client resultsApi, PromiseConverter& converter)
    : resultsApi(resultsApi),
      converter(converter) {
    KJ_DBG("Created results API", this);

    auto resultsRequest = resultsApi.resultsRequest().send();

    converter.adopt(resultsRequest.then([this](capnp::Response<ContestResults::ResultsResults> results) {
        auto talliedOpinions = results.getResults();
        updateResults(talliedOpinions);
    }));

    auto subscribeRequest = resultsApi.subscribeRequest();
    subscribeRequest.setNotifier(kj::heap<ResultsNotifier>(*this));
    converter.adopt(subscribeRequest.send());
}
Example #19
0
	ext::future<void> thread_pool::set_nworkers(unsigned n)
	{
		std::unique_lock<std::mutex> lk(m_mutex);
		unsigned old_size = static_cast<unsigned>(m_workers.size());
		if (n == old_size) return ext::make_ready_future();

		auto first = m_workers.begin();
		auto last = m_workers.end();

		if (n > old_size - m_pending)
		{
			first = std::remove_if(last - m_pending, last, is_finished);
			m_pending = last - first;
			m_workers.resize(n + m_pending);

			first = m_workers.begin() + old_size;
			last = m_workers.end() - m_pending;

			std::move(first, first + m_pending, last);

			for (; first != last; ++first)
				*first = ext::make_intrusive<worker>(this);

			return ext::make_ready_future();
		}
		else
		{
			first += n;
			last -= m_pending;
			m_pending += old_size - n;

			auto func = [](const worker_ptr & wptr) { return ext::future<void>(wptr); };

			auto all = ext::when_all(
				boost::make_transform_iterator(first, func),
				boost::make_transform_iterator(last, func));

			for (auto it = first; it != last; ++it)
				(**it).stop_request();

			lk.unlock();
			m_event.notify_all();

			return all.then([](auto) {});
		}
	}
Example #20
0
void initialize_clear_tactic() {
    register_tac(get_tactic_clear_name(),
                 [](type_checker &, elaborate_fn const &, expr const & e, pos_info_provider const *) {
                     name n = tactic_expr_to_id(app_arg(e), "invalid 'clear' tactic, argument must be an identifier");
                     return clear_tactic(n);
                 });
    register_tac(get_tactic_clears_name(),
                 [](type_checker &, elaborate_fn const &, expr const & e, pos_info_provider const *) {
                     buffer<name> ns;
                     get_tactic_id_list_elements(app_arg(e), ns, "invalid 'clears' tactic, list of identifiers expected");
                     tactic r = clear_tactic(ns.back());
                     ns.pop_back();
                     while (!ns.empty()) {
                         r = then(clear_tactic(ns.back()), r);
                         ns.pop_back();
                     }
                     return r;
                 });
}
Example #21
0
// Low level interface
void Cpp2Channel::sendMessage(SendCallback* callback,
                              std::unique_ptr<folly::IOBuf>&& buf) {
    // Callback may be null.
    assert(buf);

    if (!transport_->good()) {
        VLOG(5) << "Channel is !good() in sendMessage";
        // Callback must be last thing in sendMessage, or use guard
        if (callback) {
            callback->messageSendError(
                folly::make_exception_wrapper<TTransportException>(
                    "Channel is !good()"));
        }
        return;
    }

    std::vector<SendCallback*> cbs;
    if (callback) {
        callback->sendQueued();
        cbs.push_back(callback);
    }
    sendCallbacks_.push_back(std::move(cbs));

    DestructorGuard dg(this);

    auto future = pipeline_->write(std::move(buf));
    future.then([this,dg](folly::Try<void>&& t) {
        if (t.withException<TTransportException>(
        [&](const TTransportException& ex) {
        writeError(0, ex);
        }) ||
        t.withException<std::exception>(
        [&](const std::exception& ex) {
            writeError(0, TTransportException(ex.what()));
        })) {
            return;
        }
        else {
            writeSuccess();
        }
    });
}
Example #22
0
	ext::future<void> thread_pool::stop()
	{
		std::unique_lock<std::mutex> lk(m_mutex);
		auto first = m_workers.begin();
		auto last = m_workers.end();

		// m_workers should not be cleared, so next call to stop will be aware of current workers
		// strictly speaking only finished workers can be cleared.

		auto func = [](const worker_ptr & wptr) { return ext::future<void>(wptr); };

		auto all = ext::when_all(
			boost::make_transform_iterator(first, func),
			boost::make_transform_iterator(last, func));

		for (auto it = first; it != last - m_pending; ++it)
			(**it).stop_request();

		lk.unlock();
		m_event.notify_all();

		return all.then([](auto) {});
	}
Example #23
0
void setup(){
    set_brief("Optional extras for a simple object");
    set_long(@LORIEL
Adding some weight:
within the setup function, set its size:

    set_size(1);

Adding a value:
first inherit the module M_VALUABLE
then (within setup) set the value

inherit M_VALUABLE;

    set_value(1);
LORIEL
    );
    set_exits( ([
	"west" : R + "object02",
	"corridor" : R + "corridor05",
      ]) );
    set_objects( ([
      ]) );
}
Example #24
0
// 根据制定的类型创建下载任务,返回任务处理http响应数据
task<HRESULT> WRTHttpRequest::DownloadAsync(PCWSTR httpMethod, 
											PCWSTR uri, 
											cancellation_token cancellationToken,
											PCWSTR contentType, 
											IStream* postStream, 
											uint64 postStreamSizeToSend)
{
	// 创建IXMLHTTPRequest2对象
    ComPtr<IXMLHTTPRequest2> xhr;
    CheckHResult(CoCreateInstance(CLSID_XmlHttpRequest, nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&xhr)));

    // 创建回调
    auto httpCallback = Make<HttpRequestCallback>(xhr.Get(),_response,cancellationToken);
    CheckHResult(httpCallback ? S_OK : E_OUTOFMEMORY);

    auto completionTask = create_task(httpCallback->GetCompletionEvent());

    // 创建请求
    CheckHResult(xhr->Open(httpMethod, uri, httpCallback.Get(), nullptr, nullptr, nullptr, nullptr));

    if (postStream != nullptr && contentType != nullptr)
    {
        CheckHResult(xhr->SetRequestHeader(L"Content-Type", contentType));
    }

    // 发送请求
    CheckHResult(xhr->Send(postStream, postStreamSizeToSend));

	// http请求完成时返回完成task,由于请求完成要调用回调方法,为了确保处理流程正确,特将回调方法作为参数传递进来
    return completionTask.then([this, httpCallback](HRESULT hr)
    {
		if(SUCCEEDED(hr))
			WRTHttpClient::getInstance()->response(_response);        	
        return hr;
    });
}
Example #25
0
// Get local time as milliseconds since 00:00:00, Jan 1st 1970
wxLongLong wxGetLocalTimeMillis()
{
    wxLongLong val = 1000l;

    // If possible, use a function which avoids conversions from
    // broken-up time structures to milliseconds

#if defined(__WXPALMOS__)
    DateTimeType thenst;
    thenst.second  = 0;
    thenst.minute  = 0;
    thenst.hour    = 0;
    thenst.day     = 1;
    thenst.month   = 1;
    thenst.year    = 1970;
    thenst.weekDay = 5;
    uint32_t now = TimGetSeconds();
    uint32_t then = TimDateTimeToSeconds (&thenst);
    return SysTimeToMilliSecs(SysTimeInSecs(now - then));
#elif defined(__WXMSW__) && (defined(__WINE__) || defined(__MWERKS__))
    // This should probably be the way all WXMSW compilers should do it
    // Go direct to the OS for time

    SYSTEMTIME thenst = { 1970, 1, 4, 1, 0, 0, 0, 0 };  // 00:00:00 Jan 1st 1970
    FILETIME thenft;
    SystemTimeToFileTime( &thenst, &thenft );
    wxLongLong then( thenft.dwHighDateTime, thenft.dwLowDateTime );   // time in 100 nanoseconds

    SYSTEMTIME nowst;
    GetLocalTime( &nowst );
    FILETIME nowft;
    SystemTimeToFileTime( &nowst, &nowft );
    wxLongLong now( nowft.dwHighDateTime, nowft.dwLowDateTime );   // time in 100 nanoseconds

    return ( now - then ) / 10000.0;  // time from 00:00:00 Jan 1st 1970 to now in milliseconds

#elif defined(HAVE_GETTIMEOFDAY)
    struct timeval tp;
    if ( wxGetTimeOfDay(&tp) != -1 )
    {
        val *= tp.tv_sec;
        return (val + (tp.tv_usec / 1000));
    }
    else
    {
        wxLogError(_("wxGetTimeOfDay failed."));
        return 0;
    }
#elif defined(HAVE_FTIME)
    struct timeb tp;

    // ftime() is void and not int in some mingw32 headers, so don't
    // test the return code (well, it shouldn't fail anyhow...)
    (void)::ftime(&tp);
    val *= tp.time;
    return (val + tp.millitm);
#else // no gettimeofday() nor ftime()
    // We use wxGetLocalTime() to get the seconds since
    // 00:00:00 Jan 1st 1970 and then whatever is available
    // to get millisecond resolution.
    //
    // NOTE that this might lead to a problem if the clocks
    // use different sources, so this approach should be
    // avoided where possible.

    val *= wxGetLocalTime();

// GRG: This will go soon as all WIN32 seem to have ftime
// JACS: unfortunately not. WinCE doesn't have it.
#if defined (__WIN32__)
    // If your platform/compiler needs to use two different functions
    // to get ms resolution, please do NOT just shut off these warnings,
    // drop me a line instead at <*****@*****.**>

    // FIXME
#ifndef __WXWINCE__
    #warning "Possible clock skew bug in wxGetLocalTimeMillis()!"
#endif

    SYSTEMTIME st;
    ::GetLocalTime(&st);
    val += st.wMilliseconds;
#else // !Win32
    // If your platform/compiler does not support ms resolution please
    // do NOT just shut off these warnings, drop me a line instead at
    // <*****@*****.**>

    #if defined(__VISUALC__) || defined (__WATCOMC__)
        #pragma message("wxStopWatch will be up to second resolution!")
    #elif defined(__BORLANDC__)
        #pragma message "wxStopWatch will be up to second resolution!"
    #else
        #warning "wxStopWatch will be up to second resolution!"
    #endif // compiler
#endif

    return val;

#endif // time functions
}
task<bool> SandboxJSExecutor::ConnectAsync(std::shared_ptr<SandboxEndpoint> endpoint,
    const std::function<void(std::string)>& errorCallback) {
  m_errorCallback = std::move(errorCallback);
  auto t = task_from_result();

  return t.then([=]() -> bool {
    int retryCount = ConnectRetryCount;
    while (true) {
      try {
        cancellation_token_source timer_cts;
        auto timeoutT = create_delayed_task(std::chrono::milliseconds(ConnectTimeoutMilliseconds), [=]() -> string {
          throw std::runtime_error("timeout");
        }, timer_cts.get_token());

        if (!IsConnected()) {
          try {
            m_sandboxEndpoint = nullptr;
          }
          catch (std::exception& /*e*/) {
            // Don't care what happens with the old client at this point
          }

          // TODO: Pass as param
          m_sandboxEndpoint = endpoint;

          m_sandboxEndpoint->RegisterReplyHandler([this](int64_t replyId) {
            OnReplyMessage(replyId);
          });

          m_sandboxEndpoint->RegisterNativeModuleCallHandler([this](folly::dynamic&& calls) {
            OnNativeModuleCallMessage(std::move(calls));
          });

          if (m_sandboxEndpoint->Start(EndpointType::Host))
          {
            SetState(State::Connected);
            timer_cts.cancel();
          }
        } else {
          PrepareJavaScriptRuntimeAsync().then([=](bool success) {
            if (success) {
              SetState(State::Running);
              timer_cts.cancel();
            } else {
              SetState(State::Error);
            }
          });
        }

        auto status = timeoutT.wait();

        if (status != canceled) {
          throw new std::exception("Timeout");
        }

        if (IsRunning()) {
          return true;
        }
      }
      catch (std::exception& /*e*/) {
        retryCount--;
        if (retryCount == 0) {
          m_errorCallback(IsConnected() ? "Timeout: preparing JS runtime" : "Timeout: Failed to connect to dev server");
          SetState(State::Error);
          return false;
        }
      }
    }
  });
}
Example #27
0
   OpenGL::OpenGL(ID3D11Device* device, ID3D11DeviceContext* context)
   {
      s_instance = this;
      _orthoLeft = 0;
      _orthoRight = 0;
      _orthoBottom = 0;
      _orthoTop = 0;

      _device = device;
      _context = context;
      _vertexBuffer = NULL;
      _currentTextureId = 0;
      _enableTexture2D = false;
      _batchCurrentTextureId = 0;
      _batchEnableTexture2D = false;
      _loadingComplete = false;
      _vertexBuilder = new VertexBuilder();
      _maxVertices = MaxBatchVertices;
      _firstDrawInFrame = false;

      _currentBatchVertex = 0;

      _enableScissoring = false;
      _scissorRect.left = 0;
      _scissorRect.right = 0;
      _scissorRect.top = 0;
      _scissorRect.bottom = 0;

      _vertexShader = NULL;
      _pixelShaderTexture = NULL;
      _pixelShaderColor = NULL;

      auto vsize = sizeof (this->_batchVertices);

      // Asynchronously load the vertex and pixel shaders
      auto loadVSTask = ReadDataAsync("OpenGLVS.cso");
      auto loadPSColorTask = ReadDataAsync("OpenGLColorPS.cso");
      auto loadPSTextureTask = ReadDataAsync("OpenGLTexturePS.cso");

      auto createVSTask = loadVSTask.then([this](ByteArray ba) {
         auto bytecodeVS = ba.data;
         ThrowIfFailed(
            _device->CreateVertexShader(
            bytecodeVS->Data,
            bytecodeVS->Length,
            nullptr,
            &_vertexShader
            )
            );

         const D3D11_INPUT_ELEMENT_DESC vertexDesc[] = 
         {
            { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,    0, 0,                            D3D11_INPUT_PER_VERTEX_DATA, 0 },
            { "COLOR",    0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
            { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,       0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
         }; 

         ThrowIfFailed(
            _device->CreateInputLayout(
            vertexDesc,
            ARRAYSIZE(vertexDesc),
            bytecodeVS->Data,
            bytecodeVS->Length,
            &_inputLayout
            )
            );
      });

      auto createPSColorTask = loadPSColorTask.then([this](ByteArray ba) {
         auto bytecodePS = ba.data;
         ThrowIfFailed(
            _device->CreatePixelShader(
            bytecodePS->Data,
            bytecodePS->Length,
            nullptr,
            &_pixelShaderColor
            )
            );
      });

      auto createPSTextureTask = loadPSTextureTask.then([this](ByteArray ba) {
         auto bytecodePS = ba.data;
         ThrowIfFailed(
            _device->CreatePixelShader(
            bytecodePS->Data,
            bytecodePS->Length,
            nullptr,
            &_pixelShaderTexture
            )
            );

         ThrowIfFailed(
            _device->CreateBuffer(
            &CD3D11_BUFFER_DESC(sizeof(ModelViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER),
            nullptr,
            &_constantBuffer
            ));
      });

      createPSTextureTask.then([this] () {
         _loadingComplete = true;
      });

      ZeroMemory(&_rasterizerDesc, sizeof(_rasterizerDesc));
      _rasterizerDesc.FillMode = D3D11_FILL_MODE::D3D11_FILL_SOLID;
      _rasterizerDesc.CullMode = D3D11_CULL_MODE::D3D11_CULL_NONE;
      _rasterizerDesc.FrontCounterClockwise = true;
      _rasterizerDesc.DepthBias = 0;
      _rasterizerDesc.SlopeScaledDepthBias = 0.f;
      _rasterizerDesc.DepthBiasClamp = 0.f;
      _rasterizerDesc.DepthClipEnable = true;
      _rasterizerDesc.ScissorEnable = false;
      _rasterizerDesc.MultisampleEnable = false;
      _rasterizerDesc.AntialiasedLineEnable = false;
      ID3D11RasterizerState* rasterizerState;
      _device->CreateRasterizerState(&_rasterizerDesc, &rasterizerState);
      _context->RSSetState(rasterizerState);

      // Push an identity matrix on the stack to start with
      DirectX::XMFLOAT4X4* matrix = new DirectX::XMFLOAT4X4();
      auto identity = DirectX::XMMatrixIdentity();
      DirectX::XMStoreFloat4x4(matrix, identity);
      _matrices.push(matrix);
   }
 VerEx & find(const std::string & value) {
     return then(value);
 }
Example #29
0
    void Core<T>::success(const std::function<void ()>& f) {
	then([f] (const T&) {
		f();
	    });
    }
Example #30
0
    Promise<bool> Core<T>::then(const std::function<void (const T&)> &f) {
	return then(std::function<bool (const T&)> ([f] (const T& value) {
		    f(value);
		    return true;
		}));
    }